reports(SLA): aplica filtro de período (7d/30d/90d) no Convex e inclui período no filename do CSV; admin(alerts): filtros no servidor; alerts: batch de últimos alertas por slugs; filtros persistentes de empresa (localStorage) em relatórios; prisma: Company.contractedHoursPerMonth; smtp: suporte a múltiplos destinatários e timeout opcional

This commit is contained in:
Esdras Renan 2025-10-07 16:46:52 -03:00
parent a23b429e4d
commit 384d4411b6
13 changed files with 133 additions and 38 deletions

View file

@ -21,17 +21,11 @@ export async function GET(request: Request) {
const slugs = slugsParam.split(",").map((s) => s.trim()).filter(Boolean)
const tenantId = session.user.tenantId ?? "tenant-atlas"
const result: Record<string, { createdAt: number; usagePct: number; threshold: number } | null> = {}
for (const slug of slugs) {
try {
const last = (await client.query(api.alerts.lastForCompanyBySlug, { tenantId, slug })) as
| { createdAt: number; usagePct: number; threshold: number }
| null
result[slug] = last
} catch {
result[slug] = null
}
try {
const result = (await client.query(api.alerts.lastForCompaniesBySlugs, { tenantId, slugs })) as Record<string, { createdAt: number; usagePct: number; threshold: number } | null>
return NextResponse.json({ items: result })
} catch (error) {
console.error("Failed to fetch last alerts by slugs", error)
return NextResponse.json({ items: {} })
}
return NextResponse.json({ items: result })
}

View file

@ -68,7 +68,7 @@ export async function GET(request: Request) {
const rows: Array<Array<unknown>> = []
rows.push(["Relatório", "SLA e produtividade"])
rows.push(["Período", range ?? "—"])
rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? "90d")])
if (companyId) rows.push(["EmpresaId", companyId])
rows.push([])
@ -89,10 +89,14 @@ export async function GET(request: Request) {
}
const csv = rowsToCsv(rows)
const daysLabel = (() => {
const raw = (range ?? "90d").replace("d", "")
return /^(7|30|90)$/.test(raw) ? `${raw}d` : "all"
})()
return new NextResponse(csv, {
headers: {
"Content-Type": "text/csv; charset=UTF-8",
"Content-Disposition": `attachment; filename="sla-${tenantId}.csv"`,
"Content-Disposition": `attachment; filename="sla-${tenantId}-${daysLabel}.csv"`,
"Cache-Control": "no-store",
},
})

View file

@ -24,16 +24,21 @@ export function AdminAlertsManager() {
const alertsRaw = useQuery(
api.alerts.list,
convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
convexUserId
? ({
tenantId,
viewerId: convexUserId as Id<"users">,
start,
end,
companyId: companyId === "all" ? undefined : (companyId as Id<"companies">),
})
: "skip"
) as Doc<"alerts">[] | undefined
const alerts = useMemo(() => {
let list = alertsRaw ?? []
if (companyId !== "all") list = list.filter((a) => String(a.companyId) === companyId)
if (typeof start === "number") list = list.filter((a) => a.createdAt >= start)
if (typeof end === "number") list = list.filter((a) => a.createdAt < end)
const list = alertsRaw ?? []
return list.sort((a, b) => b.createdAt - a.createdAt)
}, [alertsRaw, companyId, start, end])
}, [alertsRaw])
const companies = useQuery(
api.companies.list,
@ -124,4 +129,3 @@ export function AdminAlertsManager() {
</Card>
)
}

View file

@ -33,6 +33,7 @@ import {
SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
import {
ToggleGroup,
ToggleGroupItem,
@ -44,8 +45,8 @@ export function ChartAreaInteractive() {
const [mounted, setMounted] = React.useState(false)
const isMobile = useIsMobile()
const [timeRange, setTimeRange] = React.useState("7d")
// Use a non-empty sentinel value for "all" to satisfy Select.Item requirements
const [companyId, setCompanyId] = React.useState<string>("all")
// Persistir seleção de empresa globalmente
const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
const [companyQuery, setCompanyQuery] = React.useState("")
const { session, convexUserId } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

View file

@ -13,6 +13,7 @@ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
const PRIORITY_LABELS: Record<string, string> = {
LOW: "Baixa",
@ -30,7 +31,7 @@ const STATUS_LABELS: Record<string, string> = {
export function BacklogReport() {
const [timeRange, setTimeRange] = useState("90d")
const [companyId, setCompanyId] = useState<string>("all")
const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
const { session, convexUserId } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
const data = useQuery(

View file

@ -13,6 +13,7 @@ import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
function formatScore(value: number | null) {
if (value === null) return "—"
@ -20,7 +21,7 @@ function formatScore(value: number | null) {
}
export function CsatReport() {
const [companyId, setCompanyId] = useState<string>("all")
const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
const [timeRange, setTimeRange] = useState<string>("90d")
const { session, convexUserId } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

View file

@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
function formatHours(ms: number) {
const hours = ms / 3600000
@ -32,7 +33,7 @@ type HoursItem = {
export function HoursReport() {
const [timeRange, setTimeRange] = useState("90d")
const [query, setQuery] = useState("")
const [companyId, setCompanyId] = useState<string>("all")
const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
const { session, convexUserId } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

View file

@ -14,6 +14,7 @@ import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useState } from "react"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
function formatMinutes(value: number | null) {
if (value === null) return "—"
@ -25,7 +26,7 @@ function formatMinutes(value: number | null) {
}
export function SlaReport() {
const [companyId, setCompanyId] = useState<string>("all")
const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
const [timeRange, setTimeRange] = useState<string>("90d")
const { session, convexUserId } = useAuth()
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

View file

@ -0,0 +1,31 @@
"use client"
import { useEffect, useState } from "react"
const STORAGE_KEY = "ui:selectedCompanyId"
export function usePersistentCompanyFilter(initial: string = "all") {
const [companyId, setCompanyId] = useState<string>(initial)
useEffect(() => {
try {
const saved = window.localStorage.getItem(STORAGE_KEY)
if (saved) setCompanyId(saved)
} catch {
// ignore
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const update = (value: string) => {
setCompanyId(value)
try {
window.localStorage.setItem(STORAGE_KEY, value)
} catch {
// ignore
}
}
return [companyId, update] as const
}

View file

@ -7,6 +7,8 @@ type SmtpConfig = {
password: string
from: string
tls?: boolean
rejectUnauthorized?: boolean
timeoutMs?: number
}
function b64(input: string) {
@ -27,24 +29,32 @@ function extractEnvelopeAddress(from: string): string {
return from
}
export async function sendSmtpMail(cfg: SmtpConfig, to: string, subject: string, html: string) {
export async function sendSmtpMail(cfg: SmtpConfig, to: string | string[], subject: string, html: string) {
return new Promise<void>((resolve, reject) => {
const socket = tls.connect(cfg.port, cfg.host, { rejectUnauthorized: false }, () => {
const socket = tls.connect(cfg.port, cfg.host, { rejectUnauthorized: cfg.rejectUnauthorized ?? false }, () => {
let buffer = ""
const send = (line: string) => socket.write(line + "\r\n")
const wait = (expected: string | RegExp) =>
new Promise<void>((res, rej) => {
const timeout = setTimeout(() => {
socket.removeListener("data", onData)
rej(new Error("smtp_timeout"))
}, Math.max(1000, cfg.timeoutMs ?? 10000))
const onData = (data: Buffer) => {
buffer += data.toString()
const lines = buffer.split(/\r?\n/)
const last = lines.filter(Boolean).slice(-1)[0] ?? ""
if (typeof expected === "string" ? last.startsWith(expected) : expected.test(last)) {
socket.removeListener("data", onData)
clearTimeout(timeout)
res()
}
}
socket.on("data", onData)
socket.on("error", rej)
socket.on("error", (e) => {
clearTimeout(timeout)
rej(e)
})
})
;(async () => {
@ -61,13 +71,21 @@ export async function sendSmtpMail(cfg: SmtpConfig, to: string, subject: string,
const envelopeFrom = extractEnvelopeAddress(cfg.from)
send(`MAIL FROM:<${envelopeFrom}>`)
await wait(/^250 /)
send(`RCPT TO:<${to}>`)
await wait(/^250 /)
const rcpts: string[] = Array.isArray(to)
? to
: String(to)
.split(/[;,]/)
.map((s) => s.trim())
.filter(Boolean)
for (const rcpt of rcpts) {
send(`RCPT TO:<${rcpt}>`)
await wait(/^250 /)
}
send("DATA")
await wait(/^354 /)
const headers = [
`From: ${cfg.from}`,
`To: ${to}`,
`To: ${Array.isArray(to) ? to.join(", ") : to}`,
`Subject: ${subject}`,
"MIME-Version: 1.0",
"Content-Type: text/html; charset=UTF-8",