705 lines
30 KiB
TypeScript
705 lines
30 KiB
TypeScript
"use client"
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
|
import { format, formatDistanceToNow } from "date-fns"
|
|
import { ptBR } from "date-fns/locale"
|
|
import { IconClock, IconFileTypePdf, IconPlayerPause, IconPlayerPlay } from "@tabler/icons-react"
|
|
import { useMutation, useQuery } from "convex/react"
|
|
import { toast } from "sonner"
|
|
import { api } from "@/convex/_generated/api"
|
|
|
|
import { useAuth } from "@/lib/auth-client"
|
|
import type { Doc, Id } from "@/convex/_generated/dataModel"
|
|
import type { TicketWithDetails, TicketQueueSummary, TicketStatus } from "@/lib/schemas/ticket"
|
|
import { Badge } from "@/components/ui/badge"
|
|
import { Separator } from "@/components/ui/separator"
|
|
import { PrioritySelect } from "@/components/tickets/priority-select"
|
|
import { DeleteTicketDialog } from "@/components/tickets/delete-ticket-dialog"
|
|
import { StatusSelect } from "@/components/tickets/status-select"
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
|
import { Button } from "@/components/ui/button"
|
|
import { Input } from "@/components/ui/input"
|
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
|
import { Textarea } from "@/components/ui/textarea"
|
|
import { Spinner } from "@/components/ui/spinner"
|
|
import { useTicketCategories } from "@/hooks/use-ticket-categories"
|
|
import { useDefaultQueues } from "@/hooks/use-default-queues"
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuTrigger,
|
|
} from "@/components/ui/dropdown-menu"
|
|
|
|
interface TicketHeaderProps {
|
|
ticket: TicketWithDetails
|
|
}
|
|
|
|
const cardClass = "relative space-y-4 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm"
|
|
const referenceBadgeClass = "inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700"
|
|
const startButtonClass =
|
|
"inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black/30"
|
|
const pauseButtonClass =
|
|
"inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#18181b]/30"
|
|
const editButtonClass =
|
|
"inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#18181b]/30"
|
|
const selectTriggerClass = "h-8 w-full rounded-lg border border-slate-300 bg-white px-3 text-left text-sm font-medium text-neutral-800 shadow-sm focus:ring-0 data-[state=open]:border-[#00d6eb]"
|
|
const smallSelectTriggerClass = "h-8 w-full rounded-lg border border-slate-300 bg-white px-3 text-left text-sm font-medium text-neutral-800 shadow-sm focus:ring-0 data-[state=open]:border-[#00d6eb]"
|
|
const sectionLabelClass = "text-xs font-semibold uppercase tracking-wide text-neutral-500"
|
|
const sectionValueClass = "font-medium text-neutral-900"
|
|
const subtleBadgeClass =
|
|
"inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-2.5 py-0.5 text-[11px] font-medium text-neutral-600"
|
|
|
|
const EMPTY_CATEGORY_VALUE = "__none__"
|
|
const EMPTY_SUBCATEGORY_VALUE = "__none__"
|
|
const PAUSE_REASONS = [
|
|
{ value: "NO_CONTACT", label: "Falta de contato" },
|
|
{ value: "WAITING_THIRD_PARTY", label: "Aguardando terceiro" },
|
|
{ value: "IN_PROCEDURE", label: "Em procedimento" },
|
|
]
|
|
|
|
function formatDuration(durationMs: number) {
|
|
if (durationMs <= 0) return "0s"
|
|
const totalSeconds = Math.floor(durationMs / 1000)
|
|
const hours = Math.floor(totalSeconds / 3600)
|
|
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
|
const seconds = totalSeconds % 60
|
|
if (hours > 0) {
|
|
return `${hours}h ${minutes.toString().padStart(2, "0")}m`
|
|
}
|
|
if (minutes > 0) {
|
|
return `${minutes}m ${seconds.toString().padStart(2, "0")}s`
|
|
}
|
|
return `${seconds}s`
|
|
}
|
|
|
|
export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
|
|
const { convexUserId, role } = useAuth()
|
|
const isManager = role === "manager"
|
|
useDefaultQueues(ticket.tenantId)
|
|
const changeAssignee = useMutation(api.tickets.changeAssignee)
|
|
const changeQueue = useMutation(api.tickets.changeQueue)
|
|
const updateSubject = useMutation(api.tickets.updateSubject)
|
|
const updateSummary = useMutation(api.tickets.updateSummary)
|
|
const startWork = useMutation(api.tickets.startWork)
|
|
const pauseWork = useMutation(api.tickets.pauseWork)
|
|
const updateCategories = useMutation(api.tickets.updateCategories)
|
|
const agents = (useQuery(api.users.listAgents, { tenantId: ticket.tenantId }) as Doc<"users">[] | undefined) ?? []
|
|
const queueArgs = convexUserId
|
|
? { tenantId: ticket.tenantId, viewerId: convexUserId as Id<"users"> }
|
|
: "skip"
|
|
const queues = (
|
|
useQuery(convexUserId ? api.queues.summary : "skip", queueArgs) as TicketQueueSummary[] | undefined
|
|
) ?? []
|
|
const { categories, isLoading: categoriesLoading } = useTicketCategories(ticket.tenantId)
|
|
const [status] = useState<TicketStatus>(ticket.status)
|
|
const workSummaryRemote = useQuery(
|
|
api.tickets.workSummary,
|
|
convexUserId
|
|
? { ticketId: ticket.id as Id<"tickets">, viewerId: convexUserId as Id<"users"> }
|
|
: "skip"
|
|
) as
|
|
| {
|
|
ticketId: Id<"tickets">
|
|
totalWorkedMs: number
|
|
activeSession: { id: Id<"ticketWorkSessions">; agentId: Id<"users">; startedAt: number } | null
|
|
}
|
|
| null
|
|
| undefined
|
|
|
|
const [editing, setEditing] = useState(false)
|
|
const [subject, setSubject] = useState(ticket.subject)
|
|
const [summary, setSummary] = useState(ticket.summary ?? "")
|
|
const [categorySelection, setCategorySelection] = useState<{ categoryId: string; subcategoryId: string }>(
|
|
{
|
|
categoryId: ticket.category?.id ?? "",
|
|
subcategoryId: ticket.subcategory?.id ?? "",
|
|
}
|
|
)
|
|
const [saving, setSaving] = useState(false)
|
|
const [pauseDialogOpen, setPauseDialogOpen] = useState(false)
|
|
const [pauseReason, setPauseReason] = useState<string>(PAUSE_REASONS[0]?.value ?? "NO_CONTACT")
|
|
const [pauseNote, setPauseNote] = useState("")
|
|
const [pausing, setPausing] = useState(false)
|
|
const [exportingPdf, setExportingPdf] = useState(false)
|
|
const selectedCategoryId = categorySelection.categoryId
|
|
const selectedSubcategoryId = categorySelection.subcategoryId
|
|
const dirty = useMemo(
|
|
() => subject !== ticket.subject || (summary ?? "") !== (ticket.summary ?? ""),
|
|
[subject, summary, ticket.subject, ticket.summary]
|
|
)
|
|
const currentCategoryId = ticket.category?.id ?? ""
|
|
const currentSubcategoryId = ticket.subcategory?.id ?? ""
|
|
const categoryDirty = useMemo(() => {
|
|
return selectedCategoryId !== currentCategoryId || selectedSubcategoryId !== currentSubcategoryId
|
|
}, [selectedCategoryId, selectedSubcategoryId, currentCategoryId, currentSubcategoryId])
|
|
const currentQueueName = ticket.queue ?? ""
|
|
const isAvulso = Boolean((ticket as any).company?.isAvulso ?? false)
|
|
const [queueSelection, setQueueSelection] = useState(currentQueueName)
|
|
const queueDirty = useMemo(() => queueSelection !== currentQueueName, [queueSelection, currentQueueName])
|
|
const formDirty = dirty || categoryDirty || queueDirty
|
|
|
|
const activeCategory = useMemo(
|
|
() => categories.find((category) => category.id === selectedCategoryId) ?? null,
|
|
[categories, selectedCategoryId]
|
|
)
|
|
const secondaryOptions = useMemo(() => activeCategory?.secondary ?? [], [activeCategory])
|
|
|
|
async function handleSave() {
|
|
if (!convexUserId || !formDirty) {
|
|
setEditing(false)
|
|
return
|
|
}
|
|
|
|
setSaving(true)
|
|
|
|
try {
|
|
if (categoryDirty && !isManager) {
|
|
toast.loading("Atualizando categoria...", { id: "ticket-category" })
|
|
try {
|
|
await updateCategories({
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
categoryId: selectedCategoryId ? (selectedCategoryId as Id<"ticketCategories">) : null,
|
|
subcategoryId: selectedSubcategoryId ? (selectedSubcategoryId as Id<"ticketSubcategories">) : null,
|
|
actorId: convexUserId as Id<"users">,
|
|
})
|
|
toast.success("Categoria atualizada!", { id: "ticket-category" })
|
|
} catch (categoryError) {
|
|
toast.error("Não foi possível atualizar a categoria.", { id: "ticket-category" })
|
|
setCategorySelection({
|
|
categoryId: currentCategoryId,
|
|
subcategoryId: currentSubcategoryId,
|
|
})
|
|
throw categoryError
|
|
}
|
|
} else if (categoryDirty && isManager) {
|
|
setCategorySelection({
|
|
categoryId: currentCategoryId,
|
|
subcategoryId: currentSubcategoryId,
|
|
})
|
|
}
|
|
|
|
if (queueDirty && !isManager) {
|
|
const queue = queues.find((item) => item.name === queueSelection)
|
|
if (!queue) {
|
|
toast.error("Fila selecionada não está disponível.")
|
|
setQueueSelection(currentQueueName)
|
|
throw new Error("Fila inválida")
|
|
}
|
|
toast.loading("Atualizando fila...", { id: "queue" })
|
|
try {
|
|
await changeQueue({
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
queueId: queue.id as Id<"queues">,
|
|
actorId: convexUserId as Id<"users">,
|
|
})
|
|
toast.success("Fila atualizada!", { id: "queue" })
|
|
} catch (queueError) {
|
|
toast.error("Não foi possível atualizar a fila.", { id: "queue" })
|
|
setQueueSelection(currentQueueName)
|
|
throw queueError
|
|
}
|
|
} else if (queueDirty && isManager) {
|
|
setQueueSelection(currentQueueName)
|
|
}
|
|
|
|
if (dirty) {
|
|
toast.loading("Salvando alterações...", { id: "save-header" })
|
|
if (subject !== ticket.subject) {
|
|
await updateSubject({
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
subject: subject.trim(),
|
|
actorId: convexUserId as Id<"users">,
|
|
})
|
|
}
|
|
if ((summary ?? "") !== (ticket.summary ?? "")) {
|
|
await updateSummary({
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
summary: (summary ?? "").trim(),
|
|
actorId: convexUserId as Id<"users">,
|
|
})
|
|
}
|
|
toast.success("Cabeçalho atualizado!", { id: "save-header" })
|
|
}
|
|
setEditing(false)
|
|
} catch {
|
|
toast.error("Não foi possível salvar.", { id: "save-header" })
|
|
} finally {
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
function handleCancel() {
|
|
setSubject(ticket.subject)
|
|
setSummary(ticket.summary ?? "")
|
|
setCategorySelection({
|
|
categoryId: currentCategoryId,
|
|
subcategoryId: currentSubcategoryId,
|
|
})
|
|
setQueueSelection(currentQueueName)
|
|
setEditing(false)
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (editing) return
|
|
setCategorySelection({
|
|
categoryId: ticket.category?.id ?? "",
|
|
subcategoryId: ticket.subcategory?.id ?? "",
|
|
})
|
|
setQueueSelection(ticket.queue ?? "")
|
|
}, [editing, ticket.category?.id, ticket.subcategory?.id, ticket.queue])
|
|
|
|
useEffect(() => {
|
|
if (!editing) return
|
|
if (!selectedCategoryId) {
|
|
if (selectedSubcategoryId) {
|
|
setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
|
|
}
|
|
return
|
|
}
|
|
|
|
const stillValid = secondaryOptions.some((option) => option.id === selectedSubcategoryId)
|
|
if (!stillValid && selectedSubcategoryId) {
|
|
setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
|
|
}
|
|
}, [editing, secondaryOptions, selectedCategoryId, selectedSubcategoryId])
|
|
|
|
const workSummary = useMemo(() => {
|
|
if (workSummaryRemote !== undefined) return workSummaryRemote ?? null
|
|
if (!ticket.workSummary) return null
|
|
return {
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
totalWorkedMs: ticket.workSummary.totalWorkedMs,
|
|
internalWorkedMs: ticket.workSummary.internalWorkedMs ?? 0,
|
|
externalWorkedMs: ticket.workSummary.externalWorkedMs ?? 0,
|
|
activeSession: ticket.workSummary.activeSession
|
|
? {
|
|
id: ticket.workSummary.activeSession.id as Id<"ticketWorkSessions">,
|
|
agentId: ticket.workSummary.activeSession.agentId as Id<"users">,
|
|
startedAt: ticket.workSummary.activeSession.startedAt.getTime(),
|
|
workType: (ticket.workSummary.activeSession as any).workType ?? "INTERNAL",
|
|
}
|
|
: null,
|
|
}
|
|
}, [ticket.id, ticket.workSummary, workSummaryRemote])
|
|
|
|
const isPlaying = Boolean(workSummary?.activeSession)
|
|
const [now, setNow] = useState(() => Date.now())
|
|
|
|
useEffect(() => {
|
|
if (!workSummary?.activeSession) return
|
|
const interval = setInterval(() => {
|
|
setNow(Date.now())
|
|
}, 1000)
|
|
return () => clearInterval(interval)
|
|
}, [workSummary?.activeSession])
|
|
|
|
useEffect(() => {
|
|
if (!pauseDialogOpen) {
|
|
setPauseReason(PAUSE_REASONS[0]?.value ?? "NO_CONTACT")
|
|
setPauseNote("")
|
|
setPausing(false)
|
|
}
|
|
}, [pauseDialogOpen])
|
|
|
|
const currentSessionMs = workSummary?.activeSession ? Math.max(0, now - workSummary.activeSession.startedAt) : 0
|
|
const totalWorkedMs = workSummary ? workSummary.totalWorkedMs + currentSessionMs : 0
|
|
const internalWorkedMs = workSummary
|
|
? (((workSummary as any).internalWorkedMs ?? 0) + (((workSummary?.activeSession as any)?.workType === "INTERNAL") ? currentSessionMs : 0))
|
|
: 0
|
|
const externalWorkedMs = workSummary
|
|
? (((workSummary as any).externalWorkedMs ?? 0) + (((workSummary?.activeSession as any)?.workType === "EXTERNAL") ? currentSessionMs : 0))
|
|
: 0
|
|
|
|
const formattedTotalWorked = useMemo(() => formatDuration(totalWorkedMs), [totalWorkedMs])
|
|
const updatedRelative = useMemo(
|
|
() => formatDistanceToNow(ticket.updatedAt, { addSuffix: true, locale: ptBR }),
|
|
[ticket.updatedAt]
|
|
)
|
|
|
|
const handleStartWork = async (workType: "INTERNAL" | "EXTERNAL") => {
|
|
if (!convexUserId) return
|
|
toast.dismiss("work")
|
|
toast.loading("Iniciando atendimento...", { id: "work" })
|
|
try {
|
|
const result = await startWork({ ticketId: ticket.id as Id<"tickets">, actorId: convexUserId as Id<"users">, workType } as any)
|
|
if (result?.status === "already_started") {
|
|
toast.info("O atendimento já estava em andamento", { id: "work" })
|
|
} else {
|
|
toast.success("Atendimento iniciado", { id: "work" })
|
|
}
|
|
} catch {
|
|
toast.error("Não foi possível atualizar o atendimento", { id: "work" })
|
|
}
|
|
}
|
|
|
|
const handlePauseConfirm = async () => {
|
|
if (!convexUserId) return
|
|
toast.dismiss("work")
|
|
toast.loading("Pausando atendimento...", { id: "work" })
|
|
setPausing(true)
|
|
try {
|
|
const result = await pauseWork({
|
|
ticketId: ticket.id as Id<"tickets">,
|
|
actorId: convexUserId as Id<"users">,
|
|
reason: pauseReason,
|
|
note: pauseNote.trim() ? pauseNote.trim() : undefined,
|
|
})
|
|
if (result?.status === "already_paused") {
|
|
toast.info("O atendimento já estava pausado", { id: "work" })
|
|
} else {
|
|
toast.success("Atendimento pausado", { id: "work" })
|
|
}
|
|
setPauseDialogOpen(false)
|
|
} catch {
|
|
toast.error("Não foi possível atualizar o atendimento", { id: "work" })
|
|
} finally {
|
|
setPausing(false)
|
|
}
|
|
}
|
|
|
|
const handleExportPdf = useCallback(async () => {
|
|
try {
|
|
setExportingPdf(true)
|
|
toast.dismiss("ticket-export")
|
|
toast.loading("Gerando PDF...", { id: "ticket-export" })
|
|
const response = await fetch(`/api/tickets/${ticket.id}/export/pdf`, { credentials: "include" })
|
|
if (!response.ok) {
|
|
throw new Error(`failed: ${response.status}`)
|
|
}
|
|
const blob = await response.blob()
|
|
const url = URL.createObjectURL(blob)
|
|
const link = document.createElement("a")
|
|
link.href = url
|
|
link.download = `ticket-${ticket.reference}.pdf`
|
|
document.body.appendChild(link)
|
|
link.click()
|
|
document.body.removeChild(link)
|
|
URL.revokeObjectURL(url)
|
|
toast.success("PDF exportado com sucesso!", { id: "ticket-export" })
|
|
} catch (error) {
|
|
console.error(error)
|
|
toast.error("Não foi possível exportar o PDF.", { id: "ticket-export" })
|
|
} finally {
|
|
setExportingPdf(false)
|
|
}
|
|
}, [ticket.id, ticket.reference])
|
|
|
|
return (
|
|
<div className={cardClass}>
|
|
<div className="absolute right-6 top-6 flex items-center gap-3">
|
|
{workSummary ? (
|
|
<>
|
|
<Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700">
|
|
<IconClock className="size-4 text-neutral-700" /> Interno: {formatDuration(internalWorkedMs)}
|
|
</Badge>
|
|
<Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700">
|
|
<IconClock className="size-4 text-neutral-700" /> Externo: {formatDuration(externalWorkedMs)}
|
|
</Badge>
|
|
<Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700">
|
|
<IconClock className="size-4 text-neutral-700" /> Total: {formattedTotalWorked}
|
|
</Badge>
|
|
</>
|
|
) : null}
|
|
{!editing ? (
|
|
<Button size="sm" className={editButtonClass} onClick={() => setEditing(true)}>
|
|
Editar
|
|
</Button>
|
|
) : null}
|
|
<Button
|
|
size="icon"
|
|
variant="outline"
|
|
aria-label="Exportar PDF"
|
|
className="inline-flex items-center justify-center rounded-lg border border-slate-200 bg-white text-neutral-800 hover:bg-slate-50"
|
|
onClick={handleExportPdf}
|
|
disabled={exportingPdf}
|
|
title="Exportar PDF"
|
|
>
|
|
{exportingPdf ? <Spinner className="size-4 text-neutral-700" /> : <IconFileTypePdf className="size-5" />}
|
|
</Button>
|
|
<DeleteTicketDialog ticketId={ticket.id as Id<"tickets">} />
|
|
</div>
|
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
|
<div className="space-y-3">
|
|
<div className="flex flex-wrap items-center gap-3">
|
|
<Badge className={referenceBadgeClass}>#{ticket.reference}</Badge>
|
|
{isAvulso ? (
|
|
<Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-rose-200 bg-rose-50 px-3 text-sm font-semibold text-rose-700">
|
|
Cliente avulso
|
|
</Badge>
|
|
) : null}
|
|
<PrioritySelect ticketId={ticket.id} value={ticket.priority} />
|
|
<StatusSelect ticketId={ticket.id} value={status} />
|
|
{isPlaying ? (
|
|
<Button
|
|
size="sm"
|
|
className={pauseButtonClass}
|
|
onClick={() => {
|
|
if (!convexUserId) return
|
|
setPauseDialogOpen(true)
|
|
}}
|
|
>
|
|
<IconPlayerPause className="size-4 text-white" /> Pausar
|
|
</Button>
|
|
) : (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button size="sm" className={startButtonClass}>
|
|
<IconPlayerPlay className="size-4 text-white" /> Iniciar
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent align="start" className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
<DropdownMenuItem onSelect={() => void handleStartWork("INTERNAL")}>Iniciar (interno)</DropdownMenuItem>
|
|
<DropdownMenuItem onSelect={() => void handleStartWork("EXTERNAL")}>Iniciar (externo)</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)}
|
|
</div>
|
|
{editing ? (
|
|
<div className="space-y-2">
|
|
<Input
|
|
value={subject}
|
|
onChange={(e) => setSubject(e.target.value)}
|
|
className="h-10 rounded-lg border border-slate-300 text-lg font-semibold text-neutral-900"
|
|
/>
|
|
<textarea
|
|
value={summary}
|
|
onChange={(e) => setSummary(e.target.value)}
|
|
rows={3}
|
|
className="w-full rounded-lg border border-slate-300 bg-white p-3 text-sm text-neutral-800 shadow-sm"
|
|
placeholder="Adicione um resumo opcional"
|
|
/>
|
|
</div>
|
|
) : (
|
|
<div className="space-y-1">
|
|
<h1 className="break-words text-2xl font-semibold text-neutral-900">{subject}</h1>
|
|
{summary ? <p className="max-w-2xl text-sm text-neutral-600">{summary}</p> : null}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<Separator className="bg-slate-200" />
|
|
<div className="grid gap-4 text-sm text-neutral-600 sm:grid-cols-2 lg:grid-cols-3">
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Categoria primária</span>
|
|
{editing ? (
|
|
<Select
|
|
disabled={saving || categoriesLoading || isManager}
|
|
value={selectedCategoryId ? selectedCategoryId : EMPTY_CATEGORY_VALUE}
|
|
onValueChange={(value) => {
|
|
if (isManager) return
|
|
if (value === EMPTY_CATEGORY_VALUE) {
|
|
setCategorySelection({ categoryId: "", subcategoryId: "" })
|
|
return
|
|
}
|
|
const category = categories.find((item) => item.id === value)
|
|
setCategorySelection({
|
|
categoryId: value,
|
|
subcategoryId: category?.secondary.find((option) => option.id === selectedSubcategoryId)?.id ?? "",
|
|
})
|
|
}}
|
|
>
|
|
<SelectTrigger className={selectTriggerClass}>
|
|
<SelectValue placeholder={categoriesLoading ? "Carregando..." : "Sem categoria"} />
|
|
</SelectTrigger>
|
|
<SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
<SelectItem value={EMPTY_CATEGORY_VALUE}>Sem categoria</SelectItem>
|
|
{categories.map((category) => (
|
|
<SelectItem key={category.id} value={category.id}>
|
|
{category.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
) : (
|
|
<span className={sectionValueClass}>{ticket.category?.name ?? "Sem categoria"}</span>
|
|
)}
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Categoria secundária</span>
|
|
{editing ? (
|
|
<Select
|
|
disabled={
|
|
saving || categoriesLoading || !selectedCategoryId || isManager
|
|
}
|
|
value={selectedSubcategoryId ? selectedSubcategoryId : EMPTY_SUBCATEGORY_VALUE}
|
|
onValueChange={(value) => {
|
|
if (isManager) return
|
|
if (value === EMPTY_SUBCATEGORY_VALUE) {
|
|
setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
|
|
return
|
|
}
|
|
setCategorySelection((prev) => ({ ...prev, subcategoryId: value }))
|
|
}}
|
|
>
|
|
<SelectTrigger className={selectTriggerClass}>
|
|
<SelectValue
|
|
placeholder={
|
|
!selectedCategoryId
|
|
? "Selecione uma primária"
|
|
: secondaryOptions.length === 0
|
|
? "Sem subcategoria"
|
|
: "Selecionar"
|
|
}
|
|
/>
|
|
</SelectTrigger>
|
|
<SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
<SelectItem value={EMPTY_SUBCATEGORY_VALUE}>Sem subcategoria</SelectItem>
|
|
{secondaryOptions.map((option) => (
|
|
<SelectItem key={option.id} value={option.id}>
|
|
{option.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
) : (
|
|
<span className={sectionValueClass}>{ticket.subcategory?.name ?? "Sem subcategoria"}</span>
|
|
)}
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Fila</span>
|
|
{editing ? (
|
|
<Select
|
|
disabled={isManager}
|
|
value={queueSelection}
|
|
onValueChange={(value) => {
|
|
if (isManager) return
|
|
setQueueSelection(value)
|
|
}}
|
|
>
|
|
<SelectTrigger className={smallSelectTriggerClass}>
|
|
<SelectValue placeholder="Selecionar" />
|
|
</SelectTrigger>
|
|
<SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
{queues.map((queue) => (
|
|
<SelectItem key={queue.id} value={queue.name}>
|
|
{queue.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
) : (
|
|
<span className={sectionValueClass}>{ticket.queue ?? "Sem fila"}</span>
|
|
)}
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Solicitante</span>
|
|
<span className={sectionValueClass}>{ticket.requester.name}</span>
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Responsável</span>
|
|
{editing ? (
|
|
<Select
|
|
disabled={isManager}
|
|
value={ticket.assignee?.id ?? ""}
|
|
onValueChange={async (value) => {
|
|
if (!convexUserId) return
|
|
if (isManager) return
|
|
toast.loading("Atribuindo responsável...", { id: "assignee" })
|
|
try {
|
|
await changeAssignee({ ticketId: ticket.id as Id<"tickets">, assigneeId: value as Id<"users">, actorId: convexUserId as Id<"users"> })
|
|
toast.success("Responsável atualizado!", { id: "assignee" })
|
|
} catch {
|
|
toast.error("Não foi possível atribuir.", { id: "assignee" })
|
|
}
|
|
}}
|
|
>
|
|
<SelectTrigger className={selectTriggerClass}>
|
|
<SelectValue placeholder="Selecionar" />
|
|
</SelectTrigger>
|
|
<SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
{agents.map((agent) => (
|
|
<SelectItem key={agent._id} value={agent._id}>
|
|
{agent.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
) : (
|
|
<span className={sectionValueClass}>{ticket.assignee?.name ?? "Não atribuído"}</span>
|
|
)}
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Criado em</span>
|
|
<span className={sectionValueClass}>{format(ticket.createdAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Atualizado em</span>
|
|
<div className="flex items-center gap-2">
|
|
<span className={sectionValueClass}>{format(ticket.updatedAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
|
|
<span className={subtleBadgeClass}>{updatedRelative}</span>
|
|
</div>
|
|
</div>
|
|
{ticket.dueAt ? (
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>SLA até</span>
|
|
<span className={sectionValueClass}>{format(ticket.dueAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
|
|
</div>
|
|
) : null}
|
|
{ticket.slaPolicy ? (
|
|
<div className="flex flex-col gap-1">
|
|
<span className={sectionLabelClass}>Política</span>
|
|
<span className={sectionValueClass}>{ticket.slaPolicy.name}</span>
|
|
</div>
|
|
) : null}
|
|
{editing ? (
|
|
<div className="flex items-center justify-end gap-2 sm:col-span-2 lg:col-span-3">
|
|
<Button variant="ghost" size="sm" className="text-sm font-semibold text-neutral-700" onClick={handleCancel}>
|
|
Cancelar
|
|
</Button>
|
|
<Button size="sm" className={startButtonClass} onClick={handleSave} disabled={!formDirty || saving}>
|
|
Salvar
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
<Dialog open={pauseDialogOpen} onOpenChange={setPauseDialogOpen}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>Registrar pausa</DialogTitle>
|
|
<DialogDescription>Informe o motivo da pausa para registrar no histórico do chamado.</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="space-y-4">
|
|
<div className="space-y-1.5">
|
|
<span className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Motivo</span>
|
|
<Select value={pauseReason} onValueChange={setPauseReason}>
|
|
<SelectTrigger className={selectTriggerClass}>
|
|
<SelectValue placeholder="Selecione" />
|
|
</SelectTrigger>
|
|
<SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
|
|
{PAUSE_REASONS.map((reason) => (
|
|
<SelectItem key={reason.value} value={reason.value}>
|
|
{reason.label}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<span className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Observações</span>
|
|
<Textarea
|
|
value={pauseNote}
|
|
onChange={(event) => setPauseNote(event.target.value)}
|
|
rows={3}
|
|
placeholder="Adicione detalhes opcionais (visível apenas internamente)."
|
|
className="min-h-[96px]"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => setPauseDialogOpen(false)} disabled={pausing}>
|
|
Cancelar
|
|
</Button>
|
|
<Button
|
|
className={pauseButtonClass}
|
|
onClick={handlePauseConfirm}
|
|
disabled={pausing || !pauseReason}
|
|
>
|
|
{pausing ? <Spinner className="size-4 text-white" /> : "Registrar pausa"}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
)
|
|
}
|