feat: checklists em tickets + automações
- Adiciona checklist no ticket (itens obrigatórios/opcionais) e bloqueia encerramento com pendências\n- Cria templates de checklist (globais/por empresa) + tela em /settings/checklists\n- Nova ação de automação: aplicar template de checklist\n- Corrige crash do Select (value vazio), warnings de Dialog e dimensionamento de charts\n- Ajusta SMTP (STARTTLS) e melhora teste de integração
This commit is contained in:
parent
4306b0504d
commit
88a9ef454e
27 changed files with 2685 additions and 226 deletions
422
src/components/tickets/ticket-checklist-card.tsx
Normal file
422
src/components/tickets/ticket-checklist-card.tsx
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import { CheckCheck, ListChecks, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { TicketChecklistItem, TicketWithDetails } from "@/lib/schemas/ticket"
|
||||
import { useAuth } from "@/lib/auth-client"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Progress } from "@/components/ui/progress"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
|
||||
type ChecklistTemplateRow = {
|
||||
id: Id<"ticketChecklistTemplates">
|
||||
name: string
|
||||
company: { id: Id<"companies">; name: string } | null
|
||||
}
|
||||
|
||||
function countRequiredPending(items: TicketChecklistItem[]) {
|
||||
return items.filter((item) => (item.required ?? true) && !item.done).length
|
||||
}
|
||||
|
||||
function countRequiredDone(items: TicketChecklistItem[]) {
|
||||
return items.filter((item) => (item.required ?? true) && item.done).length
|
||||
}
|
||||
|
||||
function countAllDone(items: TicketChecklistItem[]) {
|
||||
return items.filter((item) => item.done).length
|
||||
}
|
||||
|
||||
export function TicketChecklistCard({
|
||||
ticket,
|
||||
}: {
|
||||
ticket: Pick<TicketWithDetails, "id" | "tenantId" | "company" | "checklist" | "status">
|
||||
}) {
|
||||
const { convexUserId, isAdmin, isStaff, role } = useAuth()
|
||||
const actorId = (convexUserId ?? null) as Id<"users"> | null
|
||||
const canEdit = Boolean(isAdmin || role === "agent")
|
||||
const canToggleDone = Boolean(isStaff)
|
||||
const isResolved = ticket.status === "RESOLVED"
|
||||
|
||||
const checklist = useMemo(() => ticket.checklist ?? [], [ticket.checklist])
|
||||
const requiredTotal = useMemo(() => checklist.filter((item) => (item.required ?? true)).length, [checklist])
|
||||
const requiredDone = useMemo(() => countRequiredDone(checklist), [checklist])
|
||||
const requiredPending = useMemo(() => countRequiredPending(checklist), [checklist])
|
||||
const allDone = useMemo(() => countAllDone(checklist), [checklist])
|
||||
|
||||
const progress = requiredTotal > 0 ? Math.round((requiredDone / requiredTotal) * 100) : 100
|
||||
|
||||
const addChecklistItem = useMutation(api.tickets.addChecklistItem)
|
||||
const updateChecklistItemText = useMutation(api.tickets.updateChecklistItemText)
|
||||
const setChecklistItemDone = useMutation(api.tickets.setChecklistItemDone)
|
||||
const setChecklistItemRequired = useMutation(api.tickets.setChecklistItemRequired)
|
||||
const removeChecklistItem = useMutation(api.tickets.removeChecklistItem)
|
||||
const completeAllChecklistItems = useMutation(api.tickets.completeAllChecklistItems)
|
||||
const applyChecklistTemplate = useMutation(api.tickets.applyChecklistTemplate)
|
||||
|
||||
const templates = useQuery(
|
||||
api.checklistTemplates.listActive,
|
||||
actorId
|
||||
? {
|
||||
tenantId: ticket.tenantId,
|
||||
viewerId: actorId,
|
||||
companyId: ticket.company?.id ? (ticket.company.id as Id<"companies">) : undefined,
|
||||
}
|
||||
: "skip"
|
||||
) as ChecklistTemplateRow[] | undefined
|
||||
|
||||
const templateNameById = useMemo(() => {
|
||||
const map = new Map<string, string>()
|
||||
for (const tpl of templates ?? []) {
|
||||
map.set(String(tpl.id), tpl.name)
|
||||
}
|
||||
return map
|
||||
}, [templates])
|
||||
|
||||
const [newText, setNewText] = useState("")
|
||||
const [newRequired, setNewRequired] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editingText, setEditingText] = useState("")
|
||||
const [savingText, setSavingText] = useState(false)
|
||||
|
||||
const [selectedTemplateId, setSelectedTemplateId] = useState<string>("")
|
||||
const [applyingTemplate, setApplyingTemplate] = useState(false)
|
||||
const [completingAll, setCompletingAll] = useState(false)
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!actorId || !canEdit || isResolved) return
|
||||
const text = newText.trim()
|
||||
if (!text) {
|
||||
toast.error("Informe o texto do item do checklist.")
|
||||
return
|
||||
}
|
||||
setAdding(true)
|
||||
try {
|
||||
await addChecklistItem({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
text,
|
||||
required: newRequired,
|
||||
})
|
||||
setNewText("")
|
||||
setNewRequired(true)
|
||||
toast.success("Item adicionado ao checklist.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao adicionar item.")
|
||||
} finally {
|
||||
setAdding(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveText = async () => {
|
||||
if (!actorId || !canEdit || isResolved || !editingId) return
|
||||
const text = editingText.trim()
|
||||
if (!text) {
|
||||
toast.error("Informe o texto do item do checklist.")
|
||||
return
|
||||
}
|
||||
setSavingText(true)
|
||||
try {
|
||||
await updateChecklistItemText({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
itemId: editingId,
|
||||
text,
|
||||
})
|
||||
setEditingId(null)
|
||||
setEditingText("")
|
||||
toast.success("Item atualizado.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao atualizar item.")
|
||||
} finally {
|
||||
setSavingText(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleApplyTemplate = async () => {
|
||||
if (!actorId || !canEdit || isResolved) return
|
||||
const templateId = selectedTemplateId.trim()
|
||||
if (!templateId) return
|
||||
setApplyingTemplate(true)
|
||||
try {
|
||||
const result = await applyChecklistTemplate({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
templateId: templateId as Id<"ticketChecklistTemplates">,
|
||||
})
|
||||
const added = typeof result?.added === "number" ? result.added : 0
|
||||
toast.success(added > 0 ? `Checklist aplicado (${added} novo${added === 1 ? "" : "s"}).` : "Checklist já estava aplicado.")
|
||||
setSelectedTemplateId("")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao aplicar template.")
|
||||
} finally {
|
||||
setApplyingTemplate(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCompleteAll = async () => {
|
||||
if (!actorId || !canEdit || isResolved) return
|
||||
setCompletingAll(true)
|
||||
try {
|
||||
await completeAllChecklistItems({ ticketId: ticket.id as Id<"tickets">, actorId })
|
||||
toast.success("Checklist concluído.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao concluir checklist.")
|
||||
} finally {
|
||||
setCompletingAll(false)
|
||||
}
|
||||
}
|
||||
|
||||
const canComplete = checklist.length > 0 && requiredPending > 0 && canEdit && !isResolved
|
||||
|
||||
return (
|
||||
<Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
|
||||
<CardHeader className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2 text-base font-semibold text-neutral-900">
|
||||
<ListChecks className="size-5 text-neutral-700" />
|
||||
Checklist
|
||||
</CardTitle>
|
||||
<CardDescription className="text-sm text-neutral-600">
|
||||
{requiredTotal > 0
|
||||
? `${requiredDone}/${requiredTotal} itens obrigatórios concluídos`
|
||||
: checklist.length > 0
|
||||
? `${allDone}/${checklist.length} itens concluídos`
|
||||
: "Nenhum item cadastrado."}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{canEdit && !isResolved ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
onClick={handleCompleteAll}
|
||||
disabled={!canComplete || completingAll}
|
||||
title={requiredPending > 0 ? "Marcar todos os itens como concluídos" : "Checklist já está concluído"}
|
||||
>
|
||||
<CheckCheck className="size-4" />
|
||||
Concluir todos
|
||||
</Button>
|
||||
) : null}
|
||||
{canEdit && !isResolved && (templates ?? []).length > 0 ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
|
||||
<SelectTrigger className="h-9 w-[220px]">
|
||||
<SelectValue placeholder="Aplicar template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
{(templates ?? []).map((tpl) => (
|
||||
<SelectItem key={tpl.id} value={String(tpl.id)}>
|
||||
{tpl.name}
|
||||
{tpl.company ? ` — ${tpl.company.name}` : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleApplyTemplate}
|
||||
disabled={!selectedTemplateId || applyingTemplate}
|
||||
className="h-9"
|
||||
>
|
||||
Aplicar
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Progress value={progress} className="h-2" indicatorClassName="bg-emerald-500" />
|
||||
|
||||
{checklist.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-slate-200 p-4 text-sm text-neutral-600">
|
||||
{canEdit && !isResolved ? "Adicione itens para controlar o atendimento antes de encerrar." : "Nenhum checklist informado."}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{checklist.map((item) => {
|
||||
const required = item.required ?? true
|
||||
const canToggle = canToggleDone && !isResolved
|
||||
const templateLabel = item.templateId ? templateNameById.get(String(item.templateId)) ?? null : null
|
||||
|
||||
return (
|
||||
<div key={item.id} className="flex items-start justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2">
|
||||
<label className="flex min-w-0 flex-1 items-start gap-3">
|
||||
<Checkbox
|
||||
checked={item.done}
|
||||
disabled={!canToggle || !actorId}
|
||||
onCheckedChange={async (checked) => {
|
||||
if (!actorId || !canToggle) return
|
||||
try {
|
||||
await setChecklistItemDone({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
itemId: item.id,
|
||||
done: Boolean(checked),
|
||||
})
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao atualizar checklist.")
|
||||
}
|
||||
}}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
{editingId === item.id && canEdit && !isResolved ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={editingText}
|
||||
onChange={(e) => setEditingText(e.target.value)}
|
||||
className="h-9"
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
handleSaveText()
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
setEditingId(null)
|
||||
setEditingText("")
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button type="button" onClick={handleSaveText} disabled={savingText} className="h-9">
|
||||
Salvar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setEditingId(null)
|
||||
setEditingText("")
|
||||
}}
|
||||
className="h-9"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<p
|
||||
className={`truncate text-sm ${item.done ? "text-neutral-500 line-through" : "text-neutral-900"}`}
|
||||
title={item.text}
|
||||
onDoubleClick={() => {
|
||||
if (!canEdit || isResolved) return
|
||||
setEditingId(item.id)
|
||||
setEditingText(item.text)
|
||||
}}
|
||||
>
|
||||
{item.text}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
{required ? (
|
||||
<Badge variant="secondary" className="rounded-full text-[11px]">
|
||||
Obrigatório
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
Opcional
|
||||
</Badge>
|
||||
)}
|
||||
{templateLabel ? (
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
Template: {templateLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
{canEdit && !isResolved ? (
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="h-9 px-2 text-xs text-neutral-700 hover:bg-slate-50"
|
||||
onClick={async () => {
|
||||
if (!actorId) return
|
||||
try {
|
||||
await setChecklistItemRequired({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
itemId: item.id,
|
||||
required: !required,
|
||||
})
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao atualizar item.")
|
||||
}
|
||||
}}
|
||||
>
|
||||
{required ? "Tornar opcional" : "Tornar obrigatório"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 text-slate-500 hover:bg-red-50 hover:text-red-700"
|
||||
title="Remover"
|
||||
onClick={async () => {
|
||||
if (!actorId) return
|
||||
const ok = confirm("Remover este item do checklist?")
|
||||
if (!ok) return
|
||||
try {
|
||||
await removeChecklistItem({
|
||||
ticketId: ticket.id as Id<"tickets">,
|
||||
actorId,
|
||||
itemId: item.id,
|
||||
})
|
||||
toast.success("Item removido.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao remover item.")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canEdit && !isResolved ? (
|
||||
<div className="flex flex-col gap-2 rounded-xl border border-slate-200 bg-slate-50 p-3 sm:flex-row sm:items-center">
|
||||
<Input
|
||||
value={newText}
|
||||
onChange={(e) => setNewText(e.target.value)}
|
||||
placeholder="Adicionar item do checklist..."
|
||||
className="h-9 flex-1 bg-white"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
handleAdd()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm text-neutral-700">
|
||||
<Checkbox checked={newRequired} onCheckedChange={(checked) => setNewRequired(Boolean(checked))} />
|
||||
Obrigatório
|
||||
</label>
|
||||
<Button type="button" onClick={handleAdd} disabled={adding} className="h-9 gap-2">
|
||||
<Plus className="size-4" />
|
||||
Adicionar
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue