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
|
|
@ -676,9 +676,11 @@ export function CloseTicketDialog({
|
|||
onSuccess()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
toast.error(applyAdjustment ? "Não foi possível ajustar o tempo ou encerrar o ticket." : "Não foi possível encerrar o ticket.", {
|
||||
id: "close-ticket",
|
||||
})
|
||||
const fallback = applyAdjustment
|
||||
? "Não foi possível ajustar o tempo ou encerrar o ticket."
|
||||
: "Não foi possível encerrar o ticket."
|
||||
const message = error instanceof Error && error.message.trim().length > 0 ? error.message : fallback
|
||||
toast.error(message, { id: "close-ticket" })
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,9 +34,10 @@ import { cn } from "@/lib/utils"
|
|||
import { priorityStyles } from "@/lib/ticket-priority-style"
|
||||
import { normalizeCustomFieldInputs } from "@/lib/ticket-form-helpers"
|
||||
import type { TicketFormDefinition, TicketFormFieldDefinition } from "@/lib/ticket-form-types"
|
||||
import { Calendar as CalendarIcon } from "lucide-react"
|
||||
import { Calendar as CalendarIcon, ListChecks, Plus, Trash2 } from "lucide-react"
|
||||
import { TimePicker } from "@/components/ui/time-picker"
|
||||
import { VISIT_KEYWORDS } from "@/lib/ticket-matchers"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
|
||||
type TriggerVariant = "button" | "card"
|
||||
|
||||
|
|
@ -51,6 +52,19 @@ type CustomerOption = {
|
|||
avatarUrl: string | null
|
||||
}
|
||||
|
||||
type ChecklistDraftItem = {
|
||||
id: string
|
||||
text: string
|
||||
required: boolean
|
||||
}
|
||||
|
||||
type ChecklistTemplateOption = {
|
||||
id: Id<"ticketChecklistTemplates">
|
||||
name: string
|
||||
company: { id: Id<"companies">; name: string } | null
|
||||
items: Array<{ id: string; text: string; required: boolean }>
|
||||
}
|
||||
|
||||
function getInitials(name: string | null | undefined, fallback: string): string {
|
||||
const normalizedName = (name ?? "").trim()
|
||||
if (normalizedName.length > 0) {
|
||||
|
|
@ -219,6 +233,17 @@ export function NewTicketDialog({
|
|||
: "skip"
|
||||
) as TicketFormDefinition[] | undefined
|
||||
|
||||
const checklistTemplates = useQuery(
|
||||
api.checklistTemplates.listActive,
|
||||
convexUserId
|
||||
? {
|
||||
tenantId: DEFAULT_TENANT_ID,
|
||||
viewerId: convexUserId as Id<"users">,
|
||||
companyId: companyValue !== NO_COMPANY_VALUE ? (companyValue as Id<"companies">) : undefined,
|
||||
}
|
||||
: "skip"
|
||||
) as ChecklistTemplateOption[] | undefined
|
||||
|
||||
const forms = useMemo<TicketFormDefinition[]>(() => {
|
||||
const fallback: TicketFormDefinition = {
|
||||
key: "default",
|
||||
|
|
@ -240,6 +265,29 @@ export function NewTicketDialog({
|
|||
const [customFieldValues, setCustomFieldValues] = useState<Record<string, unknown>>({})
|
||||
const [openCalendarField, setOpenCalendarField] = useState<string | null>(null)
|
||||
const [visitDatePickerOpen, setVisitDatePickerOpen] = useState(false)
|
||||
const [manualChecklist, setManualChecklist] = useState<ChecklistDraftItem[]>([])
|
||||
const [appliedChecklistTemplateIds, setAppliedChecklistTemplateIds] = useState<string[]>([])
|
||||
const [checklistTemplateToApply, setChecklistTemplateToApply] = useState<string>("")
|
||||
const [checklistItemText, setChecklistItemText] = useState("")
|
||||
const [checklistItemRequired, setChecklistItemRequired] = useState(true)
|
||||
|
||||
const appliedChecklistTemplates = useMemo(() => {
|
||||
const selected = new Set(appliedChecklistTemplateIds.map(String))
|
||||
return (checklistTemplates ?? []).filter((tpl) => selected.has(String(tpl.id)))
|
||||
}, [appliedChecklistTemplateIds, checklistTemplates])
|
||||
|
||||
const checklistTemplatePreviewItems = useMemo(
|
||||
() =>
|
||||
appliedChecklistTemplates.flatMap((tpl) =>
|
||||
(tpl.items ?? []).map((item) => ({
|
||||
key: `${String(tpl.id)}:${item.id}`,
|
||||
text: item.text,
|
||||
required: item.required,
|
||||
templateName: tpl.name,
|
||||
}))
|
||||
),
|
||||
[appliedChecklistTemplates]
|
||||
)
|
||||
|
||||
const selectedForm = useMemo(() => forms.find((formDef) => formDef.key === selectedFormKey) ?? forms[0], [forms, selectedFormKey])
|
||||
|
||||
|
|
@ -418,6 +466,11 @@ export function NewTicketDialog({
|
|||
useEffect(() => {
|
||||
if (!open) {
|
||||
setCustomersInitialized(false)
|
||||
setManualChecklist([])
|
||||
setAppliedChecklistTemplateIds([])
|
||||
setChecklistTemplateToApply("")
|
||||
setChecklistItemText("")
|
||||
setChecklistItemRequired(true)
|
||||
form.setValue("companyId", NO_COMPANY_VALUE, { shouldDirty: false, shouldTouch: false })
|
||||
form.setValue("requesterId", "", { shouldDirty: false, shouldTouch: false })
|
||||
return
|
||||
|
|
@ -521,6 +574,31 @@ export function NewTicketDialog({
|
|||
}
|
||||
}
|
||||
|
||||
const handleApplyChecklistTemplate = () => {
|
||||
const templateId = checklistTemplateToApply.trim()
|
||||
if (!templateId) return
|
||||
setAppliedChecklistTemplateIds((prev) => {
|
||||
if (prev.includes(templateId)) return prev
|
||||
return [...prev, templateId]
|
||||
})
|
||||
setChecklistTemplateToApply("")
|
||||
}
|
||||
|
||||
const handleAddChecklistItem = () => {
|
||||
const text = checklistItemText.trim()
|
||||
if (!text) {
|
||||
toast.error("Informe o texto do item do checklist.", { id: "new-ticket" })
|
||||
return
|
||||
}
|
||||
if (text.length > 240) {
|
||||
toast.error("Item do checklist muito longo (máx. 240 caracteres).", { id: "new-ticket" })
|
||||
return
|
||||
}
|
||||
setManualChecklist((prev) => [...prev, { id: crypto.randomUUID(), text, required: checklistItemRequired }])
|
||||
setChecklistItemText("")
|
||||
setChecklistItemRequired(true)
|
||||
}
|
||||
|
||||
async function submit(values: z.infer<typeof schema>) {
|
||||
if (!convexUserId) return
|
||||
|
||||
|
|
@ -562,6 +640,17 @@ export function NewTicketDialog({
|
|||
}
|
||||
customFieldsPayload = normalized.payload
|
||||
}
|
||||
const checklistPayload = manualChecklist.map((item) => ({
|
||||
text: item.text.trim(),
|
||||
required: item.required,
|
||||
}))
|
||||
const invalidChecklist = checklistPayload.find((item) => item.text.length === 0 || item.text.length > 240)
|
||||
if (invalidChecklist) {
|
||||
toast.error("Revise os itens do checklist (texto obrigatório e até 240 caracteres).", { id: "new-ticket" })
|
||||
return
|
||||
}
|
||||
const checklistTemplateIds = appliedChecklistTemplateIds.map((id) => id as Id<"ticketChecklistTemplates">)
|
||||
|
||||
setLoading(true)
|
||||
toast.loading("Criando ticket…", { id: "new-ticket" })
|
||||
try {
|
||||
|
|
@ -590,6 +679,8 @@ export function NewTicketDialog({
|
|||
categoryId: values.categoryId as Id<"ticketCategories">,
|
||||
subcategoryId: values.subcategoryId as Id<"ticketSubcategories">,
|
||||
formTemplate: selectedFormKey !== "default" ? selectedFormKey : undefined,
|
||||
checklist: checklistPayload.length > 0 ? checklistPayload : undefined,
|
||||
checklistTemplateIds: checklistTemplateIds.length > 0 ? checklistTemplateIds : undefined,
|
||||
customFields: customFieldsPayload.length > 0 ? customFieldsPayload : undefined,
|
||||
visitDate: visitDateTimestamp,
|
||||
})
|
||||
|
|
@ -630,6 +721,11 @@ export function NewTicketDialog({
|
|||
setCustomFieldValues({})
|
||||
setAssigneeInitialized(false)
|
||||
setAttachments([])
|
||||
setManualChecklist([])
|
||||
setAppliedChecklistTemplateIds([])
|
||||
setChecklistTemplateToApply("")
|
||||
setChecklistItemText("")
|
||||
setChecklistItemRequired(true)
|
||||
// Navegar para o ticket recém-criado
|
||||
window.location.href = `/tickets/${id}`
|
||||
} catch {
|
||||
|
|
@ -1264,6 +1360,166 @@ export function NewTicketDialog({
|
|||
</div>
|
||||
) : null}
|
||||
</FieldGroup>
|
||||
|
||||
<div className="mt-6 rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<p className="flex items-center gap-2 text-sm font-semibold text-neutral-900">
|
||||
<ListChecks className="size-4 text-neutral-700" />
|
||||
Checklist (opcional)
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-neutral-500">
|
||||
Itens obrigatórios bloqueiam o encerramento do ticket até serem concluídos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{(checklistTemplates ?? []).length > 0 ? (
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Select value={checklistTemplateToApply} onValueChange={setChecklistTemplateToApply}>
|
||||
<SelectTrigger className="h-9 w-full sm:w-64">
|
||||
<SelectValue placeholder="Aplicar template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
{(checklistTemplates ?? []).map((tpl) => (
|
||||
<SelectItem key={tpl.id} value={String(tpl.id)}>
|
||||
{tpl.name}
|
||||
{tpl.company ? ` — ${tpl.company.name}` : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-9"
|
||||
onClick={handleApplyChecklistTemplate}
|
||||
disabled={
|
||||
!checklistTemplateToApply.trim() ||
|
||||
appliedChecklistTemplateIds.includes(checklistTemplateToApply.trim())
|
||||
}
|
||||
>
|
||||
Aplicar
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{appliedChecklistTemplates.length > 0 ? (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{appliedChecklistTemplates.map((tpl) => (
|
||||
<Badge key={tpl.id} variant="secondary" className="flex items-center gap-2 rounded-full">
|
||||
<span className="truncate">{tpl.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-neutral-600 hover:text-neutral-900"
|
||||
onClick={() =>
|
||||
setAppliedChecklistTemplateIds((prev) => prev.filter((id) => id !== String(tpl.id)))
|
||||
}
|
||||
title="Remover template"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{checklistTemplatePreviewItems.length > 0 || manualChecklist.length > 0 ? (
|
||||
<div className="mt-4 space-y-2">
|
||||
{checklistTemplatePreviewItems.map((item) => (
|
||||
<div
|
||||
key={item.key}
|
||||
className="flex items-start justify-between gap-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm text-neutral-800" title={item.text}>
|
||||
{item.text}
|
||||
</p>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
<Badge variant={item.required ? "secondary" : "outline"} className="rounded-full text-[11px]">
|
||||
{item.required ? "Obrigatório" : "Opcional"}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
Template: {item.templateName}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{manualChecklist.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex flex-col gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 sm:flex-row sm:items-center"
|
||||
>
|
||||
<Input
|
||||
value={item.text}
|
||||
onChange={(e) =>
|
||||
setManualChecklist((prev) =>
|
||||
prev.map((row) => (row.id === item.id ? { ...row, text: e.target.value } : row))
|
||||
)
|
||||
}
|
||||
placeholder="Item do checklist..."
|
||||
className="h-9 flex-1"
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm text-neutral-700">
|
||||
<Checkbox
|
||||
checked={item.required}
|
||||
onCheckedChange={(checked) =>
|
||||
setManualChecklist((prev) =>
|
||||
prev.map((row) =>
|
||||
row.id === item.id ? { ...row, required: Boolean(checked) } : row
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
Obrigatório
|
||||
</label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 text-slate-500 hover:bg-red-50 hover:text-red-700"
|
||||
onClick={() => setManualChecklist((prev) => prev.filter((row) => row.id !== item.id))}
|
||||
title="Remover"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-3 rounded-xl border border-dashed border-slate-200 p-4 text-sm text-neutral-600">
|
||||
Adicione itens ou aplique um template para criar um checklist neste ticket.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Input
|
||||
value={checklistItemText}
|
||||
onChange={(e) => setChecklistItemText(e.target.value)}
|
||||
placeholder="Adicionar item do checklist..."
|
||||
className="h-9 flex-1"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
handleAddChecklistItem()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm text-neutral-700">
|
||||
<Checkbox
|
||||
checked={checklistItemRequired}
|
||||
onCheckedChange={(checked) => setChecklistItemRequired(Boolean(checked))}
|
||||
/>
|
||||
Obrigatório
|
||||
</label>
|
||||
<Button type="button" onClick={handleAddChecklistItem} className="h-9 gap-2">
|
||||
<Plus className="size-4" />
|
||||
Adicionar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</FieldSet>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
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>
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -36,6 +36,7 @@ type TicketCustomFieldsListProps = {
|
|||
actionSlot?: ReactNode
|
||||
}
|
||||
|
||||
const CLEAR_SELECT_VALUE = "__clear__"
|
||||
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
const DEFAULT_FORM: TicketFormDefinition = {
|
||||
|
|
@ -483,13 +484,22 @@ function renderFieldEditor(field: TicketFormFieldDefinition) {
|
|||
<FieldLabel className="flex items-center gap-1">
|
||||
{field.label} {field.required ? <span className="text-destructive">*</span> : null}
|
||||
</FieldLabel>
|
||||
<Select value={typeof value === "string" ? value : ""} onValueChange={(selected) => handleFieldChange(field, selected)}>
|
||||
<Select
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onValueChange={(selected) => {
|
||||
if (selected === CLEAR_SELECT_VALUE) {
|
||||
handleClearField(field.id)
|
||||
return
|
||||
}
|
||||
handleFieldChange(field, selected)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-60 overflow-y-auto rounded-xl border border-slate-200 bg-white text-neutral-800 shadow-md">
|
||||
{!field.required ? (
|
||||
<SelectItem value="" className="text-neutral-500">
|
||||
<SelectItem value={CLEAR_SELECT_VALUE} className="text-neutral-500">
|
||||
Limpar seleção
|
||||
</SelectItem>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { TicketSummaryHeader } from "@/components/tickets/ticket-summary-header"
|
|||
import { TicketTimeline } from "@/components/tickets/ticket-timeline";
|
||||
import { TicketCsatCard } from "@/components/tickets/ticket-csat-card";
|
||||
import { TicketChatHistory } from "@/components/tickets/ticket-chat-history";
|
||||
import { TicketChecklistCard } from "@/components/tickets/ticket-checklist-card";
|
||||
import { useAuth } from "@/lib/auth-client";
|
||||
|
||||
export function TicketDetailView({ id }: { id: string }) {
|
||||
|
|
@ -107,6 +108,7 @@ export function TicketDetailView({ id }: { id: string }) {
|
|||
<TicketCsatCard ticket={ticket} />
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="space-y-6">
|
||||
<TicketChecklistCard ticket={ticket} />
|
||||
<TicketComments ticket={ticket} />
|
||||
<TicketTimeline ticket={ticket} />
|
||||
<TicketChatHistory ticketId={id} />
|
||||
|
|
|
|||
|
|
@ -175,6 +175,10 @@ export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
|
|||
const viewerEmailRaw = session?.user?.email ?? machineContext?.assignedUserEmail ?? null
|
||||
const viewerEmail = (viewerEmailRaw ?? "").trim().toLowerCase()
|
||||
const [status, setStatus] = useState<TicketStatus>(ticket.status)
|
||||
const checklistRequiredPending = useMemo(() => {
|
||||
const list = ticket.checklist ?? []
|
||||
return list.filter((item) => (item.required ?? true) && !item.done).length
|
||||
}, [ticket.checklist])
|
||||
const [visitStatusLoading, setVisitStatusLoading] = useState(false)
|
||||
const rawReopenDeadline = ticket.reopenDeadline ?? null
|
||||
const fallbackClosedMs = ticket.closedAt?.getTime() ?? ticket.resolvedAt?.getTime() ?? null
|
||||
|
|
@ -1348,13 +1352,33 @@ export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
|
|||
<div className="absolute right-6 top-6 flex flex-col items-end gap-1">
|
||||
<div className="flex items-center gap-3">
|
||||
{status !== "RESOLVED" ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-2 rounded-lg border border-sidebar-border bg-sidebar-accent px-3 py-1.5 text-sm font-semibold text-sidebar-accent-foreground transition-all duration-200 ease-out hover:-translate-y-0.5 hover:border-sidebar-ring hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--sidebar-ring)]/30 active:translate-y-0 active:border-sidebar-ring"
|
||||
onClick={() => setCloseOpen(true)}
|
||||
>
|
||||
<CheckCircle2 className="size-4" /> Encerrar
|
||||
</Button>
|
||||
checklistRequiredPending > 0 ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span>
|
||||
<Button
|
||||
type="button"
|
||||
disabled
|
||||
className="inline-flex items-center gap-2 rounded-lg border border-sidebar-border bg-sidebar-accent px-3 py-1.5 text-sm font-semibold text-sidebar-accent-foreground opacity-70"
|
||||
>
|
||||
<CheckCircle2 className="size-4" /> Encerrar
|
||||
</Button>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-neutral-700 shadow-lg">
|
||||
Conclua o checklist antes de encerrar ({checklistRequiredPending} pendente
|
||||
{checklistRequiredPending === 1 ? "" : "s"}).
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-2 rounded-lg border border-sidebar-border bg-sidebar-accent px-3 py-1.5 text-sm font-semibold text-sidebar-accent-foreground transition-all duration-200 ease-out hover:-translate-y-0.5 hover:border-sidebar-ring hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--sidebar-ring)]/30 active:translate-y-0 active:border-sidebar-ring"
|
||||
onClick={() => setCloseOpen(true)}
|
||||
>
|
||||
<CheckCircle2 className="size-4" /> Encerrar
|
||||
</Button>
|
||||
)
|
||||
) : canReopenTicket ? (
|
||||
<Button
|
||||
type="button"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue