chore: sync staging
This commit is contained in:
parent
c5ddd54a3e
commit
561b19cf66
610 changed files with 105285 additions and 1206 deletions
|
|
@ -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",
|
||||
},
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue