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
27
src/app/settings/checklists/page.tsx
Normal file
27
src/app/settings/checklists/page.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { AppShell } from "@/components/app-shell"
|
||||
import { ChecklistTemplatesManager } from "@/components/settings/checklist-templates-manager"
|
||||
import { SiteHeader } from "@/components/site-header"
|
||||
import { requireAdminSession } from "@/lib/auth-server"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
export const runtime = "nodejs"
|
||||
|
||||
export default async function ChecklistTemplatesPage() {
|
||||
await requireAdminSession()
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
header={
|
||||
<SiteHeader
|
||||
title="Templates de checklist"
|
||||
lead="Crie modelos globais ou por empresa para padronizar tarefas do atendimento."
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="mx-auto w-full max-w-6xl px-6 pb-12 lg:px-8">
|
||||
<ChecklistTemplatesManager />
|
||||
</div>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -32,6 +32,8 @@ type Template = {
|
|||
order: number
|
||||
}
|
||||
|
||||
const CLEAR_SELECT_VALUE = "__clear__"
|
||||
|
||||
export function TicketFormTemplatesManager() {
|
||||
const { session, convexUserId } = useAuth()
|
||||
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
|
|
@ -276,12 +278,15 @@ export function TicketFormTemplatesManager() {
|
|||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-neutral-700">Basear em</label>
|
||||
<Select value={baseTemplate} onValueChange={setBaseTemplate}>
|
||||
<Select
|
||||
value={baseTemplate}
|
||||
onValueChange={(value) => setBaseTemplate(value === CLEAR_SELECT_VALUE ? "" : value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Em branco" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="">Começar do zero</SelectItem>
|
||||
<SelectItem value={CLEAR_SELECT_VALUE}>Começar do zero</SelectItem>
|
||||
{baseOptions.map((tpl) => (
|
||||
<SelectItem key={tpl.key} value={tpl.key}>
|
||||
{tpl.label}
|
||||
|
|
|
|||
|
|
@ -120,6 +120,7 @@ const navigation: NavigationGroup[] = [
|
|||
{ title: "Usuários", url: "/admin/users", icon: Users, requiredRole: "admin" },
|
||||
{ title: "Campos personalizados", url: "/admin/custom-fields", icon: ClipboardList, requiredRole: "admin" },
|
||||
{ title: "Templates de comentários", url: "/settings/templates", icon: LayoutTemplate, requiredRole: "admin" },
|
||||
{ title: "Templates de checklist", url: "/settings/checklists", icon: ClipboardList, requiredRole: "admin" },
|
||||
{ title: "Templates de relatórios", url: "/admin/report-templates", icon: LayoutTemplate, requiredRole: "admin" },
|
||||
],
|
||||
},
|
||||
|
|
@ -340,7 +341,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
|||
|
||||
return (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton asChild isActive={isActive(item)}>
|
||||
<SidebarMenuButton asChild isActive={isActive(item)} className="font-medium">
|
||||
<Link href={item.url} className="gap-2">
|
||||
{item.icon ? <item.icon className="size-4" /> : null}
|
||||
<span>{item.title}</span>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
|||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { DialogClose, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { DialogClose, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
|
|
@ -58,6 +58,7 @@ type ActionType =
|
|||
| "SET_FORM_TEMPLATE"
|
||||
| "SET_CHAT_ENABLED"
|
||||
| "ADD_INTERNAL_COMMENT"
|
||||
| "APPLY_CHECKLIST_TEMPLATE"
|
||||
| "SEND_EMAIL"
|
||||
|
||||
type EmailCtaTarget = "AUTO" | "PORTAL" | "STAFF"
|
||||
|
|
@ -69,6 +70,7 @@ type ActionDraft =
|
|||
| { id: string; type: "SET_FORM_TEMPLATE"; formTemplate: string | null }
|
||||
| { id: string; type: "SET_CHAT_ENABLED"; enabled: boolean }
|
||||
| { id: string; type: "ADD_INTERNAL_COMMENT"; body: string }
|
||||
| { id: string; type: "APPLY_CHECKLIST_TEMPLATE"; templateId: string }
|
||||
| {
|
||||
id: string
|
||||
type: "SEND_EMAIL"
|
||||
|
|
@ -112,6 +114,8 @@ const TRIGGERS = [
|
|||
{ value: "TICKET_RESOLVED", label: "Finalização" },
|
||||
]
|
||||
|
||||
const CLEAR_SELECT_VALUE = "__clear__"
|
||||
|
||||
function msToMinutes(ms: number | null) {
|
||||
if (!ms || ms <= 0) return 0
|
||||
return Math.max(1, Math.round(ms / 60000))
|
||||
|
|
@ -197,6 +201,7 @@ function toDraftActions(raw: unknown[]): ActionDraft[] {
|
|||
if (type === "SET_FORM_TEMPLATE") return { id, type, formTemplate: safeString(base.formTemplate) || null }
|
||||
if (type === "SET_CHAT_ENABLED") return { id, type, enabled: Boolean(base.enabled) }
|
||||
if (type === "ADD_INTERNAL_COMMENT") return { id, type, body: safeString(base.body) }
|
||||
if (type === "APPLY_CHECKLIST_TEMPLATE") return { id, type, templateId: safeString(base.templateId) }
|
||||
return { id, type: "SET_PRIORITY", priority: safeString(base.priority) || "MEDIUM" }
|
||||
})
|
||||
}
|
||||
|
|
@ -245,6 +250,11 @@ export function AutomationEditorDialog({
|
|||
convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
|
||||
) as Array<{ id: string; key: string; label: string }> | undefined
|
||||
|
||||
const checklistTemplates = useQuery(
|
||||
api.checklistTemplates.listActive,
|
||||
convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
|
||||
) as Array<{ id: Id<"ticketChecklistTemplates">; name: string; company: { id: Id<"companies">; name: string } | null }> | undefined
|
||||
|
||||
const initialState = useMemo(() => {
|
||||
const rawOp = (automation?.conditions as { op?: unknown } | null)?.op
|
||||
const conditionsOp = rawOp === "OR" ? ("OR" as const) : ("AND" as const)
|
||||
|
|
@ -337,6 +347,11 @@ export function AutomationEditorDialog({
|
|||
if (a.type === "ASSIGN_TO") return { type: a.type, assigneeId: a.assigneeId }
|
||||
if (a.type === "SET_FORM_TEMPLATE") return { type: a.type, formTemplate: a.formTemplate }
|
||||
if (a.type === "SET_CHAT_ENABLED") return { type: a.type, enabled: a.enabled }
|
||||
if (a.type === "APPLY_CHECKLIST_TEMPLATE") {
|
||||
const templateId = a.templateId.trim()
|
||||
if (!templateId) throw new Error("Selecione um template de checklist.")
|
||||
return { type: a.type, templateId }
|
||||
}
|
||||
if (a.type === "SEND_EMAIL") {
|
||||
const subject = a.subject.trim()
|
||||
const message = a.message.trim()
|
||||
|
|
@ -422,6 +437,11 @@ export function AutomationEditorDialog({
|
|||
<DialogHeader className="gap-4 pb-2">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<DialogTitle>{automation ? "Editar automação" : "Nova automação"}</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
{automation
|
||||
? "Edite as condições e ações que devem disparar automaticamente nos tickets."
|
||||
: "Crie uma automação definindo condições e ações automáticas para tickets."}
|
||||
</DialogDescription>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium text-neutral-700">Ativa</span>
|
||||
<Switch
|
||||
|
|
@ -733,15 +753,18 @@ export function AutomationEditorDialog({
|
|||
) : (
|
||||
<Select
|
||||
value={c.value}
|
||||
onValueChange={(value) =>
|
||||
setConditions((prev) => prev.map((item) => (item.id === c.id ? { ...item, value } : item)))
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
const nextValue = value === CLEAR_SELECT_VALUE ? "" : value
|
||||
setConditions((prev) =>
|
||||
prev.map((item) => (item.id === c.id ? { ...item, value: nextValue } : item))
|
||||
)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="bg-white">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
<SelectItem value="">Nenhum</SelectItem>
|
||||
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||
{(templates ?? []).map((tpl) => (
|
||||
<SelectItem key={tpl.key} value={tpl.key}>
|
||||
{tpl.label}
|
||||
|
|
@ -797,13 +820,14 @@ export function AutomationEditorDialog({
|
|||
const next = value as ActionType
|
||||
if (next === "MOVE_QUEUE") return { id: item.id, type: next, queueId: "" }
|
||||
if (next === "ASSIGN_TO") return { id: item.id, type: next, assigneeId: "" }
|
||||
if (next === "SET_FORM_TEMPLATE") return { id: item.id, type: next, formTemplate: null }
|
||||
if (next === "SET_CHAT_ENABLED") return { id: item.id, type: next, enabled: true }
|
||||
if (next === "ADD_INTERNAL_COMMENT") return { id: item.id, type: next, body: "" }
|
||||
if (next === "SEND_EMAIL") {
|
||||
return {
|
||||
id: item.id,
|
||||
type: next,
|
||||
if (next === "SET_FORM_TEMPLATE") return { id: item.id, type: next, formTemplate: null }
|
||||
if (next === "SET_CHAT_ENABLED") return { id: item.id, type: next, enabled: true }
|
||||
if (next === "ADD_INTERNAL_COMMENT") return { id: item.id, type: next, body: "" }
|
||||
if (next === "APPLY_CHECKLIST_TEMPLATE") return { id: item.id, type: next, templateId: "" }
|
||||
if (next === "SEND_EMAIL") {
|
||||
return {
|
||||
id: item.id,
|
||||
type: next,
|
||||
subject: "",
|
||||
message: "",
|
||||
toRequester: true,
|
||||
|
|
@ -829,6 +853,7 @@ export function AutomationEditorDialog({
|
|||
<SelectItem value="SET_FORM_TEMPLATE">Aplicar formulário</SelectItem>
|
||||
<SelectItem value="SET_CHAT_ENABLED">Habilitar/desabilitar chat</SelectItem>
|
||||
<SelectItem value="ADD_INTERNAL_COMMENT">Adicionar comentário interno</SelectItem>
|
||||
<SelectItem value="APPLY_CHECKLIST_TEMPLATE">Aplicar checklist (template)</SelectItem>
|
||||
<SelectItem value="SEND_EMAIL">Enviar e-mail</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
|
@ -893,15 +918,18 @@ export function AutomationEditorDialog({
|
|||
) : a.type === "SET_FORM_TEMPLATE" ? (
|
||||
<Select
|
||||
value={a.formTemplate ?? ""}
|
||||
onValueChange={(value) =>
|
||||
setActions((prev) => prev.map((item) => (item.id === a.id ? { ...item, formTemplate: value || null } : item)))
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
const nextValue = value === CLEAR_SELECT_VALUE ? null : value
|
||||
setActions((prev) =>
|
||||
prev.map((item) => (item.id === a.id ? { ...item, formTemplate: nextValue } : item))
|
||||
)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
<SelectItem value="">Nenhum</SelectItem>
|
||||
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||
{(templates ?? []).map((tpl) => (
|
||||
<SelectItem key={tpl.key} value={tpl.key}>
|
||||
{tpl.label}
|
||||
|
|
@ -920,6 +948,25 @@ export function AutomationEditorDialog({
|
|||
className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300"
|
||||
/>
|
||||
</div>
|
||||
) : a.type === "APPLY_CHECKLIST_TEMPLATE" ? (
|
||||
<Select
|
||||
value={a.templateId}
|
||||
onValueChange={(value) =>
|
||||
setActions((prev) => prev.map((item) => (item.id === a.id ? { ...item, templateId: value } : item)))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</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>
|
||||
) : a.type === "SEND_EMAIL" ? (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
|
|
@ -982,15 +1029,18 @@ export function AutomationEditorDialog({
|
|||
<Label className="text-xs">Agente específico (opcional)</Label>
|
||||
<Select
|
||||
value={a.toUserId}
|
||||
onValueChange={(value) =>
|
||||
setActions((prev) => prev.map((item) => (item.id === a.id ? { ...item, toUserId: value } : item)))
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
const nextValue = value === CLEAR_SELECT_VALUE ? "" : value
|
||||
setActions((prev) =>
|
||||
prev.map((item) => (item.id === a.id ? { ...item, toUserId: nextValue } : item))
|
||||
)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
<SelectItem value="">Nenhum</SelectItem>
|
||||
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||
{(agents ?? []).map((u) => (
|
||||
<SelectItem key={u._id} value={String(u._id)}>
|
||||
{u.name}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { useAuth } from "@/lib/auth-client"
|
|||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DialogClose, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { DialogClose, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
|
|
@ -94,6 +94,9 @@ export function AutomationRunsDialog({
|
|||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<DialogTitle>Histórico de execuções</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
Veja as execuções recentes da automação, com status, evento e ticket relacionado.
|
||||
</DialogDescription>
|
||||
{automationName ? (
|
||||
<p className="text-sm text-neutral-600">{automationName}</p>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -155,7 +155,7 @@ export function AutomationsManager() {
|
|||
<CardHeader>
|
||||
<CardTitle className="text-lg font-semibold text-neutral-900">Automações</CardTitle>
|
||||
<CardDescription className="text-neutral-600">
|
||||
Crie gatilhos para executar ações automáticas (fila, prioridade, responsável, formulário, chat…).
|
||||
Crie gatilhos para executar ações automáticas.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
||||
|
|
|
|||
387
src/components/settings/checklist-templates-manager.tsx
Normal file
387
src/components/settings/checklist-templates-manager.tsx
Normal file
|
|
@ -0,0 +1,387 @@
|
|||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { useAuth } from "@/lib/auth-client"
|
||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||
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 { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
|
||||
type ChecklistTemplateRow = {
|
||||
id: Id<"ticketChecklistTemplates">
|
||||
name: string
|
||||
description: string
|
||||
company: { id: Id<"companies">; name: string } | null
|
||||
items: Array<{ id: string; text: string; required: boolean }>
|
||||
isArchived: boolean
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
type CompanyRow = { id: Id<"companies">; name: string }
|
||||
|
||||
type DraftItem = { id: string; text: string; required: boolean }
|
||||
|
||||
const NO_COMPANY_VALUE = "__global__"
|
||||
|
||||
function normalizeTemplateItems(items: DraftItem[]) {
|
||||
const normalized = items
|
||||
.map((item) => ({ ...item, text: item.text.trim() }))
|
||||
.filter((item) => item.text.length > 0)
|
||||
|
||||
if (normalized.length === 0) {
|
||||
throw new Error("Adicione pelo menos um item no checklist.")
|
||||
}
|
||||
const invalid = normalized.find((item) => item.text.length > 240)
|
||||
if (invalid) {
|
||||
throw new Error("Item do checklist muito longo (máx. 240 caracteres).")
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function TemplateEditorDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
template,
|
||||
companies,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
template: ChecklistTemplateRow | null
|
||||
companies: CompanyRow[]
|
||||
}) {
|
||||
const { convexUserId, session } = useAuth()
|
||||
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
const actorId = convexUserId as Id<"users"> | null
|
||||
|
||||
const createTemplate = useMutation(api.checklistTemplates.create)
|
||||
const updateTemplate = useMutation(api.checklistTemplates.update)
|
||||
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [name, setName] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [companyValue, setCompanyValue] = useState<string>(NO_COMPANY_VALUE)
|
||||
const [items, setItems] = useState<DraftItem[]>([{ id: crypto.randomUUID(), text: "", required: true }])
|
||||
const [archived, setArchived] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setName(template?.name ?? "")
|
||||
setDescription(template?.description ?? "")
|
||||
setCompanyValue(template?.company?.id ? String(template.company.id) : NO_COMPANY_VALUE)
|
||||
setItems(
|
||||
template?.items?.length
|
||||
? template.items.map((item) => ({ id: item.id, text: item.text, required: item.required }))
|
||||
: [{ id: crypto.randomUUID(), text: "", required: true }]
|
||||
)
|
||||
setArchived(template?.isArchived ?? false)
|
||||
}, [open, template])
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!actorId) return
|
||||
const trimmedName = name.trim()
|
||||
if (trimmedName.length < 3) {
|
||||
toast.error("Informe um nome com pelo menos 3 caracteres.")
|
||||
return
|
||||
}
|
||||
let normalizedItems: DraftItem[]
|
||||
try {
|
||||
normalizedItems = normalizeTemplateItems(items)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Itens do checklist inválidos.")
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
tenantId,
|
||||
actorId,
|
||||
name: trimmedName,
|
||||
description: description.trim().length > 0 ? description.trim() : undefined,
|
||||
companyId: companyValue !== NO_COMPANY_VALUE ? (companyValue as Id<"companies">) : undefined,
|
||||
items: normalizedItems.map((item) => ({ id: item.id, text: item.text, required: item.required })),
|
||||
isArchived: archived,
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
if (template) {
|
||||
await updateTemplate({ templateId: template.id, ...payload })
|
||||
toast.success("Template atualizado.")
|
||||
} else {
|
||||
await createTemplate(payload)
|
||||
toast.success("Template criado.")
|
||||
}
|
||||
onOpenChange(false)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao salvar template.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const canSave = Boolean(actorId) && !saving
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-3xl">
|
||||
<DialogHeader className="gap-1">
|
||||
<DialogTitle>{template ? "Editar template de checklist" : "Novo template de checklist"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-5">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label>Nome</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Ex.: Checklist de instalação" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Empresa</Label>
|
||||
<Select value={companyValue} onValueChange={setCompanyValue}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Global" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
<SelectItem value={NO_COMPANY_VALUE}>Global (todas)</SelectItem>
|
||||
{companies.map((company) => (
|
||||
<SelectItem key={company.id} value={String(company.id)}>
|
||||
{company.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Descrição (opcional)</Label>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Quando usar este checklist?" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-semibold text-neutral-900">Itens</p>
|
||||
<p className="text-xs text-muted-foreground">Defina o que precisa ser feito. Itens obrigatórios bloqueiam o encerramento.</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
onClick={() => setItems((prev) => [...prev, { id: crypto.randomUUID(), text: "", required: true }])}
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Novo item
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="flex flex-col gap-2 rounded-xl border border-slate-200 bg-white p-3 sm:flex-row sm:items-center">
|
||||
<Input
|
||||
value={item.text}
|
||||
onChange={(e) =>
|
||||
setItems((prev) => prev.map((row) => (row.id === item.id ? { ...row, text: e.target.value } : row)))
|
||||
}
|
||||
placeholder="Ex.: Validar backup"
|
||||
className="h-9 flex-1"
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm text-neutral-700">
|
||||
<Checkbox
|
||||
checked={item.required}
|
||||
onCheckedChange={(checked) =>
|
||||
setItems((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={() => setItems((prev) => prev.filter((row) => row.id !== item.id))}
|
||||
title="Remover"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium text-neutral-700">Arquivado</span>
|
||||
<Switch checked={archived} onCheckedChange={setArchived} className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSave} disabled={!canSave}>
|
||||
Salvar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export function ChecklistTemplatesManager() {
|
||||
const { convexUserId, session } = useAuth()
|
||||
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
const viewerId = convexUserId as Id<"users"> | null
|
||||
|
||||
const [includeArchived, setIncludeArchived] = useState(false)
|
||||
const [editorOpen, setEditorOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<ChecklistTemplateRow | null>(null)
|
||||
|
||||
const templates = useQuery(
|
||||
api.checklistTemplates.list,
|
||||
viewerId ? { tenantId, viewerId, includeArchived } : "skip"
|
||||
) as ChecklistTemplateRow[] | undefined
|
||||
|
||||
const companies = useQuery(
|
||||
api.companies.list,
|
||||
viewerId ? { tenantId, viewerId } : "skip"
|
||||
) as Array<{ id: Id<"companies">; name: string }> | undefined
|
||||
|
||||
const updateTemplate = useMutation(api.checklistTemplates.update)
|
||||
|
||||
const companyOptions = useMemo<CompanyRow[]>(
|
||||
() => (companies ?? []).map((c) => ({ id: c.id, name: c.name })).sort((a, b) => a.name.localeCompare(b.name, "pt-BR")),
|
||||
[companies]
|
||||
)
|
||||
|
||||
const orderedTemplates = useMemo(() => (templates ?? []).slice().sort((a, b) => b.updatedAt - a.updatedAt), [templates])
|
||||
|
||||
const handleNew = () => {
|
||||
setEditing(null)
|
||||
setEditorOpen(true)
|
||||
}
|
||||
|
||||
const handleEdit = (tpl: ChecklistTemplateRow) => {
|
||||
setEditing(tpl)
|
||||
setEditorOpen(true)
|
||||
}
|
||||
|
||||
const handleToggleArchived = async (tpl: ChecklistTemplateRow) => {
|
||||
if (!viewerId) return
|
||||
try {
|
||||
await updateTemplate({
|
||||
tenantId,
|
||||
actorId: viewerId,
|
||||
templateId: tpl.id,
|
||||
name: tpl.name,
|
||||
description: tpl.description || undefined,
|
||||
companyId: tpl.company?.id ?? undefined,
|
||||
items: tpl.items.map((item) => ({ id: item.id, text: item.text, required: item.required })),
|
||||
isArchived: !tpl.isArchived,
|
||||
})
|
||||
toast.success(tpl.isArchived ? "Template restaurado." : "Template arquivado.")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Falha ao atualizar template.")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card className="border border-slate-200">
|
||||
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-xl font-semibold text-neutral-900">Templates de checklist</CardTitle>
|
||||
<CardDescription className="text-sm text-neutral-600">
|
||||
Crie modelos globais ou por empresa para padronizar tarefas de atendimento.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className="flex items-center gap-2 text-sm text-neutral-700">
|
||||
<Switch
|
||||
checked={includeArchived}
|
||||
onCheckedChange={setIncludeArchived}
|
||||
className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300"
|
||||
/>
|
||||
Exibir arquivados
|
||||
</label>
|
||||
<Button type="button" onClick={handleNew} className="gap-2">
|
||||
<Plus className="size-4" />
|
||||
Novo template
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!templates ? (
|
||||
<p className="text-sm text-neutral-600">Carregando templates...</p>
|
||||
) : orderedTemplates.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-slate-200 p-6 text-sm text-neutral-600">
|
||||
Nenhum template cadastrado.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{orderedTemplates.map((tpl) => (
|
||||
<div key={tpl.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="truncate text-sm font-semibold text-neutral-900">{tpl.name}</p>
|
||||
{tpl.isArchived ? (
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
Arquivado
|
||||
</Badge>
|
||||
) : null}
|
||||
{tpl.company ? (
|
||||
<Badge variant="secondary" className="rounded-full text-[11px]">
|
||||
{tpl.company.name}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
Global
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant="outline" className="rounded-full text-[11px]">
|
||||
{tpl.items.length} item{tpl.items.length === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
</div>
|
||||
{tpl.description ? (
|
||||
<p className="mt-1 text-xs text-neutral-500">{tpl.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => handleEdit(tpl)}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => handleToggleArchived(tpl)}>
|
||||
{tpl.isArchived ? "Restaurar" : "Arquivar"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TemplateEditorDialog
|
||||
open={editorOpen}
|
||||
onOpenChange={setEditorOpen}
|
||||
template={editing}
|
||||
companies={companyOptions}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ function ChartContainer({
|
|||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer>
|
||||
<RechartsPrimitive.ResponsiveContainer initialDimension={{ width: 1, height: 1 }} minWidth={0}>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -81,6 +81,22 @@ const serverTicketSchema = z.object({
|
|||
queue: z.string().nullable(),
|
||||
formTemplate: z.string().nullable().optional(),
|
||||
formTemplateLabel: z.string().nullable().optional(),
|
||||
checklist: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
text: z.string(),
|
||||
done: z.boolean(),
|
||||
required: z.boolean().optional(),
|
||||
templateId: z.string().optional(),
|
||||
templateItemId: z.string().optional(),
|
||||
createdAt: z.number().optional(),
|
||||
createdBy: z.string().optional(),
|
||||
doneAt: z.number().optional(),
|
||||
doneBy: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
requester: serverUserSchema,
|
||||
assignee: serverUserSchema.nullable(),
|
||||
company: z
|
||||
|
|
@ -227,6 +243,10 @@ export function mapTicketFromServer(input: unknown) {
|
|||
...base
|
||||
} = serverTicketSchema.parse(input);
|
||||
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
||||
const checklist = (s.checklist ?? []).map((item) => ({
|
||||
...item,
|
||||
required: item.required ?? true,
|
||||
}));
|
||||
const slaSnapshot = s.slaSnapshot
|
||||
? {
|
||||
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
||||
|
|
@ -243,6 +263,7 @@ export function mapTicketFromServer(input: unknown) {
|
|||
const ui = {
|
||||
...base,
|
||||
status: normalizeTicketStatus(s.status),
|
||||
checklist,
|
||||
company: s.company
|
||||
? { id: s.company.id, name: s.company.name, isAvulso: s.company.isAvulso ?? false }
|
||||
: undefined,
|
||||
|
|
@ -325,6 +346,10 @@ export function mapTicketWithDetailsFromServer(input: unknown) {
|
|||
...base
|
||||
} = serverTicketWithDetailsSchema.parse(input);
|
||||
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
||||
const checklist = (s.checklist ?? []).map((item) => ({
|
||||
...item,
|
||||
required: item.required ?? true,
|
||||
}));
|
||||
const slaSnapshot = s.slaSnapshot
|
||||
? {
|
||||
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
||||
|
|
@ -360,6 +385,7 @@ export function mapTicketWithDetailsFromServer(input: unknown) {
|
|||
...base,
|
||||
customFields,
|
||||
status: normalizeTicketStatus(base.status),
|
||||
checklist,
|
||||
category: base.category ?? undefined,
|
||||
subcategory: base.subcategory ?? undefined,
|
||||
lastTimelineEntry: base.lastTimelineEntry ?? undefined,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { z } from "zod"
|
||||
|
||||
import { z } from "zod"
|
||||
|
||||
export const ticketStatusSchema = z.enum([
|
||||
"PENDING",
|
||||
"AWAITING_ATTENDANCE",
|
||||
|
|
@ -27,29 +27,29 @@ export const ticketSlaSnapshotSchema = z.object({
|
|||
})
|
||||
|
||||
export type TicketSlaSnapshot = z.infer<typeof ticketSlaSnapshotSchema>
|
||||
|
||||
export const ticketPrioritySchema = z.enum(["LOW", "MEDIUM", "HIGH", "URGENT"])
|
||||
export type TicketPriority = z.infer<typeof ticketPrioritySchema>
|
||||
|
||||
export const ticketChannelSchema = z.enum([
|
||||
"EMAIL",
|
||||
"WHATSAPP",
|
||||
"CHAT",
|
||||
"PHONE",
|
||||
"API",
|
||||
"MANUAL",
|
||||
])
|
||||
export type TicketChannel = z.infer<typeof ticketChannelSchema>
|
||||
|
||||
export const commentVisibilitySchema = z.enum(["PUBLIC", "INTERNAL"])
|
||||
export type CommentVisibility = z.infer<typeof commentVisibilitySchema>
|
||||
|
||||
|
||||
export const ticketPrioritySchema = z.enum(["LOW", "MEDIUM", "HIGH", "URGENT"])
|
||||
export type TicketPriority = z.infer<typeof ticketPrioritySchema>
|
||||
|
||||
export const ticketChannelSchema = z.enum([
|
||||
"EMAIL",
|
||||
"WHATSAPP",
|
||||
"CHAT",
|
||||
"PHONE",
|
||||
"API",
|
||||
"MANUAL",
|
||||
])
|
||||
export type TicketChannel = z.infer<typeof ticketChannelSchema>
|
||||
|
||||
export const commentVisibilitySchema = z.enum(["PUBLIC", "INTERNAL"])
|
||||
export type CommentVisibility = z.infer<typeof commentVisibilitySchema>
|
||||
|
||||
export const userSummarySchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
avatarUrl: z.string().url().optional(),
|
||||
teams: z.array(z.string()).default([]),
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
avatarUrl: z.string().url().optional(),
|
||||
teams: z.array(z.string()).default([]),
|
||||
})
|
||||
export type UserSummary = z.infer<typeof userSummarySchema>
|
||||
|
||||
|
|
@ -98,30 +98,30 @@ export const ticketCommentSchema = z.object({
|
|||
id: z.string(),
|
||||
author: userSummarySchema,
|
||||
visibility: commentVisibilitySchema,
|
||||
body: z.string(),
|
||||
attachments: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
size: z.number().optional(),
|
||||
body: z.string(),
|
||||
attachments: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
size: z.number().optional(),
|
||||
type: z.string().optional(),
|
||||
url: z.string().url().optional(),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date(),
|
||||
})
|
||||
export type TicketComment = z.infer<typeof ticketCommentSchema>
|
||||
|
||||
url: z.string().url().optional(),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
createdAt: z.coerce.date(),
|
||||
updatedAt: z.coerce.date(),
|
||||
})
|
||||
export type TicketComment = z.infer<typeof ticketCommentSchema>
|
||||
|
||||
export const ticketEventSchema = z.object({
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
payload: z.record(z.string(), z.any()).optional(),
|
||||
createdAt: z.coerce.date(),
|
||||
})
|
||||
export type TicketEvent = z.infer<typeof ticketEventSchema>
|
||||
export type TicketEvent = z.infer<typeof ticketEventSchema>
|
||||
|
||||
export const ticketFieldTypeSchema = z.enum(["text", "number", "select", "date", "boolean"])
|
||||
export type TicketFieldType = z.infer<typeof ticketFieldTypeSchema>
|
||||
|
|
@ -133,17 +133,31 @@ export const ticketCustomFieldValueSchema = z.object({
|
|||
displayValue: z.string().optional(),
|
||||
})
|
||||
export type TicketCustomFieldValue = z.infer<typeof ticketCustomFieldValueSchema>
|
||||
|
||||
|
||||
export const ticketChecklistItemSchema = z.object({
|
||||
id: z.string(),
|
||||
text: z.string(),
|
||||
done: z.boolean(),
|
||||
required: z.boolean().optional(),
|
||||
templateId: z.string().optional(),
|
||||
templateItemId: z.string().optional(),
|
||||
createdAt: z.number().optional(),
|
||||
createdBy: z.string().optional(),
|
||||
doneAt: z.number().optional(),
|
||||
doneBy: z.string().optional(),
|
||||
})
|
||||
export type TicketChecklistItem = z.infer<typeof ticketChecklistItemSchema>
|
||||
|
||||
export const ticketSchema = z.object({
|
||||
id: z.string(),
|
||||
reference: z.number(),
|
||||
tenantId: z.string(),
|
||||
subject: z.string(),
|
||||
summary: z.string().optional(),
|
||||
status: ticketStatusSchema,
|
||||
priority: ticketPrioritySchema,
|
||||
channel: ticketChannelSchema,
|
||||
queue: z.string().nullable(),
|
||||
subject: z.string(),
|
||||
summary: z.string().optional(),
|
||||
status: ticketStatusSchema,
|
||||
priority: ticketPrioritySchema,
|
||||
channel: ticketChannelSchema,
|
||||
queue: z.string().nullable(),
|
||||
requester: userSummarySchema,
|
||||
assignee: userSummarySchema.nullable(),
|
||||
company: ticketCompanySummarySchema.optional().nullable(),
|
||||
|
|
@ -196,6 +210,7 @@ export const ticketSchema = z.object({
|
|||
csatRatedBy: z.string().nullable().optional(),
|
||||
category: ticketCategorySummarySchema.nullable().optional(),
|
||||
subcategory: ticketSubcategorySummarySchema.nullable().optional(),
|
||||
checklist: z.array(ticketChecklistItemSchema).default([]),
|
||||
workSummary: z
|
||||
.object({
|
||||
totalWorkedMs: z.number(),
|
||||
|
|
@ -216,15 +231,15 @@ export const ticketSchema = z.object({
|
|||
.optional(),
|
||||
})
|
||||
export type Ticket = z.infer<typeof ticketSchema>
|
||||
|
||||
|
||||
export const ticketWithDetailsSchema = ticketSchema.extend({
|
||||
description: z.string().optional(),
|
||||
customFields: z.record(z.string(), ticketCustomFieldValueSchema).optional(),
|
||||
timeline: z.array(ticketEventSchema),
|
||||
comments: z.array(ticketCommentSchema),
|
||||
})
|
||||
export type TicketWithDetails = z.infer<typeof ticketWithDetailsSchema>
|
||||
|
||||
export type TicketWithDetails = z.infer<typeof ticketWithDetailsSchema>
|
||||
|
||||
export const ticketQueueSummarySchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
|
|
@ -233,10 +248,10 @@ export const ticketQueueSummarySchema = z.object({
|
|||
paused: z.number(),
|
||||
breached: z.number(),
|
||||
})
|
||||
export type TicketQueueSummary = z.infer<typeof ticketQueueSummarySchema>
|
||||
|
||||
export const ticketPlayContextSchema = z.object({
|
||||
queue: ticketQueueSummarySchema,
|
||||
nextTicket: ticketSchema.nullable(),
|
||||
})
|
||||
export type TicketPlayContext = z.infer<typeof ticketPlayContextSchema>
|
||||
export type TicketQueueSummary = z.infer<typeof ticketQueueSummarySchema>
|
||||
|
||||
export const ticketPlayContextSchema = z.object({
|
||||
queue: ticketQueueSummarySchema,
|
||||
nextTicket: ticketSchema.nullable(),
|
||||
})
|
||||
export type TicketPlayContext = z.infer<typeof ticketPlayContextSchema>
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
import net from "net"
|
||||
import tls from "tls"
|
||||
|
||||
type SmtpConfig = {
|
||||
host: string
|
||||
port: number
|
||||
domain?: string
|
||||
username: string
|
||||
password: string
|
||||
from: string
|
||||
starttls?: boolean
|
||||
tls?: boolean
|
||||
rejectUnauthorized?: boolean
|
||||
timeoutMs?: number
|
||||
|
|
@ -29,74 +32,253 @@ function extractEnvelopeAddress(from: string): string {
|
|||
return from
|
||||
}
|
||||
|
||||
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: 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", (e) => {
|
||||
clearTimeout(timeout)
|
||||
rej(e)
|
||||
})
|
||||
})
|
||||
type SmtpSocket = net.Socket | tls.TLSSocket
|
||||
|
||||
;(async () => {
|
||||
await wait(/^220 /)
|
||||
send(`EHLO ${cfg.host}`)
|
||||
await wait(/^250-/)
|
||||
await wait(/^250 /)
|
||||
send("AUTH LOGIN")
|
||||
await wait(/^334 /)
|
||||
send(b64(cfg.username))
|
||||
await wait(/^334 /)
|
||||
send(b64(cfg.password))
|
||||
await wait(/^235 /)
|
||||
const envelopeFrom = extractEnvelopeAddress(cfg.from)
|
||||
send(`MAIL FROM:<${envelopeFrom}>`)
|
||||
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: ${Array.isArray(to) ? to.join(", ") : to}`,
|
||||
`Subject: ${subject}`,
|
||||
"MIME-Version: 1.0",
|
||||
"Content-Type: text/html; charset=UTF-8",
|
||||
].join("\r\n")
|
||||
send(headers + "\r\n\r\n" + html + "\r\n.")
|
||||
await wait(/^250 /)
|
||||
send("QUIT")
|
||||
socket.end()
|
||||
resolve()
|
||||
})().catch(reject)
|
||||
type SmtpResponse = { code: number; lines: string[] }
|
||||
|
||||
function createSmtpReader(socket: SmtpSocket, timeoutMs: number) {
|
||||
let buffer = ""
|
||||
let current: SmtpResponse | null = null
|
||||
const queue: SmtpResponse[] = []
|
||||
let pending:
|
||||
| { resolve: (response: SmtpResponse) => void; reject: (error: unknown) => void; timer: ReturnType<typeof setTimeout> }
|
||||
| null = null
|
||||
|
||||
const finalize = (response: SmtpResponse) => {
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer)
|
||||
const resolve = pending.resolve
|
||||
pending = null
|
||||
resolve(response)
|
||||
return
|
||||
}
|
||||
queue.push(response)
|
||||
}
|
||||
|
||||
const onData = (data: Buffer) => {
|
||||
buffer += data.toString("utf8")
|
||||
const lines = buffer.split(/\r?\n/)
|
||||
buffer = lines.pop() ?? ""
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue
|
||||
const match = line.match(/^(\d{3})([ -])\s?(.*)$/)
|
||||
if (!match) continue
|
||||
|
||||
const code = Number(match[1])
|
||||
const isFinal = match[2] === " "
|
||||
|
||||
if (!current) current = { code, lines: [] }
|
||||
current.lines.push(line)
|
||||
|
||||
if (isFinal) {
|
||||
const response = current
|
||||
current = null
|
||||
finalize(response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const onError = (error: unknown) => {
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer)
|
||||
const reject = pending.reject
|
||||
pending = null
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
socket.on("data", onData)
|
||||
socket.on("error", onError)
|
||||
|
||||
const read = () =>
|
||||
new Promise<SmtpResponse>((resolve, reject) => {
|
||||
const queued = queue.shift()
|
||||
if (queued) {
|
||||
resolve(queued)
|
||||
return
|
||||
}
|
||||
if (pending) {
|
||||
reject(new Error("smtp_concurrent_read"))
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
if (!pending) return
|
||||
const rejectPending = pending.reject
|
||||
pending = null
|
||||
rejectPending(new Error("smtp_timeout"))
|
||||
}, timeoutMs)
|
||||
pending = { resolve, reject, timer }
|
||||
})
|
||||
|
||||
const dispose = () => {
|
||||
socket.off("data", onData)
|
||||
socket.off("error", onError)
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer)
|
||||
pending = null
|
||||
}
|
||||
}
|
||||
|
||||
return { read, dispose }
|
||||
}
|
||||
|
||||
function isCapability(lines: string[], capability: string) {
|
||||
const upper = capability.trim().toUpperCase()
|
||||
return lines.some((line) => line.replace(/^(\d{3})([ -])/, "").trim().toUpperCase().startsWith(upper))
|
||||
}
|
||||
|
||||
function assertCode(response: SmtpResponse, expected: number | ((code: number) => boolean), context: string) {
|
||||
const ok = typeof expected === "number" ? response.code === expected : expected(response.code)
|
||||
if (ok) return
|
||||
const details = response.lines.join(" | ")
|
||||
throw new Error(`smtp_unexpected_response:${context}:${response.code}:${details}`)
|
||||
}
|
||||
|
||||
async function connectPlain(host: string, port: number, timeoutMs: number) {
|
||||
return new Promise<net.Socket>((resolve, reject) => {
|
||||
const socket = net.connect(port, host)
|
||||
const timer = setTimeout(() => {
|
||||
socket.destroy()
|
||||
reject(new Error("smtp_connect_timeout"))
|
||||
}, timeoutMs)
|
||||
socket.once("connect", () => {
|
||||
clearTimeout(timer)
|
||||
resolve(socket)
|
||||
})
|
||||
socket.once("error", (e) => {
|
||||
clearTimeout(timer)
|
||||
reject(e)
|
||||
})
|
||||
socket.on("error", reject)
|
||||
})
|
||||
}
|
||||
|
||||
async function connectTls(host: string, port: number, rejectUnauthorized: boolean, timeoutMs: number) {
|
||||
return new Promise<tls.TLSSocket>((resolve, reject) => {
|
||||
const socket = tls.connect({ host, port, rejectUnauthorized, servername: host })
|
||||
const timer = setTimeout(() => {
|
||||
socket.destroy()
|
||||
reject(new Error("smtp_connect_timeout"))
|
||||
}, timeoutMs)
|
||||
socket.once("secureConnect", () => {
|
||||
clearTimeout(timer)
|
||||
resolve(socket)
|
||||
})
|
||||
socket.once("error", (e) => {
|
||||
clearTimeout(timer)
|
||||
reject(e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function upgradeToStartTls(socket: net.Socket, host: string, rejectUnauthorized: boolean, timeoutMs: number) {
|
||||
return new Promise<tls.TLSSocket>((resolve, reject) => {
|
||||
const tlsSocket = tls.connect({ socket, servername: host, rejectUnauthorized })
|
||||
const timer = setTimeout(() => {
|
||||
tlsSocket.destroy()
|
||||
reject(new Error("smtp_connect_timeout"))
|
||||
}, timeoutMs)
|
||||
tlsSocket.once("secureConnect", () => {
|
||||
clearTimeout(timer)
|
||||
resolve(tlsSocket)
|
||||
})
|
||||
tlsSocket.once("error", (e) => {
|
||||
clearTimeout(timer)
|
||||
reject(e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function sendSmtpMail(cfg: SmtpConfig, to: string | string[], subject: string, html: string) {
|
||||
const timeoutMs = Math.max(1000, cfg.timeoutMs ?? 10000)
|
||||
const rejectUnauthorized = cfg.rejectUnauthorized ?? false
|
||||
const implicitTls = cfg.tls ?? cfg.port === 465
|
||||
const wantsStarttls = cfg.starttls ?? !implicitTls
|
||||
|
||||
const rcpts: string[] = Array.isArray(to)
|
||||
? to
|
||||
: String(to)
|
||||
.split(/[;,]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
let socket: SmtpSocket | null = null
|
||||
let reader: ReturnType<typeof createSmtpReader> | null = null
|
||||
|
||||
const sendLine = (line: string) => socket?.write(line + "\r\n")
|
||||
|
||||
const readExpected = async (expected: number | ((code: number) => boolean), context: string) => {
|
||||
if (!reader) throw new Error("smtp_reader_not_ready")
|
||||
const response = await reader.read()
|
||||
assertCode(response, expected, context)
|
||||
return response
|
||||
}
|
||||
|
||||
try {
|
||||
socket = implicitTls
|
||||
? await connectTls(cfg.host, cfg.port, rejectUnauthorized, timeoutMs)
|
||||
: await connectPlain(cfg.host, cfg.port, timeoutMs)
|
||||
|
||||
reader = createSmtpReader(socket, timeoutMs)
|
||||
|
||||
await readExpected(220, "greeting")
|
||||
|
||||
const domain = cfg.domain ?? cfg.host
|
||||
sendLine(`EHLO ${domain}`)
|
||||
let ehlo = await readExpected(250, "ehlo")
|
||||
|
||||
if (!implicitTls && wantsStarttls) {
|
||||
const supportsStarttls = isCapability(ehlo.lines, "STARTTLS")
|
||||
if (!supportsStarttls) {
|
||||
throw new Error("smtp_starttls_not_supported")
|
||||
}
|
||||
|
||||
sendLine("STARTTLS")
|
||||
await readExpected(220, "starttls")
|
||||
|
||||
reader.dispose()
|
||||
const upgraded = await upgradeToStartTls(socket as net.Socket, cfg.host, rejectUnauthorized, timeoutMs)
|
||||
socket = upgraded
|
||||
reader = createSmtpReader(socket, timeoutMs)
|
||||
|
||||
sendLine(`EHLO ${domain}`)
|
||||
ehlo = await readExpected(250, "ehlo_starttls")
|
||||
}
|
||||
|
||||
sendLine("AUTH LOGIN")
|
||||
await readExpected(334, "auth_login")
|
||||
sendLine(b64(cfg.username))
|
||||
await readExpected(334, "auth_username")
|
||||
sendLine(b64(cfg.password))
|
||||
await readExpected(235, "auth_password")
|
||||
|
||||
const envelopeFrom = extractEnvelopeAddress(cfg.from)
|
||||
sendLine(`MAIL FROM:<${envelopeFrom}>`)
|
||||
await readExpected((code) => Math.floor(code / 100) === 2, "mail_from")
|
||||
|
||||
for (const rcpt of rcpts) {
|
||||
sendLine(`RCPT TO:<${rcpt}>`)
|
||||
await readExpected((code) => Math.floor(code / 100) === 2, "rcpt_to")
|
||||
}
|
||||
|
||||
sendLine("DATA")
|
||||
await readExpected(354, "data")
|
||||
|
||||
const headers = [
|
||||
`From: ${cfg.from}`,
|
||||
`To: ${Array.isArray(to) ? to.join(", ") : to}`,
|
||||
`Subject: ${subject}`,
|
||||
"MIME-Version: 1.0",
|
||||
"Content-Type: text/html; charset=UTF-8",
|
||||
].join("\r\n")
|
||||
|
||||
sendLine(headers + "\r\n\r\n" + html + "\r\n.")
|
||||
await readExpected((code) => Math.floor(code / 100) === 2, "message")
|
||||
|
||||
sendLine("QUIT")
|
||||
await readExpected(221, "quit")
|
||||
} finally {
|
||||
reader?.dispose()
|
||||
socket?.end()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue