chore: sync staging

This commit is contained in:
Esdras Renan 2025-11-10 01:57:45 -03:00
parent c5ddd54a3e
commit 561b19cf66
610 changed files with 105285 additions and 1206 deletions

View file

@ -1,12 +1,7 @@
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"
import { buildXlsxWorkbook } from "@/lib/xlsx"
import { buildBacklogWorkbook, createConvexContext } from "@/server/report-exporters"
export const runtime = "nodejs"
@ -16,98 +11,27 @@ export async function GET(request: Request) {
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 export", 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 companyId = searchParams.get("companyId") ?? undefined
const report = await client.query(api.reports.backlogOverview, {
const context = await createConvexContext({
tenantId,
viewerId: viewerId as unknown as Id<"users">,
range,
companyId: companyId as unknown as Id<"companies">,
name: session.user.name ?? session.user.email,
email: session.user.email,
avatarUrl: session.user.avatarUrl,
role: session.user.role.toUpperCase(),
})
const summaryRows: Array<Array<unknown>> = [
["Relatório", "Backlog"],
["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : "—"],
]
if (companyId) {
summaryRows.push(["EmpresaId", companyId])
}
summaryRows.push(["Chamados em aberto", report.totalOpen])
const artifact = await buildBacklogWorkbook(context, { range, companyId: companyId ?? undefined })
const distributionRows: Array<Array<unknown>> = []
const STATUS_PT: Record<string, string> = {
PENDING: "Pendentes",
AWAITING_ATTENDANCE: "Em andamento",
PAUSED: "Pausados",
RESOLVED: "Resolvidos",
}
for (const [status, total] of Object.entries(report.statusCounts)) {
distributionRows.push(["Status", STATUS_PT[status] ?? status, total])
}
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)) {
distributionRows.push(["Prioridade", PRIORITY_PT[priority] ?? priority, total])
}
for (const q of report.queueCounts) {
distributionRows.push(["Fila", q.name || q.id, q.total])
}
const workbook = buildXlsxWorkbook([
{
name: "Resumo",
headers: ["Item", "Valor"],
rows: summaryRows,
},
{
name: "Distribuições",
headers: ["Categoria", "Chave", "Total"],
rows: distributionRows,
},
])
const body = new Uint8Array(workbook)
return new NextResponse(body, {
return new NextResponse(artifact.buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="backlog-${tenantId}-${report.rangeDays ?? 'all'}d.xlsx"`,
"Content-Type": artifact.mimeType,
"Content-Disposition": `attachment; filename="${artifact.fileName}"`,
"Cache-Control": "no-store",
},
})

View file

@ -1,12 +1,7 @@
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"
import { buildXlsxWorkbook } from "@/lib/xlsx"
import { buildCsatWorkbook, createConvexContext } from "@/server/report-exporters"
export const runtime = "nodejs"
@ -16,90 +11,27 @@ export async function GET(request: Request) {
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 companyId = searchParams.get("companyId") ?? 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, {
const context = await createConvexContext({
tenantId,
name: session.user.name ?? session.user.email,
email: session.user.email,
avatarUrl: session.user.avatarUrl ?? undefined,
avatarUrl: session.user.avatarUrl,
role: session.user.role.toUpperCase(),
})
viewerId = ensuredUser?._id ?? null
} catch (error) {
console.error("Failed to synchronize user with Convex for CSAT export", 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 })
}
const artifact = await buildCsatWorkbook(context, { range, companyId: companyId ?? undefined })
try {
const report = await client.query(api.reports.csatOverview, {
tenantId,
viewerId: viewerId as unknown as Id<"users">,
range,
companyId: companyId as unknown as Id<"companies">,
})
const summaryRows: Array<Array<unknown>> = [
["Relatório", "CSAT"],
["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : range ?? "90d"],
]
if (companyId) {
summaryRows.push(["EmpresaId", companyId])
}
summaryRows.push(["CSAT médio", report.averageScore ?? "—"])
summaryRows.push(["Total de respostas", report.totalSurveys ?? 0])
const distributionRows: Array<Array<unknown>> = (report.distribution ?? []).map((entry) => [
entry.score,
entry.total,
])
const recentRows: Array<Array<unknown>> = (report.recent ?? []).map((item) => [
`#${item.reference}`,
item.score,
new Date(item.receivedAt).toISOString(),
])
const workbook = buildXlsxWorkbook([
{
name: "Resumo",
headers: ["Métrica", "Valor"],
rows: summaryRows,
},
{
name: "Distribuição",
headers: ["Nota", "Total"],
rows: distributionRows.length > 0 ? distributionRows : [["—", 0]],
},
{
name: "Respostas recentes",
headers: ["Ticket", "Nota", "Recebido em"],
rows: recentRows.length > 0 ? recentRows : [["—", "—", "—"]],
},
])
const body = new Uint8Array(workbook)
return new NextResponse(body, {
return new NextResponse(artifact.buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="csat-${tenantId}-${report.rangeDays ?? '90'}d.xlsx"`,
"Content-Type": artifact.mimeType,
"Content-Disposition": `attachment; filename="${artifact.fileName}"`,
"Cache-Control": "no-store",
},
})

View file

@ -1,104 +1,45 @@
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"
import { buildXlsxWorkbook } from "@/lib/xlsx"
import { buildHoursWorkbook, createConvexContext } from "@/server/report-exporters"
export const runtime = "nodejs"
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 q = searchParams.get("q")?.toLowerCase().trim() ?? ""
const companyId = searchParams.get("companyId") ?? ""
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, {
const context = await createConvexContext({
tenantId,
name: session.user.name ?? session.user.email,
email: session.user.email,
avatarUrl: session.user.avatarUrl ?? undefined,
avatarUrl: session.user.avatarUrl,
role: session.user.role.toUpperCase(),
})
viewerId = ensuredUser?._id ?? null
} catch {
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.hoursByClient, {
tenantId,
viewerId: viewerId as unknown as Id<"users">,
const artifact = await buildHoursWorkbook(context, {
range,
companyId: companyId || undefined,
search: q || undefined,
})
const summaryRows: Array<Array<unknown>> = [
["Relatório", "Horas por cliente"],
["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : range ?? "90d"],
]
if (q) summaryRows.push(["Filtro", q])
if (companyId) summaryRows.push(["EmpresaId", companyId])
summaryRows.push(["Total de clientes", (report.items as Array<unknown>).length])
type Item = { companyId: string; name: string; isAvulso: boolean; internalMs: number; externalMs: number; totalMs: number; contractedHoursPerMonth: number | null }
let items = (report.items as Item[])
if (companyId) items = items.filter((i) => String(i.companyId) === companyId)
if (q) items = items.filter((i) => i.name.toLowerCase().includes(q))
const dataRows = items.map((item) => {
const internalHours = item.internalMs / 3600000
const externalHours = item.externalMs / 3600000
const totalHours = item.totalMs / 3600000
const contracted = item.contractedHoursPerMonth
const usagePct = contracted ? (totalHours / contracted) * 100 : null
return [
item.name,
item.isAvulso ? "Sim" : "Não",
Number(internalHours.toFixed(2)),
Number(externalHours.toFixed(2)),
Number(totalHours.toFixed(2)),
contracted ?? null,
usagePct !== null ? Number(usagePct.toFixed(1)) : null,
]
})
const workbook = buildXlsxWorkbook([
{
name: "Resumo",
headers: ["Item", "Valor"],
rows: summaryRows,
},
{
name: "Clientes",
headers: ["Cliente", "Avulso", "Horas internas", "Horas externas", "Horas totais", "Horas contratadas/mês", "% uso"],
rows: dataRows.length > 0 ? dataRows : [["—", "—", 0, 0, 0, null, null]],
},
])
const body = new Uint8Array(workbook)
return new NextResponse(body, {
return new NextResponse(artifact.buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="hours-by-client-${tenantId}-${report.rangeDays ?? '90'}d${companyId ? `-${companyId}` : ''}${q ? `-${encodeURIComponent(q)}` : ''}.xlsx"`,
"Content-Type": artifact.mimeType,
"Content-Disposition": `attachment; filename="${artifact.fileName}"`,
"Cache-Control": "no-store",
},
})
} catch {
} catch (error) {
console.error("Falha ao gerar planilha de horas por cliente", error)
return NextResponse.json({ error: "Falha ao gerar planilha de horas por cliente" }, { status: 500 })
}
}

View file

@ -0,0 +1,160 @@
import { NextResponse } from "next/server"
import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"
import {
computeNextRunAt,
sanitizeRecipients,
sanitizeReportKeys,
serializeSchedule,
} from "@/server/report-schedule-service"
export const runtime = "nodejs"
export async function PATCH(request: Request, { params }: { params: { id: string } }) {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
const schedule = await prisma.reportExportSchedule.findFirst({
where: { id: params.id, tenantId },
})
if (!schedule) {
return NextResponse.json({ error: "Agendamento não encontrado" }, { status: 404 })
}
const payload = (await request.json().catch(() => null)) as Record<string, unknown> | null
if (!payload) {
return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
}
const data: Record<string, unknown> = {}
if (typeof payload.name === "string" && payload.name.trim().length > 0) {
data.name = payload.name.trim()
}
if (Array.isArray(payload.reportKeys)) {
const keys = sanitizeReportKeys(payload.reportKeys as string[])
if (!keys.length) {
return NextResponse.json({ error: "Selecione ao menos um relatório." }, { status: 400 })
}
data.reportKeys = keys
}
if (typeof payload.range === "string") {
data.range = payload.range
}
if (payload.companyId === null || typeof payload.companyId === "string") {
data.companyId = payload.companyId ?? null
}
if (payload.companyName === null || typeof payload.companyName === "string") {
data.companyName = payload.companyName ?? null
}
if (typeof payload.format === "string") {
data.format = payload.format
}
if (payload.recipients === null || Array.isArray(payload.recipients)) {
const recipients = sanitizeRecipients((payload.recipients as string[] | null) ?? [])
if (!recipients.length) {
return NextResponse.json({ error: "Informe ao menos um destinatário válido." }, { status: 400 })
}
data.recipients = recipients
}
let needsReschedule = false
if (typeof payload.frequency === "string") {
const frequency = payload.frequency.toLowerCase()
if (!["daily", "weekly", "monthly"].includes(frequency)) {
return NextResponse.json({ error: "Frequência inválida." }, { status: 400 })
}
data.frequency = frequency
needsReschedule = true
}
if (payload.dayOfWeek === null || typeof payload.dayOfWeek === "number") {
data.dayOfWeek = payload.dayOfWeek ?? null
needsReschedule = true
}
if (payload.dayOfMonth === null || typeof payload.dayOfMonth === "number") {
data.dayOfMonth = payload.dayOfMonth ?? null
needsReschedule = true
}
if (typeof payload.time === "string") {
const { hour, minute } = parseTime(payload.time)
data.hour = hour
data.minute = minute
needsReschedule = true
}
if (typeof payload.timezone === "string") {
data.timezone = payload.timezone
needsReschedule = true
}
if (typeof payload.status === "string") {
data.status = payload.status.toUpperCase() === "PAUSED" ? "PAUSED" : "ACTIVE"
if (data.status === "ACTIVE") {
needsReschedule = true
}
}
if (needsReschedule) {
const cronSource = {
frequency: (data.frequency as string) ?? schedule.frequency,
dayOfWeek: (data.dayOfWeek as number | undefined | null) ?? schedule.dayOfWeek,
dayOfMonth: (data.dayOfMonth as number | undefined | null) ?? schedule.dayOfMonth,
hour: (data.hour as number | undefined) ?? schedule.hour,
minute: (data.minute as number | undefined) ?? schedule.minute,
timezone: (data.timezone as string | undefined) ?? schedule.timezone,
}
data.nextRunAt =
data.status === "PAUSED"
? null
: computeNextRunAt(
{
frequency: cronSource.frequency as "daily" | "weekly" | "monthly",
dayOfWeek: cronSource.dayOfWeek,
dayOfMonth: cronSource.dayOfMonth,
hour: cronSource.hour,
minute: cronSource.minute,
timezone: cronSource.timezone,
},
new Date()
)
}
const updated = await prisma.reportExportSchedule.update({
where: { id: schedule.id },
data,
})
return NextResponse.json({
item: serializeSchedule(
{
...updated,
reportKeys: (updated.reportKeys as string[] | null) ?? [],
recipients: (updated.recipients as string[] | null) ?? [],
},
[]
),
})
}
export async function DELETE(_: Request, { params }: { params: { id: string } }) {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
await prisma.reportExportRun.deleteMany({ where: { scheduleId: params.id, tenantId } })
await prisma.reportExportSchedule.deleteMany({ where: { id: params.id, tenantId } })
return NextResponse.json({ success: true })
}
function parseTime(value: string) {
const match = value.match(/^(\d{1,2}):(\d{1,2})$/)
if (!match) return { hour: 8, minute: 0 }
const hour = Math.min(23, Math.max(0, Number(match[1])))
const minute = Math.min(59, Math.max(0, Number(match[2])))
return { hour, minute }
}

View file

@ -0,0 +1,146 @@
import { NextResponse } from "next/server"
import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"
import {
computeNextRunAt,
sanitizeRecipients,
sanitizeReportKeys,
serializeSchedule,
} from "@/server/report-schedule-service"
export const runtime = "nodejs"
export async function GET() {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
const [schedules, runs] = await Promise.all([
prisma.reportExportSchedule.findMany({
where: { tenantId },
orderBy: { createdAt: "desc" },
}),
prisma.reportExportRun.findMany({
where: { tenantId },
orderBy: { startedAt: "desc" },
take: 50,
}),
])
const runBySchedule = runs.reduce<Record<string, typeof runs>>((acc, run) => {
acc[run.scheduleId] = acc[run.scheduleId] ? [...acc[run.scheduleId], run] : [run]
return acc
}, {})
return NextResponse.json({
items: schedules.map((schedule) =>
serializeSchedule(
{
...schedule,
reportKeys: (schedule.reportKeys as string[] | null) ?? [],
recipients: (schedule.recipients as string[] | null) ?? [],
},
runBySchedule[schedule.id] ?? []
)
),
})
}
export async function POST(request: Request) {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
const payload = (await request.json().catch(() => null)) as
| {
name?: string
reportKeys?: string[]
range?: string
companyId?: string | null
companyName?: string | null
frequency?: "daily" | "weekly" | "monthly"
dayOfWeek?: number | null
dayOfMonth?: number | null
time?: string
timezone?: string
recipients?: string[]
format?: string
}
| null
if (!payload) {
return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
}
const name = payload.name?.trim()
if (!name) {
return NextResponse.json({ error: "Informe um nome para o agendamento." }, { status: 400 })
}
const reportKeys = sanitizeReportKeys(payload.reportKeys ?? [])
if (reportKeys.length === 0) {
return NextResponse.json({ error: "Selecione ao menos um relatório." }, { status: 400 })
}
const recipients = sanitizeRecipients(payload.recipients ?? [])
if (recipients.length === 0) {
return NextResponse.json({ error: "Informe ao menos um destinatário válido." }, { status: 400 })
}
const frequency = (payload.frequency ?? "weekly").toLowerCase() as "daily" | "weekly" | "monthly"
const { hour, minute } = parseTime(payload.time ?? "08:00")
const timezone = payload.timezone ?? "America/Sao_Paulo"
const nextRunAt = computeNextRunAt(
{
frequency,
dayOfWeek: payload.dayOfWeek,
dayOfMonth: payload.dayOfMonth,
hour,
minute,
timezone,
},
new Date()
)
const schedule = await prisma.reportExportSchedule.create({
data: {
tenantId,
name,
reportKeys,
range: payload.range ?? "30d",
companyId: payload.companyId ?? null,
companyName: payload.companyName ?? null,
format: payload.format ?? "xlsx",
frequency,
dayOfWeek: payload.dayOfWeek ?? null,
dayOfMonth: payload.dayOfMonth ?? null,
hour,
minute,
timezone,
recipients,
status: "ACTIVE",
createdBy: session.user.id,
nextRunAt,
},
})
return NextResponse.json({
item: serializeSchedule(
{ ...schedule, reportKeys, recipients },
[]
),
})
}
function parseTime(value: string) {
const match = value.match(/^(\d{1,2}):(\d{1,2})$/)
if (!match) return { hour: 8, minute: 0 }
const hour = Math.min(23, Math.max(0, Number(match[1])))
const minute = Math.min(59, Math.max(0, Number(match[2])))
return { hour, minute }
}

View file

@ -0,0 +1,56 @@
import { NextResponse } from "next/server"
import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { env } from "@/lib/env"
import { runReportSchedules } from "@/server/report-schedule-runner"
export const runtime = "nodejs"
export async function POST(request: Request) {
const payload = (await request.json().catch(() => ({}))) as {
scheduleId?: string
tenantId?: string
}
const session = await assertAdminSession()
const cronAuthorized = isCronRequest(request)
if (!session && !cronAuthorized) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session ? session.user.tenantId ?? DEFAULT_TENANT_ID : payload.tenantId
const result = await runReportSchedules({
tenantId,
scheduleId: payload.scheduleId,
initiatedBy: session
? {
userId: session.user.id,
name: session.user.name,
email: session.user.email,
avatarUrl: session.user.avatarUrl,
role: session.user.role,
}
: {
name: "Report Scheduler",
email: env.SMTP?.from ?? "scheduler@sistema.local",
role: "ADMIN",
},
})
return NextResponse.json(result)
}
function isCronRequest(request: Request) {
const secret = env.REPORTS_CRON_SECRET
if (!secret) return false
const auth = request.headers.get("authorization")
if (auth && auth === `Bearer ${secret}`) return true
const header = request.headers.get("x-cron-secret")
if (header && header === secret) return true
const url = new URL(request.url)
if (url.searchParams.get("secret") === secret) return true
return false
}

View file

@ -0,0 +1,38 @@
import { NextResponse } from "next/server"
import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"
export const runtime = "nodejs"
export async function GET(request: Request, { params }: { params: { id: string } }) {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
const run = await prisma.reportExportRun.findFirst({
where: { id: params.id, tenantId },
})
if (!run || !run.artifacts) {
return NextResponse.json({ error: "Arquivo não encontrado" }, { status: 404 })
}
const { searchParams } = new URL(request.url)
const artifactIndex = Number(searchParams.get("artifact") ?? "0")
const artifacts = run.artifacts as Array<{ key: string; fileName: string; mimeType: string; data: string }>
const artifact = artifacts?.[artifactIndex]
if (!artifact) {
return NextResponse.json({ error: "Arquivo não encontrado" }, { status: 404 })
}
const buffer = Buffer.from(artifact.data, "base64")
return new NextResponse(buffer, {
headers: {
"Content-Type": artifact.mimeType ?? "application/octet-stream",
"Content-Disposition": `attachment; filename="${artifact.fileName ?? `export-${run.id}`}"`,
"Cache-Control": "no-store",
},
})
}

View file

@ -1,12 +1,7 @@
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"
import { buildXlsxWorkbook } from "@/lib/xlsx"
import { buildSlaWorkbook, createConvexContext } from "@/server/report-exporters"
export const runtime = "nodejs"
@ -16,89 +11,27 @@ export async function GET(request: Request) {
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 companyId = searchParams.get("companyId") ?? 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, {
const context = await createConvexContext({
tenantId,
name: session.user.name ?? session.user.email,
email: session.user.email,
avatarUrl: session.user.avatarUrl ?? undefined,
avatarUrl: session.user.avatarUrl,
role: session.user.role.toUpperCase(),
})
viewerId = ensuredUser?._id ?? null
} catch (error) {
console.error("Failed to synchronize user with Convex for SLA export", 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 })
}
const artifact = await buildSlaWorkbook(context, { range, companyId: companyId ?? undefined })
try {
const report = await client.query(api.reports.slaOverview, {
tenantId,
viewerId: viewerId as unknown as Id<"users">,
range,
companyId: companyId as unknown as Id<"companies">,
})
const summaryRows: Array<Array<unknown>> = [
["Relatório", "Produtividade"],
["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? "90d")],
]
if (companyId) {
summaryRows.push(["EmpresaId", companyId])
}
summaryRows.push(["Tickets totais", report.totals.total])
summaryRows.push(["Tickets abertos", report.totals.open])
summaryRows.push(["Tickets resolvidos", report.totals.resolved])
summaryRows.push(["Atrasados (SLA)", report.totals.overdue])
summaryRows.push(["Tempo médio de 1ª resposta (min)", report.response.averageFirstResponseMinutes ?? "—"])
summaryRows.push(["Respostas registradas", report.response.responsesRegistered ?? 0])
summaryRows.push(["Tempo médio de resolução (min)", report.resolution.averageResolutionMinutes ?? "—"])
summaryRows.push(["Tickets resolvidos (amostra)", report.resolution.resolvedCount ?? 0])
const queueRows: Array<Array<unknown>> = []
for (const queue of report.queueBreakdown ?? []) {
queueRows.push([queue.name || queue.id, queue.open])
}
const workbook = buildXlsxWorkbook([
{
name: "Resumo",
headers: ["Indicador", "Valor"],
rows: summaryRows,
},
{
name: "Filas",
headers: ["Fila", "Chamados abertos"],
rows: queueRows.length > 0 ? queueRows : [["—", 0]],
},
])
const daysLabel = (() => {
const raw = (range ?? "90d").replace("d", "")
return /^(7|30|90)$/.test(raw) ? `${raw}d` : "all"
})()
const body = new Uint8Array(workbook)
return new NextResponse(body, {
return new NextResponse(artifact.buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="sla-${tenantId}-${daysLabel}.xlsx"`,
"Content-Type": artifact.mimeType,
"Content-Disposition": `attachment; filename="${artifact.fileName}"`,
"Cache-Control": "no-store",
},
})

View file

@ -1,12 +1,7 @@
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"
import { buildXlsxWorkbook } from "@/lib/xlsx"
import { buildTicketsByChannelWorkbook, createConvexContext } from "@/server/report-exporters"
export const runtime = "nodejs"
@ -16,88 +11,30 @@ export async function GET(request: Request) {
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 companyId = searchParams.get("companyId") ?? 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, {
const context = await createConvexContext({
tenantId,
name: session.user.name ?? session.user.email,
email: session.user.email,
avatarUrl: session.user.avatarUrl ?? undefined,
avatarUrl: session.user.avatarUrl,
role: session.user.role.toUpperCase(),
})
viewerId = ensuredUser?._id ?? null
} catch (error) {
console.error("Failed to synchronize user with Convex for channel export", 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">,
const artifact = await buildTicketsByChannelWorkbook(context, {
range,
companyId: companyId as unknown as Id<"companies">,
companyId: companyId ?? undefined,
})
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 summaryRows: Array<Array<unknown>> = [
["Relatório", "Tickets por canal"],
["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : range ?? "90d"],
]
if (companyId) summaryRows.push(["EmpresaId", companyId])
summaryRows.push(["Total de linhas", report.points.length])
const header = ["Data", ...channels.map((ch) => CHANNEL_PT[ch] ?? ch)]
const dataRows: Array<Array<unknown>> = report.points.map((point) => {
const values = channels.map((ch) => point.values[ch] ?? 0)
return [point.date, ...values]
})
const workbook = buildXlsxWorkbook([
{
name: "Resumo",
headers: ["Item", "Valor"],
rows: summaryRows,
},
{
name: "Distribuição",
headers: header,
rows: dataRows.length > 0 ? dataRows : [[new Date().toISOString().slice(0, 10), ...channels.map(() => 0)]],
},
])
const body = new Uint8Array(workbook)
return new NextResponse(body, {
return new NextResponse(artifact.buffer, {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="tickets-by-channel-${tenantId}-${range ?? '90d'}${companyId ? `-${companyId}` : ''}.xlsx"`,
"Content-Type": artifact.mimeType,
"Content-Disposition": `attachment; filename="${artifact.fileName}"`,
"Cache-Control": "no-store",
},
})