"use client" import { useMemo, useState } from "react" import { useMutation, useQuery } from "convex/react" import { toast } from "sonner" import { IconFileText, IconPlus, IconTrash, IconX } from "@tabler/icons-react" 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 { sanitizeEditorHtml, RichTextEditor, RichTextContent } from "@/components/ui/rich-text-editor" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty" import { Spinner } from "@/components/ui/spinner" import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs" export function CommentTemplatesManager() { const { convexUserId, session } = useAuth() const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID const viewerId = convexUserId as Id<"users"> | undefined const [activeKind, setActiveKind] = useState<"comment" | "closing">("comment") const templates = useQuery( viewerId ? api.commentTemplates.list : "skip", viewerId ? { tenantId, viewerId, kind: activeKind } : "skip" ) as | { id: Id<"commentTemplates"> title: string body: string createdAt: number updatedAt: number createdBy: Id<"users"> updatedBy: Id<"users"> | null kind: "comment" | "closing" | string }[] | undefined const createTemplate = useMutation(api.commentTemplates.create) const updateTemplate = useMutation(api.commentTemplates.update) const deleteTemplate = useMutation(api.commentTemplates.remove) const [title, setTitle] = useState("") const [body, setBody] = useState("") const [isSubmitting, setIsSubmitting] = useState(false) const isLoading = viewerId && templates === undefined const orderedTemplates = useMemo(() => templates ?? [], [templates]) const kindLabels: Record = { comment: { title: "Templates de comentário", description: "Mantenha respostas rápidas prontas para uso. Administradores e agentes podem criar, editar e remover templates.", placeholder: "Escreva a mensagem padrão...", empty: { title: "Nenhum template cadastrado", description: "Crie seu primeiro template de comentário usando o formulário acima.", }, }, closing: { title: "Templates de encerramento", description: "Padronize as mensagens de fechamento de tickets. Os nomes dos clientes podem ser inseridos automaticamente com {{cliente}}.", placeholder: "Conteúdo da mensagem de encerramento...", empty: { title: "Nenhum template de encerramento", description: "Cadastre mensagens padrão para encerrar tickets rapidamente.", }, }, } async function handleCreate(event: React.FormEvent) { event.preventDefault() if (!viewerId) return const trimmedTitle = title.trim() const sanitizedBody = sanitizeEditorHtml(body) if (trimmedTitle.length < 3) { toast.error("Informe um título com pelo menos 3 caracteres.") return } if (!sanitizedBody) { toast.error("Escreva o conteúdo do template antes de salvar.") return } setIsSubmitting(true) toast.loading("Criando template...", { id: "create-template" }) try { await createTemplate({ tenantId, actorId: viewerId, title: trimmedTitle, body: sanitizedBody, kind: activeKind }) toast.success("Template criado!", { id: "create-template" }) setTitle("") setBody("") } catch (error) { console.error(error) toast.error("Não foi possível criar o template.", { id: "create-template" }) } finally { setIsSubmitting(false) } } async function handleUpdate(templateId: Id<"commentTemplates">, nextTitle: string, nextBody: string, kind: "comment" | "closing" | string) { if (!viewerId) return const trimmedTitle = nextTitle.trim() const sanitizedBody = sanitizeEditorHtml(nextBody) if (trimmedTitle.length < 3) { toast.error("Informe um título com pelo menos 3 caracteres.") return false } if (!sanitizedBody) { toast.error("Escreva o conteúdo do template antes de salvar.") return false } const toastId = `update-template-${templateId}` toast.loading("Atualizando template...", { id: toastId }) try { await updateTemplate({ templateId, tenantId, actorId: viewerId, title: trimmedTitle, body: sanitizedBody, kind, }) toast.success("Template atualizado!", { id: toastId }) return true } catch (error) { console.error(error) toast.error("Não foi possível atualizar o template.", { id: toastId }) return false } } async function handleDelete(templateId: Id<"commentTemplates">) { if (!viewerId) return const toastId = `delete-template-${templateId}` toast.loading("Removendo template...", { id: toastId }) try { await deleteTemplate({ templateId, tenantId, actorId: viewerId }) toast.success("Template removido!", { id: toastId }) } catch (error) { console.error(error) toast.error("Não foi possível remover o template.", { id: toastId }) } } if (!viewerId) { return ( Templates de comentário Faça login para gerenciar os templates de resposta rápida. ) } return (
Templates rápidos Gerencie mensagens padrão para comentários e encerramentos de tickets.
setActiveKind(value as "comment" | "closing")} className="w-full"> Comentários Encerramentos
{kindLabels[activeKind].description}
setTitle(event.target.value)} required />
{body ? ( ) : null}
Templates cadastrados Gerencie as mensagens prontas utilizadas nos {activeKind === "comment" ? "comentários" : "encerramentos"} de tickets. {isLoading ? (
Carregando templates...
) : orderedTemplates.length === 0 ? ( {kindLabels[activeKind].empty.title} {kindLabels[activeKind].empty.description} ) : (
{orderedTemplates.map((template) => ( ))}
)}
) } type TemplateItemProps = { template: { id: Id<"commentTemplates"> title: string body: string updatedAt: number kind: "comment" | "closing" | string } onSave: (templateId: Id<"commentTemplates">, title: string, body: string, kind: "comment" | "closing" | string) => Promise onDelete: (templateId: Id<"commentTemplates">) => Promise } function TemplateItem({ template, onSave, onDelete }: TemplateItemProps) { const [isEditing, setIsEditing] = useState(false) const [title, setTitle] = useState(template.title) const [body, setBody] = useState(template.body) const [isSaving, setIsSaving] = useState(false) const [isDeleting, setIsDeleting] = useState(false) const lastUpdated = useMemo(() => new Date(template.updatedAt), [template.updatedAt]) async function handleSave() { setIsSaving(true) const ok = await onSave(template.id, title, body, template.kind ?? "comment") setIsSaving(false) if (ok !== false) { setIsEditing(false) } } async function handleDelete() { setIsDeleting(true) await onDelete(template.id) setIsDeleting(false) } return (
{isEditing ? (
setTitle(event.target.value)} placeholder="Título" />
) : (

{template.title}

)}
Atualizado em {lastUpdated.toLocaleString("pt-BR")}
{isEditing ? ( <> ) : ( <> )}
) }