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
2
convex/_generated/api.d.ts
vendored
2
convex/_generated/api.d.ts
vendored
|
|
@ -13,6 +13,7 @@ import type * as automations from "../automations.js";
|
||||||
import type * as bootstrap from "../bootstrap.js";
|
import type * as bootstrap from "../bootstrap.js";
|
||||||
import type * as categories from "../categories.js";
|
import type * as categories from "../categories.js";
|
||||||
import type * as categorySlas from "../categorySlas.js";
|
import type * as categorySlas from "../categorySlas.js";
|
||||||
|
import type * as checklistTemplates from "../checklistTemplates.js";
|
||||||
import type * as commentTemplates from "../commentTemplates.js";
|
import type * as commentTemplates from "../commentTemplates.js";
|
||||||
import type * as companies from "../companies.js";
|
import type * as companies from "../companies.js";
|
||||||
import type * as crons from "../crons.js";
|
import type * as crons from "../crons.js";
|
||||||
|
|
@ -57,6 +58,7 @@ declare const fullApi: ApiFromModules<{
|
||||||
bootstrap: typeof bootstrap;
|
bootstrap: typeof bootstrap;
|
||||||
categories: typeof categories;
|
categories: typeof categories;
|
||||||
categorySlas: typeof categorySlas;
|
categorySlas: typeof categorySlas;
|
||||||
|
checklistTemplates: typeof checklistTemplates;
|
||||||
commentTemplates: typeof commentTemplates;
|
commentTemplates: typeof commentTemplates;
|
||||||
companies: typeof companies;
|
companies: typeof companies;
|
||||||
crons: typeof crons;
|
crons: typeof crons;
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { getTemplateByKey, normalizeFormTemplateKey } from "./ticketFormTemplate
|
||||||
import { TICKET_FORM_CONFIG } from "./ticketForms.config"
|
import { TICKET_FORM_CONFIG } from "./ticketForms.config"
|
||||||
import { renderAutomationEmailHtml, type AutomationEmailProps } from "./reactEmail"
|
import { renderAutomationEmailHtml, type AutomationEmailProps } from "./reactEmail"
|
||||||
import { buildBaseUrl } from "./url"
|
import { buildBaseUrl } from "./url"
|
||||||
|
import { applyChecklistTemplateToItems, type TicketChecklistItem } from "./ticketChecklist"
|
||||||
|
|
||||||
type AutomationEmailTarget = "AUTO" | "PORTAL" | "STAFF"
|
type AutomationEmailTarget = "AUTO" | "PORTAL" | "STAFF"
|
||||||
|
|
||||||
|
|
@ -32,6 +33,7 @@ type AutomationAction =
|
||||||
| { type: "SET_FORM_TEMPLATE"; formTemplate: string | null }
|
| { type: "SET_FORM_TEMPLATE"; formTemplate: string | null }
|
||||||
| { type: "SET_CHAT_ENABLED"; enabled: boolean }
|
| { type: "SET_CHAT_ENABLED"; enabled: boolean }
|
||||||
| { type: "ADD_INTERNAL_COMMENT"; body: string }
|
| { type: "ADD_INTERNAL_COMMENT"; body: string }
|
||||||
|
| { type: "APPLY_CHECKLIST_TEMPLATE"; templateId: Id<"ticketChecklistTemplates"> }
|
||||||
| {
|
| {
|
||||||
type: "SEND_EMAIL"
|
type: "SEND_EMAIL"
|
||||||
recipients: AutomationEmailRecipient[]
|
recipients: AutomationEmailRecipient[]
|
||||||
|
|
@ -141,6 +143,12 @@ function parseAction(value: unknown): AutomationAction | null {
|
||||||
return { type: "ADD_INTERNAL_COMMENT", body }
|
return { type: "ADD_INTERNAL_COMMENT", body }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (type === "APPLY_CHECKLIST_TEMPLATE") {
|
||||||
|
const templateId = typeof record.templateId === "string" ? record.templateId : ""
|
||||||
|
if (!templateId) return null
|
||||||
|
return { type: "APPLY_CHECKLIST_TEMPLATE", templateId: templateId as Id<"ticketChecklistTemplates"> }
|
||||||
|
}
|
||||||
|
|
||||||
if (type === "SEND_EMAIL") {
|
if (type === "SEND_EMAIL") {
|
||||||
const subject = typeof record.subject === "string" ? record.subject.trim() : ""
|
const subject = typeof record.subject === "string" ? record.subject.trim() : ""
|
||||||
const message = typeof record.message === "string" ? record.message : ""
|
const message = typeof record.message === "string" ? record.message : ""
|
||||||
|
|
@ -672,6 +680,10 @@ async function applyActions(
|
||||||
ctaLabel: string
|
ctaLabel: string
|
||||||
}> = []
|
}> = []
|
||||||
|
|
||||||
|
let checklist = (Array.isArray((ticket as unknown as { checklist?: unknown }).checklist)
|
||||||
|
? ((ticket as unknown as { checklist?: unknown }).checklist as TicketChecklistItem[])
|
||||||
|
: []) as TicketChecklistItem[]
|
||||||
|
|
||||||
for (const action of actions) {
|
for (const action of actions) {
|
||||||
if (action.type === "SET_PRIORITY") {
|
if (action.type === "SET_PRIORITY") {
|
||||||
const next = action.priority.trim().toUpperCase()
|
const next = action.priority.trim().toUpperCase()
|
||||||
|
|
@ -814,6 +826,32 @@ async function applyActions(
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action.type === "APPLY_CHECKLIST_TEMPLATE") {
|
||||||
|
const template = (await ctx.db.get(action.templateId)) as Doc<"ticketChecklistTemplates"> | null
|
||||||
|
if (!template || template.tenantId !== ticket.tenantId || template.isArchived === true) {
|
||||||
|
throw new ConvexError("Template de checklist inválido na automação")
|
||||||
|
}
|
||||||
|
if (template.companyId && (!ticket.companyId || String(template.companyId) !== String(ticket.companyId))) {
|
||||||
|
throw new ConvexError("Template de checklist não pertence à empresa do ticket")
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = applyChecklistTemplateToItems(checklist, template, {
|
||||||
|
now,
|
||||||
|
actorId: automation.createdBy ?? undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (result.added > 0) {
|
||||||
|
checklist = result.checklist
|
||||||
|
patch.checklist = checklist.length > 0 ? checklist : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
applied.push({
|
||||||
|
type: action.type,
|
||||||
|
details: { templateId: String(template._id), templateName: template.name, added: result.added },
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if (action.type === "SEND_EMAIL") {
|
if (action.type === "SEND_EMAIL") {
|
||||||
const subject = action.subject.trim()
|
const subject = action.subject.trim()
|
||||||
const message = action.message.replace(/\r\n/g, "\n").trim()
|
const message = action.message.replace(/\r\n/g, "\n").trim()
|
||||||
|
|
|
||||||
259
convex/checklistTemplates.ts
Normal file
259
convex/checklistTemplates.ts
Normal file
|
|
@ -0,0 +1,259 @@
|
||||||
|
import { ConvexError, v } from "convex/values"
|
||||||
|
|
||||||
|
import type { Doc, Id } from "./_generated/dataModel"
|
||||||
|
import { mutation, query } from "./_generated/server"
|
||||||
|
import { requireAdmin, requireStaff } from "./rbac"
|
||||||
|
import { normalizeChecklistText } from "./ticketChecklist"
|
||||||
|
|
||||||
|
function normalizeTemplateName(input: string) {
|
||||||
|
return input.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTemplateDescription(input: string | null | undefined) {
|
||||||
|
const text = (input ?? "").trim()
|
||||||
|
return text.length > 0 ? text : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTemplateItems(
|
||||||
|
raw: Array<{ id?: string; text: string; required?: boolean }>,
|
||||||
|
options: { generateId?: () => string }
|
||||||
|
) {
|
||||||
|
if (!Array.isArray(raw) || raw.length === 0) {
|
||||||
|
throw new ConvexError("Adicione pelo menos um item no checklist.")
|
||||||
|
}
|
||||||
|
|
||||||
|
const generateId = options.generateId ?? (() => crypto.randomUUID())
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const items: Array<{ id: string; text: string; required?: boolean }> = []
|
||||||
|
|
||||||
|
for (const entry of raw) {
|
||||||
|
const id = String(entry.id ?? "").trim() || generateId()
|
||||||
|
if (seen.has(id)) {
|
||||||
|
throw new ConvexError("Itens do checklist com IDs duplicados.")
|
||||||
|
}
|
||||||
|
seen.add(id)
|
||||||
|
|
||||||
|
const text = normalizeChecklistText(entry.text)
|
||||||
|
if (!text) {
|
||||||
|
throw new ConvexError("Todos os itens do checklist precisam ter um texto.")
|
||||||
|
}
|
||||||
|
if (text.length > 240) {
|
||||||
|
throw new ConvexError("Item do checklist muito longo (máx. 240 caracteres).")
|
||||||
|
}
|
||||||
|
|
||||||
|
const required = typeof entry.required === "boolean" ? entry.required : true
|
||||||
|
items.push({ id, text, required })
|
||||||
|
}
|
||||||
|
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapTemplate(template: Doc<"ticketChecklistTemplates">, company: Doc<"companies"> | null) {
|
||||||
|
return {
|
||||||
|
id: template._id,
|
||||||
|
name: template.name,
|
||||||
|
description: template.description ?? "",
|
||||||
|
company: company ? { id: company._id, name: company.name } : null,
|
||||||
|
items: (template.items ?? []).map((item) => ({
|
||||||
|
id: item.id,
|
||||||
|
text: item.text,
|
||||||
|
required: typeof item.required === "boolean" ? item.required : true,
|
||||||
|
})),
|
||||||
|
isArchived: Boolean(template.isArchived),
|
||||||
|
createdAt: template.createdAt,
|
||||||
|
updatedAt: template.updatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const listActive = query({
|
||||||
|
args: {
|
||||||
|
tenantId: v.string(),
|
||||||
|
viewerId: v.id("users"),
|
||||||
|
companyId: v.optional(v.id("companies")),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { tenantId, viewerId, companyId }) => {
|
||||||
|
await requireStaff(ctx, viewerId, tenantId)
|
||||||
|
|
||||||
|
const templates = await ctx.db
|
||||||
|
.query("ticketChecklistTemplates")
|
||||||
|
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
|
||||||
|
.take(200)
|
||||||
|
|
||||||
|
const filtered = templates.filter((tpl) => {
|
||||||
|
if (tpl.isArchived === true) return false
|
||||||
|
if (!companyId) return true
|
||||||
|
return !tpl.companyId || String(tpl.companyId) === String(companyId)
|
||||||
|
})
|
||||||
|
|
||||||
|
const companiesToHydrate = new Map<string, Id<"companies">>()
|
||||||
|
for (const tpl of filtered) {
|
||||||
|
if (tpl.companyId) {
|
||||||
|
companiesToHydrate.set(String(tpl.companyId), tpl.companyId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const companyMap = new Map<string, Doc<"companies">>()
|
||||||
|
for (const id of companiesToHydrate.values()) {
|
||||||
|
const company = await ctx.db.get(id)
|
||||||
|
if (company && company.tenantId === tenantId) {
|
||||||
|
companyMap.set(String(id), company as Doc<"companies">)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered
|
||||||
|
.sort((a, b) => {
|
||||||
|
const aSpecific = a.companyId ? 1 : 0
|
||||||
|
const bSpecific = b.companyId ? 1 : 0
|
||||||
|
if (aSpecific !== bSpecific) return bSpecific - aSpecific
|
||||||
|
return (a.name ?? "").localeCompare(b.name ?? "", "pt-BR")
|
||||||
|
})
|
||||||
|
.map((tpl) => mapTemplate(tpl, tpl.companyId ? (companyMap.get(String(tpl.companyId)) ?? null) : null))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const list = query({
|
||||||
|
args: {
|
||||||
|
tenantId: v.string(),
|
||||||
|
viewerId: v.id("users"),
|
||||||
|
includeArchived: v.optional(v.boolean()),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { tenantId, viewerId, includeArchived }) => {
|
||||||
|
await requireAdmin(ctx, viewerId, tenantId)
|
||||||
|
|
||||||
|
const templates = await ctx.db
|
||||||
|
.query("ticketChecklistTemplates")
|
||||||
|
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
|
||||||
|
.take(500)
|
||||||
|
|
||||||
|
const filtered = templates.filter((tpl) => includeArchived || tpl.isArchived !== true)
|
||||||
|
|
||||||
|
const companiesToHydrate = new Map<string, Id<"companies">>()
|
||||||
|
for (const tpl of filtered) {
|
||||||
|
if (tpl.companyId) {
|
||||||
|
companiesToHydrate.set(String(tpl.companyId), tpl.companyId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const companyMap = new Map<string, Doc<"companies">>()
|
||||||
|
for (const id of companiesToHydrate.values()) {
|
||||||
|
const company = await ctx.db.get(id)
|
||||||
|
if (company && company.tenantId === tenantId) {
|
||||||
|
companyMap.set(String(id), company as Doc<"companies">)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered
|
||||||
|
.sort((a, b) => {
|
||||||
|
const aSpecific = a.companyId ? 1 : 0
|
||||||
|
const bSpecific = b.companyId ? 1 : 0
|
||||||
|
if (aSpecific !== bSpecific) return bSpecific - aSpecific
|
||||||
|
return (a.name ?? "").localeCompare(b.name ?? "", "pt-BR")
|
||||||
|
})
|
||||||
|
.map((tpl) => mapTemplate(tpl, tpl.companyId ? (companyMap.get(String(tpl.companyId)) ?? null) : null))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const create = mutation({
|
||||||
|
args: {
|
||||||
|
tenantId: v.string(),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
name: v.string(),
|
||||||
|
description: v.optional(v.string()),
|
||||||
|
companyId: v.optional(v.id("companies")),
|
||||||
|
items: v.array(
|
||||||
|
v.object({
|
||||||
|
id: v.optional(v.string()),
|
||||||
|
text: v.string(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { tenantId, actorId, name, description, companyId, items }) => {
|
||||||
|
await requireAdmin(ctx, actorId, tenantId)
|
||||||
|
|
||||||
|
const normalizedName = normalizeTemplateName(name)
|
||||||
|
if (normalizedName.length < 3) {
|
||||||
|
throw new ConvexError("Informe um nome com pelo menos 3 caracteres.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (companyId) {
|
||||||
|
const company = await ctx.db.get(companyId)
|
||||||
|
if (!company || company.tenantId !== tenantId) {
|
||||||
|
throw new ConvexError("Empresa inválida para o template.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedItems = normalizeTemplateItems(items, {})
|
||||||
|
const normalizedDescription = normalizeTemplateDescription(description)
|
||||||
|
const now = Date.now()
|
||||||
|
|
||||||
|
return ctx.db.insert("ticketChecklistTemplates", {
|
||||||
|
tenantId,
|
||||||
|
name: normalizedName,
|
||||||
|
description: normalizedDescription ?? undefined,
|
||||||
|
companyId: companyId ?? undefined,
|
||||||
|
items: normalizedItems,
|
||||||
|
isArchived: false,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
createdBy: actorId,
|
||||||
|
updatedBy: actorId,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const update = mutation({
|
||||||
|
args: {
|
||||||
|
tenantId: v.string(),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
templateId: v.id("ticketChecklistTemplates"),
|
||||||
|
name: v.string(),
|
||||||
|
description: v.optional(v.string()),
|
||||||
|
companyId: v.optional(v.id("companies")),
|
||||||
|
items: v.array(
|
||||||
|
v.object({
|
||||||
|
id: v.optional(v.string()),
|
||||||
|
text: v.string(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
isArchived: v.optional(v.boolean()),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { tenantId, actorId, templateId, name, description, companyId, items, isArchived }) => {
|
||||||
|
await requireAdmin(ctx, actorId, tenantId)
|
||||||
|
|
||||||
|
const existing = await ctx.db.get(templateId)
|
||||||
|
if (!existing || existing.tenantId !== tenantId) {
|
||||||
|
throw new ConvexError("Template de checklist não encontrado.")
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedName = normalizeTemplateName(name)
|
||||||
|
if (normalizedName.length < 3) {
|
||||||
|
throw new ConvexError("Informe um nome com pelo menos 3 caracteres.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (companyId) {
|
||||||
|
const company = await ctx.db.get(companyId)
|
||||||
|
if (!company || company.tenantId !== tenantId) {
|
||||||
|
throw new ConvexError("Empresa inválida para o template.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedItems = normalizeTemplateItems(items, {})
|
||||||
|
const normalizedDescription = normalizeTemplateDescription(description)
|
||||||
|
const nextArchived = typeof isArchived === "boolean" ? isArchived : Boolean(existing.isArchived)
|
||||||
|
const now = Date.now()
|
||||||
|
|
||||||
|
await ctx.db.patch(templateId, {
|
||||||
|
name: normalizedName,
|
||||||
|
description: normalizedDescription ?? undefined,
|
||||||
|
companyId: companyId ?? undefined,
|
||||||
|
items: normalizedItems,
|
||||||
|
isArchived: nextArchived,
|
||||||
|
updatedAt: now,
|
||||||
|
updatedBy: actorId,
|
||||||
|
})
|
||||||
|
|
||||||
|
return { ok: true }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
@ -309,6 +309,22 @@ export default defineSchema({
|
||||||
),
|
),
|
||||||
formTemplate: v.optional(v.string()),
|
formTemplate: v.optional(v.string()),
|
||||||
formTemplateLabel: v.optional(v.string()),
|
formTemplateLabel: v.optional(v.string()),
|
||||||
|
checklist: v.optional(
|
||||||
|
v.array(
|
||||||
|
v.object({
|
||||||
|
id: v.string(),
|
||||||
|
text: v.string(),
|
||||||
|
done: v.boolean(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
templateId: v.optional(v.id("ticketChecklistTemplates")),
|
||||||
|
templateItemId: v.optional(v.string()),
|
||||||
|
createdAt: v.optional(v.number()),
|
||||||
|
createdBy: v.optional(v.id("users")),
|
||||||
|
doneAt: v.optional(v.number()),
|
||||||
|
doneBy: v.optional(v.id("users")),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
),
|
||||||
relatedTicketIds: v.optional(v.array(v.id("tickets"))),
|
relatedTicketIds: v.optional(v.array(v.id("tickets"))),
|
||||||
resolvedWithTicketId: v.optional(v.id("tickets")),
|
resolvedWithTicketId: v.optional(v.id("tickets")),
|
||||||
reopenDeadline: v.optional(v.number()),
|
reopenDeadline: v.optional(v.number()),
|
||||||
|
|
@ -633,6 +649,28 @@ export default defineSchema({
|
||||||
.index("by_tenant_key", ["tenantId", "key"])
|
.index("by_tenant_key", ["tenantId", "key"])
|
||||||
.index("by_tenant_active", ["tenantId", "isArchived"]),
|
.index("by_tenant_active", ["tenantId", "isArchived"]),
|
||||||
|
|
||||||
|
ticketChecklistTemplates: defineTable({
|
||||||
|
tenantId: v.string(),
|
||||||
|
name: v.string(),
|
||||||
|
description: v.optional(v.string()),
|
||||||
|
companyId: v.optional(v.id("companies")),
|
||||||
|
items: v.array(
|
||||||
|
v.object({
|
||||||
|
id: v.string(),
|
||||||
|
text: v.string(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
})
|
||||||
|
),
|
||||||
|
isArchived: v.optional(v.boolean()),
|
||||||
|
createdAt: v.number(),
|
||||||
|
updatedAt: v.number(),
|
||||||
|
createdBy: v.optional(v.id("users")),
|
||||||
|
updatedBy: v.optional(v.id("users")),
|
||||||
|
})
|
||||||
|
.index("by_tenant", ["tenantId"])
|
||||||
|
.index("by_tenant_company", ["tenantId", "companyId"])
|
||||||
|
.index("by_tenant_active", ["tenantId", "isArchived"]),
|
||||||
|
|
||||||
userInvites: defineTable({
|
userInvites: defineTable({
|
||||||
tenantId: v.string(),
|
tenantId: v.string(),
|
||||||
inviteId: v.string(),
|
inviteId: v.string(),
|
||||||
|
|
|
||||||
71
convex/ticketChecklist.ts
Normal file
71
convex/ticketChecklist.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import type { Id } from "./_generated/dataModel"
|
||||||
|
|
||||||
|
export type TicketChecklistItem = {
|
||||||
|
id: string
|
||||||
|
text: string
|
||||||
|
done: boolean
|
||||||
|
required?: boolean
|
||||||
|
templateId?: Id<"ticketChecklistTemplates">
|
||||||
|
templateItemId?: string
|
||||||
|
createdAt?: number
|
||||||
|
createdBy?: Id<"users">
|
||||||
|
doneAt?: number
|
||||||
|
doneBy?: Id<"users">
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TicketChecklistTemplateLike = {
|
||||||
|
_id: Id<"ticketChecklistTemplates">
|
||||||
|
items: Array<{ id: string; text: string; required?: boolean }>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeChecklistText(input: string) {
|
||||||
|
return input.replace(/\r\n/g, "\n").trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checklistBlocksResolution(checklist: TicketChecklistItem[] | null | undefined) {
|
||||||
|
return (checklist ?? []).some((item) => (item.required ?? true) && item.done !== true)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyChecklistTemplateToItems(
|
||||||
|
existing: TicketChecklistItem[],
|
||||||
|
template: TicketChecklistTemplateLike,
|
||||||
|
options: {
|
||||||
|
now: number
|
||||||
|
actorId?: Id<"users">
|
||||||
|
generateId?: () => string
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
const generateId = options.generateId ?? (() => crypto.randomUUID())
|
||||||
|
const now = options.now
|
||||||
|
|
||||||
|
const next = Array.isArray(existing) ? [...existing] : []
|
||||||
|
const existingKeys = new Set<string>()
|
||||||
|
for (const item of next) {
|
||||||
|
if (!item.templateId || !item.templateItemId) continue
|
||||||
|
existingKeys.add(`${String(item.templateId)}:${item.templateItemId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let added = 0
|
||||||
|
for (const tplItem of template.items ?? []) {
|
||||||
|
const templateItemId = String(tplItem.id ?? "").trim()
|
||||||
|
const text = normalizeChecklistText(String(tplItem.text ?? ""))
|
||||||
|
if (!templateItemId || !text) continue
|
||||||
|
const key = `${String(template._id)}:${templateItemId}`
|
||||||
|
if (existingKeys.has(key)) continue
|
||||||
|
existingKeys.add(key)
|
||||||
|
next.push({
|
||||||
|
id: generateId(),
|
||||||
|
text,
|
||||||
|
done: false,
|
||||||
|
required: typeof tplItem.required === "boolean" ? tplItem.required : true,
|
||||||
|
templateId: template._id,
|
||||||
|
templateItemId,
|
||||||
|
createdAt: now,
|
||||||
|
createdBy: options.actorId,
|
||||||
|
})
|
||||||
|
added += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return { checklist: next, added }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
"use node"
|
"use node"
|
||||||
|
|
||||||
|
import net from "net"
|
||||||
import tls from "tls"
|
import tls from "tls"
|
||||||
import { action } from "./_generated/server"
|
import { action } from "./_generated/server"
|
||||||
import { v } from "convex/values"
|
import { v } from "convex/values"
|
||||||
|
|
@ -11,7 +12,28 @@ function b64(input: string) {
|
||||||
return Buffer.from(input, "utf8").toString("base64")
|
return Buffer.from(input, "utf8").toString("base64")
|
||||||
}
|
}
|
||||||
|
|
||||||
type SmtpConfig = { host: string; port: number; username: string; password: string; from: string }
|
function extractEnvelopeAddress(from: string): string {
|
||||||
|
const angle = from.match(/<\s*([^>\s]+)\s*>/)
|
||||||
|
if (angle?.[1]) return angle[1]
|
||||||
|
|
||||||
|
const paren = from.match(/\(([^)\s]+@[^)\s]+)\)/)
|
||||||
|
if (paren?.[1]) return paren[1]
|
||||||
|
|
||||||
|
const email = from.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/)
|
||||||
|
if (email?.[0]) return email[0]
|
||||||
|
|
||||||
|
return from
|
||||||
|
}
|
||||||
|
|
||||||
|
type SmtpConfig = {
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
from: string
|
||||||
|
secure: boolean
|
||||||
|
timeoutMs: number
|
||||||
|
}
|
||||||
|
|
||||||
function buildSmtpConfig(): SmtpConfig | null {
|
function buildSmtpConfig(): SmtpConfig | null {
|
||||||
const host = process.env.SMTP_ADDRESS || process.env.SMTP_HOST
|
const host = process.env.SMTP_ADDRESS || process.env.SMTP_HOST
|
||||||
|
|
@ -26,62 +48,237 @@ function buildSmtpConfig(): SmtpConfig | null {
|
||||||
|
|
||||||
if (!host || !username || !password) return null
|
if (!host || !username || !password) return null
|
||||||
|
|
||||||
return { host, port, username, password, from }
|
const secureFlag = (process.env.SMTP_SECURE ?? process.env.SMTP_TLS ?? "").toLowerCase()
|
||||||
|
const secure = secureFlag ? secureFlag === "true" : port === 465
|
||||||
|
|
||||||
|
return { host, port, username, password, from, secure, timeoutMs: 30000 }
|
||||||
|
}
|
||||||
|
|
||||||
|
type SmtpSocket = net.Socket | tls.TLSSocket
|
||||||
|
|
||||||
|
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
|
||||||
|
throw new Error(`smtp_unexpected_response:${context}:${response.code}:${response.lines.join(" | ")}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connectTls(host: string, port: number, timeoutMs: number) {
|
||||||
|
return new Promise<tls.TLSSocket>((resolve, reject) => {
|
||||||
|
const socket = tls.connect({ host, port, rejectUnauthorized: false, 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, timeoutMs: number) {
|
||||||
|
return new Promise<tls.TLSSocket>((resolve, reject) => {
|
||||||
|
const tlsSocket = tls.connect({ socket, servername: host, rejectUnauthorized: false })
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendSmtpMail(cfg: SmtpConfig, to: string, subject: string, html: string) {
|
async function sendSmtpMail(cfg: SmtpConfig, to: string, subject: string, html: string) {
|
||||||
return new Promise<void>((resolve, reject) => {
|
const timeoutMs = Math.max(1000, cfg.timeoutMs)
|
||||||
const socket = tls.connect(cfg.port, cfg.host, { rejectUnauthorized: false }, () => {
|
|
||||||
let buffer = ""
|
|
||||||
const send = (line: string) => socket.write(line + "\r\n")
|
|
||||||
const wait = (expected: string | RegExp) =>
|
|
||||||
new Promise<void>((res) => {
|
|
||||||
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)
|
|
||||||
res()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
socket.on("data", onData)
|
|
||||||
socket.on("error", reject)
|
|
||||||
})
|
|
||||||
|
|
||||||
;(async () => {
|
let socket: SmtpSocket | null = null
|
||||||
await wait(/^220 /)
|
let reader: ReturnType<typeof createSmtpReader> | null = null
|
||||||
send(`EHLO ${cfg.host}`)
|
|
||||||
await wait(/^250-/)
|
const sendLine = (line: string) => socket?.write(line + "\r\n")
|
||||||
await wait(/^250 /)
|
const readExpected = async (expected: number | ((code: number) => boolean), context: string) => {
|
||||||
send("AUTH LOGIN")
|
if (!reader) throw new Error("smtp_reader_not_ready")
|
||||||
await wait(/^334 /)
|
const response = await reader.read()
|
||||||
send(b64(cfg.username))
|
assertCode(response, expected, context)
|
||||||
await wait(/^334 /)
|
return response
|
||||||
send(b64(cfg.password))
|
}
|
||||||
await wait(/^235 /)
|
|
||||||
send(`MAIL FROM:<${cfg.from.match(/<(.+)>/)?.[1] ?? cfg.from}>`)
|
try {
|
||||||
await wait(/^250 /)
|
socket = cfg.secure ? await connectTls(cfg.host, cfg.port, timeoutMs) : await connectPlain(cfg.host, cfg.port, timeoutMs)
|
||||||
send(`RCPT TO:<${to}>`)
|
reader = createSmtpReader(socket, timeoutMs)
|
||||||
await wait(/^250 /)
|
|
||||||
send("DATA")
|
await readExpected(220, "greeting")
|
||||||
await wait(/^354 /)
|
|
||||||
const headers = [
|
sendLine(`EHLO ${cfg.host}`)
|
||||||
`From: ${cfg.from}`,
|
let ehlo = await readExpected(250, "ehlo")
|
||||||
`To: ${to}`,
|
|
||||||
`Subject: ${subject}`,
|
if (!cfg.secure && isCapability(ehlo.lines, "STARTTLS")) {
|
||||||
"MIME-Version: 1.0",
|
sendLine("STARTTLS")
|
||||||
"Content-Type: text/html; charset=UTF-8",
|
await readExpected(220, "starttls")
|
||||||
].join("\r\n")
|
|
||||||
send(headers + "\r\n\r\n" + html + "\r\n.")
|
reader.dispose()
|
||||||
await wait(/^250 /)
|
socket = await upgradeToStartTls(socket as net.Socket, cfg.host, timeoutMs)
|
||||||
send("QUIT")
|
reader = createSmtpReader(socket, timeoutMs)
|
||||||
socket.end()
|
|
||||||
resolve()
|
sendLine(`EHLO ${cfg.host}`)
|
||||||
})().catch(reject)
|
ehlo = await readExpected(250, "ehlo_starttls")
|
||||||
})
|
}
|
||||||
socket.on("error", reject)
|
|
||||||
})
|
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")
|
||||||
|
|
||||||
|
sendLine(`RCPT TO:<${to}>`)
|
||||||
|
await readExpected((code) => Math.floor(code / 100) === 2, "rcpt_to")
|
||||||
|
|
||||||
|
sendLine("DATA")
|
||||||
|
await readExpected(354, "data")
|
||||||
|
|
||||||
|
const headers = [
|
||||||
|
`From: ${cfg.from}`,
|
||||||
|
`To: ${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()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const sendPublicCommentEmail = action({
|
export const sendPublicCommentEmail = action({
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,12 @@ import {
|
||||||
getTemplateByKey,
|
getTemplateByKey,
|
||||||
normalizeFormTemplateKey,
|
normalizeFormTemplateKey,
|
||||||
} from "./ticketFormTemplates";
|
} from "./ticketFormTemplates";
|
||||||
|
import {
|
||||||
|
applyChecklistTemplateToItems,
|
||||||
|
checklistBlocksResolution,
|
||||||
|
normalizeChecklistText,
|
||||||
|
type TicketChecklistItem,
|
||||||
|
} from "./ticketChecklist";
|
||||||
|
|
||||||
const STAFF_ROLES = new Set(["ADMIN", "MANAGER", "AGENT"]);
|
const STAFF_ROLES = new Set(["ADMIN", "MANAGER", "AGENT"]);
|
||||||
const INTERNAL_STAFF_ROLES = new Set(["ADMIN", "AGENT"]);
|
const INTERNAL_STAFF_ROLES = new Set(["ADMIN", "AGENT"]);
|
||||||
|
|
@ -2088,6 +2094,20 @@ export const getById = query({
|
||||||
updatedAt: t.updatedAt,
|
updatedAt: t.updatedAt,
|
||||||
createdAt: t.createdAt,
|
createdAt: t.createdAt,
|
||||||
tags: t.tags ?? [],
|
tags: t.tags ?? [],
|
||||||
|
checklist: Array.isArray(t.checklist)
|
||||||
|
? t.checklist.map((item) => ({
|
||||||
|
id: item.id,
|
||||||
|
text: item.text,
|
||||||
|
done: item.done,
|
||||||
|
required: typeof item.required === "boolean" ? item.required : true,
|
||||||
|
templateId: item.templateId ? String(item.templateId) : undefined,
|
||||||
|
templateItemId: item.templateItemId ?? undefined,
|
||||||
|
createdAt: item.createdAt ?? undefined,
|
||||||
|
createdBy: item.createdBy ? String(item.createdBy) : undefined,
|
||||||
|
doneAt: item.doneAt ?? undefined,
|
||||||
|
doneBy: item.doneBy ? String(item.doneBy) : undefined,
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
lastTimelineEntry: null,
|
lastTimelineEntry: null,
|
||||||
metrics: null,
|
metrics: null,
|
||||||
csatScore: typeof t.csatScore === "number" ? t.csatScore : null,
|
csatScore: typeof t.csatScore === "number" ? t.csatScore : null,
|
||||||
|
|
@ -2177,6 +2197,15 @@ export const create = mutation({
|
||||||
categoryId: v.id("ticketCategories"),
|
categoryId: v.id("ticketCategories"),
|
||||||
subcategoryId: v.id("ticketSubcategories"),
|
subcategoryId: v.id("ticketSubcategories"),
|
||||||
machineId: v.optional(v.id("machines")),
|
machineId: v.optional(v.id("machines")),
|
||||||
|
checklist: v.optional(
|
||||||
|
v.array(
|
||||||
|
v.object({
|
||||||
|
text: v.string(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
),
|
||||||
|
checklistTemplateIds: v.optional(v.array(v.id("ticketChecklistTemplates"))),
|
||||||
customFields: v.optional(
|
customFields: v.optional(
|
||||||
v.array(
|
v.array(
|
||||||
v.object({
|
v.object({
|
||||||
|
|
@ -2285,6 +2314,23 @@ export const create = mutation({
|
||||||
const nextRef = existing[0]?.reference ? existing[0].reference + 1 : 41000;
|
const nextRef = existing[0]?.reference ? existing[0].reference + 1 : 41000;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const initialStatus: TicketStatusNormalized = "PENDING";
|
const initialStatus: TicketStatusNormalized = "PENDING";
|
||||||
|
const manualChecklist: TicketChecklistItem[] = (args.checklist ?? []).map((entry) => {
|
||||||
|
const text = normalizeChecklistText(entry.text ?? "");
|
||||||
|
if (!text) {
|
||||||
|
throw new ConvexError("Item do checklist inválido.")
|
||||||
|
}
|
||||||
|
if (text.length > 240) {
|
||||||
|
throw new ConvexError("Item do checklist muito longo (máx. 240 caracteres).")
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
text,
|
||||||
|
done: false,
|
||||||
|
required: typeof entry.required === "boolean" ? entry.required : true,
|
||||||
|
createdAt: now,
|
||||||
|
createdBy: args.actorId,
|
||||||
|
}
|
||||||
|
})
|
||||||
const requesterSnapshot = {
|
const requesterSnapshot = {
|
||||||
name: requester.name,
|
name: requester.name,
|
||||||
email: requester.email,
|
email: requester.email,
|
||||||
|
|
@ -2302,6 +2348,19 @@ export const create = mutation({
|
||||||
const companySnapshot = companyDoc
|
const companySnapshot = companyDoc
|
||||||
? { name: companyDoc.name, slug: companyDoc.slug, isAvulso: companyDoc.isAvulso ?? undefined }
|
? { name: companyDoc.name, slug: companyDoc.slug, isAvulso: companyDoc.isAvulso ?? undefined }
|
||||||
: undefined
|
: undefined
|
||||||
|
const resolvedCompanyId = companyDoc?._id ?? requester.companyId ?? undefined
|
||||||
|
|
||||||
|
let checklist = manualChecklist
|
||||||
|
for (const templateId of args.checklistTemplateIds ?? []) {
|
||||||
|
const template = await ctx.db.get(templateId)
|
||||||
|
if (!template || template.tenantId !== args.tenantId || template.isArchived === true) {
|
||||||
|
throw new ConvexError("Template de checklist inválido.")
|
||||||
|
}
|
||||||
|
if (template.companyId && (!resolvedCompanyId || String(template.companyId) !== String(resolvedCompanyId))) {
|
||||||
|
throw new ConvexError("Template de checklist não pertence à empresa do ticket.")
|
||||||
|
}
|
||||||
|
checklist = applyChecklistTemplateToItems(checklist, template, { now, actorId: args.actorId }).checklist
|
||||||
|
}
|
||||||
|
|
||||||
const assigneeSnapshot = initialAssignee
|
const assigneeSnapshot = initialAssignee
|
||||||
? {
|
? {
|
||||||
|
|
@ -2358,7 +2417,7 @@ export const create = mutation({
|
||||||
requesterSnapshot,
|
requesterSnapshot,
|
||||||
assigneeId: initialAssigneeId,
|
assigneeId: initialAssigneeId,
|
||||||
assigneeSnapshot,
|
assigneeSnapshot,
|
||||||
companyId: companyDoc?._id ?? requester.companyId ?? undefined,
|
companyId: resolvedCompanyId,
|
||||||
companySnapshot,
|
companySnapshot,
|
||||||
machineId: machineDoc?._id ?? undefined,
|
machineId: machineDoc?._id ?? undefined,
|
||||||
machineSnapshot: machineDoc
|
machineSnapshot: machineDoc
|
||||||
|
|
@ -2382,6 +2441,7 @@ export const create = mutation({
|
||||||
resolvedAt: undefined,
|
resolvedAt: undefined,
|
||||||
closedAt: undefined,
|
closedAt: undefined,
|
||||||
tags: [],
|
tags: [],
|
||||||
|
checklist: checklist.length > 0 ? checklist : undefined,
|
||||||
slaPolicyId: undefined,
|
slaPolicyId: undefined,
|
||||||
dueAt: visitDueAt && isVisitQueue ? visitDueAt : undefined,
|
dueAt: visitDueAt && isVisitQueue ? visitDueAt : undefined,
|
||||||
customFields: normalizedCustomFields.length ? normalizedCustomFields : undefined,
|
customFields: normalizedCustomFields.length ? normalizedCustomFields : undefined,
|
||||||
|
|
@ -2423,6 +2483,259 @@ export const create = mutation({
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function ensureChecklistEditor(viewer: { role: string | null }) {
|
||||||
|
const normalizedRole = (viewer.role ?? "").toUpperCase();
|
||||||
|
if (!INTERNAL_STAFF_ROLES.has(normalizedRole)) {
|
||||||
|
throw new ConvexError("Apenas administradores e agentes podem alterar o checklist.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTicketChecklist(list: unknown): TicketChecklistItem[] {
|
||||||
|
if (!Array.isArray(list)) return [];
|
||||||
|
return list as TicketChecklistItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const addChecklistItem = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
text: v.string(),
|
||||||
|
required: v.optional(v.boolean()),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, text, required }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const normalizedText = normalizeChecklistText(text);
|
||||||
|
if (!normalizedText) {
|
||||||
|
throw new ConvexError("Informe o texto do item do checklist.");
|
||||||
|
}
|
||||||
|
if (normalizedText.length > 240) {
|
||||||
|
throw new ConvexError("Item do checklist muito longo (máx. 240 caracteres).");
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const item: TicketChecklistItem = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
text: normalizedText,
|
||||||
|
done: false,
|
||||||
|
required: typeof required === "boolean" ? required : true,
|
||||||
|
createdAt: now,
|
||||||
|
createdBy: actorId,
|
||||||
|
};
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist).concat(item);
|
||||||
|
|
||||||
|
await ctx.db.patch(ticketId, {
|
||||||
|
checklist: checklist.length > 0 ? checklist : undefined,
|
||||||
|
updatedAt: now,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { ok: true, item };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateChecklistItemText = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
itemId: v.string(),
|
||||||
|
text: v.string(),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, itemId, text }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const normalizedText = normalizeChecklistText(text);
|
||||||
|
if (!normalizedText) {
|
||||||
|
throw new ConvexError("Informe o texto do item do checklist.");
|
||||||
|
}
|
||||||
|
if (normalizedText.length > 240) {
|
||||||
|
throw new ConvexError("Item do checklist muito longo (máx. 240 caracteres).");
|
||||||
|
}
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
const index = checklist.findIndex((item) => item.id === itemId);
|
||||||
|
if (index < 0) {
|
||||||
|
throw new ConvexError("Item do checklist não encontrado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextChecklist = checklist.map((item) =>
|
||||||
|
item.id === itemId ? { ...item, text: normalizedText } : item
|
||||||
|
);
|
||||||
|
|
||||||
|
await ctx.db.patch(ticketId, { checklist: nextChecklist, updatedAt: Date.now() });
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const setChecklistItemDone = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
itemId: v.string(),
|
||||||
|
done: v.boolean(),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, itemId, done }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
const index = checklist.findIndex((item) => item.id === itemId);
|
||||||
|
if (index < 0) {
|
||||||
|
throw new ConvexError("Item do checklist não encontrado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const previous = checklist[index]!;
|
||||||
|
if (previous.done === done) {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const nextChecklist = checklist.map((item) => {
|
||||||
|
if (item.id !== itemId) return item;
|
||||||
|
if (done) {
|
||||||
|
return { ...item, done: true, doneAt: now, doneBy: actorId };
|
||||||
|
}
|
||||||
|
return { ...item, done: false, doneAt: undefined, doneBy: undefined };
|
||||||
|
});
|
||||||
|
|
||||||
|
await ctx.db.patch(ticketId, { checklist: nextChecklist, updatedAt: now });
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const setChecklistItemRequired = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
itemId: v.string(),
|
||||||
|
required: v.boolean(),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, itemId, required }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
const index = checklist.findIndex((item) => item.id === itemId);
|
||||||
|
if (index < 0) {
|
||||||
|
throw new ConvexError("Item do checklist não encontrado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextChecklist = checklist.map((item) => (item.id === itemId ? { ...item, required: Boolean(required) } : item));
|
||||||
|
await ctx.db.patch(ticketId, { checklist: nextChecklist, updatedAt: Date.now() });
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const removeChecklistItem = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
itemId: v.string(),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, itemId }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
const nextChecklist = checklist.filter((item) => item.id !== itemId);
|
||||||
|
await ctx.db.patch(ticketId, {
|
||||||
|
checklist: nextChecklist.length > 0 ? nextChecklist : undefined,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
});
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const completeAllChecklistItems = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const checklist = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
if (checklist.length === 0) return { ok: true };
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const nextChecklist = checklist.map((item) => {
|
||||||
|
if (item.done === true) return item;
|
||||||
|
return { ...item, done: true, doneAt: now, doneBy: actorId };
|
||||||
|
});
|
||||||
|
|
||||||
|
await ctx.db.patch(ticketId, { checklist: nextChecklist, updatedAt: now });
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const applyChecklistTemplate = mutation({
|
||||||
|
args: {
|
||||||
|
ticketId: v.id("tickets"),
|
||||||
|
actorId: v.id("users"),
|
||||||
|
templateId: v.id("ticketChecklistTemplates"),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { ticketId, actorId, templateId }) => {
|
||||||
|
const ticket = await ctx.db.get(ticketId);
|
||||||
|
if (!ticket) {
|
||||||
|
throw new ConvexError("Ticket não encontrado");
|
||||||
|
}
|
||||||
|
const ticketDoc = ticket as Doc<"tickets">;
|
||||||
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc);
|
||||||
|
ensureChecklistEditor(viewer);
|
||||||
|
|
||||||
|
const template = await ctx.db.get(templateId);
|
||||||
|
if (!template || template.tenantId !== ticketDoc.tenantId || template.isArchived === true) {
|
||||||
|
throw new ConvexError("Template de checklist inválido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (template.companyId && (!ticketDoc.companyId || String(template.companyId) !== String(ticketDoc.companyId))) {
|
||||||
|
throw new ConvexError("Template de checklist não pertence à empresa do ticket.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const current = normalizeTicketChecklist(ticketDoc.checklist);
|
||||||
|
const result = applyChecklistTemplateToItems(current, template, { now, actorId });
|
||||||
|
if (result.added === 0) {
|
||||||
|
return { ok: true, added: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.db.patch(ticketId, { checklist: result.checklist, updatedAt: now });
|
||||||
|
return { ok: true, added: result.added };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
export const addComment = mutation({
|
export const addComment = mutation({
|
||||||
args: {
|
args: {
|
||||||
ticketId: v.id("tickets"),
|
ticketId: v.id("tickets"),
|
||||||
|
|
@ -2743,6 +3056,10 @@ export async function resolveTicketHandler(
|
||||||
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc)
|
const viewer = await requireTicketStaff(ctx, actorId, ticketDoc)
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
|
|
||||||
|
if (checklistBlocksResolution((ticketDoc.checklist ?? []) as unknown as TicketChecklistItem[])) {
|
||||||
|
throw new ConvexError("Conclua todos os itens obrigatórios do checklist antes de encerrar o ticket.")
|
||||||
|
}
|
||||||
|
|
||||||
const baseRelated = new Set<string>()
|
const baseRelated = new Set<string>()
|
||||||
for (const rel of relatedTicketIds ?? []) {
|
for (const rel of relatedTicketIds ?? []) {
|
||||||
if (String(rel) === String(ticketId)) continue
|
if (String(rel) === String(ticketId)) continue
|
||||||
|
|
|
||||||
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
|
order: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CLEAR_SELECT_VALUE = "__clear__"
|
||||||
|
|
||||||
export function TicketFormTemplatesManager() {
|
export function TicketFormTemplatesManager() {
|
||||||
const { session, convexUserId } = useAuth()
|
const { session, convexUserId } = useAuth()
|
||||||
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
|
||||||
|
|
@ -276,12 +278,15 @@ export function TicketFormTemplatesManager() {
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium text-neutral-700">Basear em</label>
|
<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>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Em branco" />
|
<SelectValue placeholder="Em branco" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="">Começar do zero</SelectItem>
|
<SelectItem value={CLEAR_SELECT_VALUE}>Começar do zero</SelectItem>
|
||||||
{baseOptions.map((tpl) => (
|
{baseOptions.map((tpl) => (
|
||||||
<SelectItem key={tpl.key} value={tpl.key}>
|
<SelectItem key={tpl.key} value={tpl.key}>
|
||||||
{tpl.label}
|
{tpl.label}
|
||||||
|
|
|
||||||
|
|
@ -120,6 +120,7 @@ const navigation: NavigationGroup[] = [
|
||||||
{ title: "Usuários", url: "/admin/users", icon: Users, requiredRole: "admin" },
|
{ title: "Usuários", url: "/admin/users", icon: Users, requiredRole: "admin" },
|
||||||
{ title: "Campos personalizados", url: "/admin/custom-fields", icon: ClipboardList, 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 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" },
|
{ 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 (
|
return (
|
||||||
<SidebarMenuItem key={item.title}>
|
<SidebarMenuItem key={item.title}>
|
||||||
<SidebarMenuButton asChild isActive={isActive(item)}>
|
<SidebarMenuButton asChild isActive={isActive(item)} className="font-medium">
|
||||||
<Link href={item.url} className="gap-2">
|
<Link href={item.url} className="gap-2">
|
||||||
{item.icon ? <item.icon className="size-4" /> : null}
|
{item.icon ? <item.icon className="size-4" /> : null}
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
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 { Input } from "@/components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
|
|
@ -58,6 +58,7 @@ type ActionType =
|
||||||
| "SET_FORM_TEMPLATE"
|
| "SET_FORM_TEMPLATE"
|
||||||
| "SET_CHAT_ENABLED"
|
| "SET_CHAT_ENABLED"
|
||||||
| "ADD_INTERNAL_COMMENT"
|
| "ADD_INTERNAL_COMMENT"
|
||||||
|
| "APPLY_CHECKLIST_TEMPLATE"
|
||||||
| "SEND_EMAIL"
|
| "SEND_EMAIL"
|
||||||
|
|
||||||
type EmailCtaTarget = "AUTO" | "PORTAL" | "STAFF"
|
type EmailCtaTarget = "AUTO" | "PORTAL" | "STAFF"
|
||||||
|
|
@ -69,6 +70,7 @@ type ActionDraft =
|
||||||
| { id: string; type: "SET_FORM_TEMPLATE"; formTemplate: string | null }
|
| { id: string; type: "SET_FORM_TEMPLATE"; formTemplate: string | null }
|
||||||
| { id: string; type: "SET_CHAT_ENABLED"; enabled: boolean }
|
| { id: string; type: "SET_CHAT_ENABLED"; enabled: boolean }
|
||||||
| { id: string; type: "ADD_INTERNAL_COMMENT"; body: string }
|
| { id: string; type: "ADD_INTERNAL_COMMENT"; body: string }
|
||||||
|
| { id: string; type: "APPLY_CHECKLIST_TEMPLATE"; templateId: string }
|
||||||
| {
|
| {
|
||||||
id: string
|
id: string
|
||||||
type: "SEND_EMAIL"
|
type: "SEND_EMAIL"
|
||||||
|
|
@ -112,6 +114,8 @@ const TRIGGERS = [
|
||||||
{ value: "TICKET_RESOLVED", label: "Finalização" },
|
{ value: "TICKET_RESOLVED", label: "Finalização" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
const CLEAR_SELECT_VALUE = "__clear__"
|
||||||
|
|
||||||
function msToMinutes(ms: number | null) {
|
function msToMinutes(ms: number | null) {
|
||||||
if (!ms || ms <= 0) return 0
|
if (!ms || ms <= 0) return 0
|
||||||
return Math.max(1, Math.round(ms / 60000))
|
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_FORM_TEMPLATE") return { id, type, formTemplate: safeString(base.formTemplate) || null }
|
||||||
if (type === "SET_CHAT_ENABLED") return { id, type, enabled: Boolean(base.enabled) }
|
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 === "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" }
|
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"
|
convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
|
||||||
) as Array<{ id: string; key: string; label: string }> | undefined
|
) 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 initialState = useMemo(() => {
|
||||||
const rawOp = (automation?.conditions as { op?: unknown } | null)?.op
|
const rawOp = (automation?.conditions as { op?: unknown } | null)?.op
|
||||||
const conditionsOp = rawOp === "OR" ? ("OR" as const) : ("AND" as const)
|
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 === "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_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 === "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") {
|
if (a.type === "SEND_EMAIL") {
|
||||||
const subject = a.subject.trim()
|
const subject = a.subject.trim()
|
||||||
const message = a.message.trim()
|
const message = a.message.trim()
|
||||||
|
|
@ -422,6 +437,11 @@ export function AutomationEditorDialog({
|
||||||
<DialogHeader className="gap-4 pb-2">
|
<DialogHeader className="gap-4 pb-2">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<DialogTitle>{automation ? "Editar automação" : "Nova automação"}</DialogTitle>
|
<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">
|
<div className="flex items-center gap-3">
|
||||||
<span className="text-sm font-medium text-neutral-700">Ativa</span>
|
<span className="text-sm font-medium text-neutral-700">Ativa</span>
|
||||||
<Switch
|
<Switch
|
||||||
|
|
@ -733,15 +753,18 @@ export function AutomationEditorDialog({
|
||||||
) : (
|
) : (
|
||||||
<Select
|
<Select
|
||||||
value={c.value}
|
value={c.value}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) => {
|
||||||
setConditions((prev) => prev.map((item) => (item.id === c.id ? { ...item, value } : item)))
|
const nextValue = value === CLEAR_SELECT_VALUE ? "" : value
|
||||||
}
|
setConditions((prev) =>
|
||||||
|
prev.map((item) => (item.id === c.id ? { ...item, value: nextValue } : item))
|
||||||
|
)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="bg-white">
|
<SelectTrigger className="bg-white">
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent className="rounded-xl">
|
<SelectContent className="rounded-xl">
|
||||||
<SelectItem value="">Nenhum</SelectItem>
|
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||||
{(templates ?? []).map((tpl) => (
|
{(templates ?? []).map((tpl) => (
|
||||||
<SelectItem key={tpl.key} value={tpl.key}>
|
<SelectItem key={tpl.key} value={tpl.key}>
|
||||||
{tpl.label}
|
{tpl.label}
|
||||||
|
|
@ -797,13 +820,14 @@ export function AutomationEditorDialog({
|
||||||
const next = value as ActionType
|
const next = value as ActionType
|
||||||
if (next === "MOVE_QUEUE") return { id: item.id, type: next, queueId: "" }
|
if (next === "MOVE_QUEUE") return { id: item.id, type: next, queueId: "" }
|
||||||
if (next === "ASSIGN_TO") return { id: item.id, type: next, assigneeId: "" }
|
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_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 === "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 === "ADD_INTERNAL_COMMENT") return { id: item.id, type: next, body: "" }
|
||||||
if (next === "SEND_EMAIL") {
|
if (next === "APPLY_CHECKLIST_TEMPLATE") return { id: item.id, type: next, templateId: "" }
|
||||||
return {
|
if (next === "SEND_EMAIL") {
|
||||||
id: item.id,
|
return {
|
||||||
type: next,
|
id: item.id,
|
||||||
|
type: next,
|
||||||
subject: "",
|
subject: "",
|
||||||
message: "",
|
message: "",
|
||||||
toRequester: true,
|
toRequester: true,
|
||||||
|
|
@ -829,6 +853,7 @@ export function AutomationEditorDialog({
|
||||||
<SelectItem value="SET_FORM_TEMPLATE">Aplicar formulário</SelectItem>
|
<SelectItem value="SET_FORM_TEMPLATE">Aplicar formulário</SelectItem>
|
||||||
<SelectItem value="SET_CHAT_ENABLED">Habilitar/desabilitar chat</SelectItem>
|
<SelectItem value="SET_CHAT_ENABLED">Habilitar/desabilitar chat</SelectItem>
|
||||||
<SelectItem value="ADD_INTERNAL_COMMENT">Adicionar comentário interno</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>
|
<SelectItem value="SEND_EMAIL">Enviar e-mail</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
@ -893,15 +918,18 @@ export function AutomationEditorDialog({
|
||||||
) : a.type === "SET_FORM_TEMPLATE" ? (
|
) : a.type === "SET_FORM_TEMPLATE" ? (
|
||||||
<Select
|
<Select
|
||||||
value={a.formTemplate ?? ""}
|
value={a.formTemplate ?? ""}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) => {
|
||||||
setActions((prev) => prev.map((item) => (item.id === a.id ? { ...item, formTemplate: value || null } : item)))
|
const nextValue = value === CLEAR_SELECT_VALUE ? null : value
|
||||||
}
|
setActions((prev) =>
|
||||||
|
prev.map((item) => (item.id === a.id ? { ...item, formTemplate: nextValue } : item))
|
||||||
|
)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent className="rounded-xl">
|
<SelectContent className="rounded-xl">
|
||||||
<SelectItem value="">Nenhum</SelectItem>
|
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||||
{(templates ?? []).map((tpl) => (
|
{(templates ?? []).map((tpl) => (
|
||||||
<SelectItem key={tpl.key} value={tpl.key}>
|
<SelectItem key={tpl.key} value={tpl.key}>
|
||||||
{tpl.label}
|
{tpl.label}
|
||||||
|
|
@ -920,6 +948,25 @@ export function AutomationEditorDialog({
|
||||||
className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300"
|
className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300"
|
||||||
/>
|
/>
|
||||||
</div>
|
</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" ? (
|
) : a.type === "SEND_EMAIL" ? (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
|
|
@ -982,15 +1029,18 @@ export function AutomationEditorDialog({
|
||||||
<Label className="text-xs">Agente específico (opcional)</Label>
|
<Label className="text-xs">Agente específico (opcional)</Label>
|
||||||
<Select
|
<Select
|
||||||
value={a.toUserId}
|
value={a.toUserId}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) => {
|
||||||
setActions((prev) => prev.map((item) => (item.id === a.id ? { ...item, toUserId: value } : item)))
|
const nextValue = value === CLEAR_SELECT_VALUE ? "" : value
|
||||||
}
|
setActions((prev) =>
|
||||||
|
prev.map((item) => (item.id === a.id ? { ...item, toUserId: nextValue } : item))
|
||||||
|
)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent className="rounded-xl">
|
<SelectContent className="rounded-xl">
|
||||||
<SelectItem value="">Nenhum</SelectItem>
|
<SelectItem value={CLEAR_SELECT_VALUE}>Nenhum</SelectItem>
|
||||||
{(agents ?? []).map((u) => (
|
{(agents ?? []).map((u) => (
|
||||||
<SelectItem key={u._id} value={String(u._id)}>
|
<SelectItem key={u._id} value={String(u._id)}>
|
||||||
{u.name}
|
{u.name}
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import { useAuth } from "@/lib/auth-client"
|
||||||
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
import { DEFAULT_TENANT_ID } from "@/lib/constants"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Skeleton } from "@/components/ui/skeleton"
|
import { Skeleton } from "@/components/ui/skeleton"
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
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="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<DialogTitle>Histórico de execuções</DialogTitle>
|
<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 ? (
|
{automationName ? (
|
||||||
<p className="text-sm text-neutral-600">{automationName}</p>
|
<p className="text-sm text-neutral-600">{automationName}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
|
||||||
|
|
@ -155,7 +155,7 @@ export function AutomationsManager() {
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-lg font-semibold text-neutral-900">Automações</CardTitle>
|
<CardTitle className="text-lg font-semibold text-neutral-900">Automações</CardTitle>
|
||||||
<CardDescription className="text-neutral-600">
|
<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>
|
</CardDescription>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
<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()
|
onSuccess()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(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.", {
|
const fallback = applyAdjustment
|
||||||
id: "close-ticket",
|
? "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 {
|
} finally {
|
||||||
setIsSubmitting(false)
|
setIsSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -34,9 +34,10 @@ import { cn } from "@/lib/utils"
|
||||||
import { priorityStyles } from "@/lib/ticket-priority-style"
|
import { priorityStyles } from "@/lib/ticket-priority-style"
|
||||||
import { normalizeCustomFieldInputs } from "@/lib/ticket-form-helpers"
|
import { normalizeCustomFieldInputs } from "@/lib/ticket-form-helpers"
|
||||||
import type { TicketFormDefinition, TicketFormFieldDefinition } from "@/lib/ticket-form-types"
|
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 { TimePicker } from "@/components/ui/time-picker"
|
||||||
import { VISIT_KEYWORDS } from "@/lib/ticket-matchers"
|
import { VISIT_KEYWORDS } from "@/lib/ticket-matchers"
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
|
|
||||||
type TriggerVariant = "button" | "card"
|
type TriggerVariant = "button" | "card"
|
||||||
|
|
||||||
|
|
@ -51,6 +52,19 @@ type CustomerOption = {
|
||||||
avatarUrl: string | null
|
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 {
|
function getInitials(name: string | null | undefined, fallback: string): string {
|
||||||
const normalizedName = (name ?? "").trim()
|
const normalizedName = (name ?? "").trim()
|
||||||
if (normalizedName.length > 0) {
|
if (normalizedName.length > 0) {
|
||||||
|
|
@ -219,6 +233,17 @@ export function NewTicketDialog({
|
||||||
: "skip"
|
: "skip"
|
||||||
) as TicketFormDefinition[] | undefined
|
) 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 forms = useMemo<TicketFormDefinition[]>(() => {
|
||||||
const fallback: TicketFormDefinition = {
|
const fallback: TicketFormDefinition = {
|
||||||
key: "default",
|
key: "default",
|
||||||
|
|
@ -240,6 +265,29 @@ export function NewTicketDialog({
|
||||||
const [customFieldValues, setCustomFieldValues] = useState<Record<string, unknown>>({})
|
const [customFieldValues, setCustomFieldValues] = useState<Record<string, unknown>>({})
|
||||||
const [openCalendarField, setOpenCalendarField] = useState<string | null>(null)
|
const [openCalendarField, setOpenCalendarField] = useState<string | null>(null)
|
||||||
const [visitDatePickerOpen, setVisitDatePickerOpen] = useState(false)
|
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])
|
const selectedForm = useMemo(() => forms.find((formDef) => formDef.key === selectedFormKey) ?? forms[0], [forms, selectedFormKey])
|
||||||
|
|
||||||
|
|
@ -418,6 +466,11 @@ export function NewTicketDialog({
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
setCustomersInitialized(false)
|
setCustomersInitialized(false)
|
||||||
|
setManualChecklist([])
|
||||||
|
setAppliedChecklistTemplateIds([])
|
||||||
|
setChecklistTemplateToApply("")
|
||||||
|
setChecklistItemText("")
|
||||||
|
setChecklistItemRequired(true)
|
||||||
form.setValue("companyId", NO_COMPANY_VALUE, { shouldDirty: false, shouldTouch: false })
|
form.setValue("companyId", NO_COMPANY_VALUE, { shouldDirty: false, shouldTouch: false })
|
||||||
form.setValue("requesterId", "", { shouldDirty: false, shouldTouch: false })
|
form.setValue("requesterId", "", { shouldDirty: false, shouldTouch: false })
|
||||||
return
|
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>) {
|
async function submit(values: z.infer<typeof schema>) {
|
||||||
if (!convexUserId) return
|
if (!convexUserId) return
|
||||||
|
|
||||||
|
|
@ -562,6 +640,17 @@ export function NewTicketDialog({
|
||||||
}
|
}
|
||||||
customFieldsPayload = normalized.payload
|
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)
|
setLoading(true)
|
||||||
toast.loading("Criando ticket…", { id: "new-ticket" })
|
toast.loading("Criando ticket…", { id: "new-ticket" })
|
||||||
try {
|
try {
|
||||||
|
|
@ -590,6 +679,8 @@ export function NewTicketDialog({
|
||||||
categoryId: values.categoryId as Id<"ticketCategories">,
|
categoryId: values.categoryId as Id<"ticketCategories">,
|
||||||
subcategoryId: values.subcategoryId as Id<"ticketSubcategories">,
|
subcategoryId: values.subcategoryId as Id<"ticketSubcategories">,
|
||||||
formTemplate: selectedFormKey !== "default" ? selectedFormKey : undefined,
|
formTemplate: selectedFormKey !== "default" ? selectedFormKey : undefined,
|
||||||
|
checklist: checklistPayload.length > 0 ? checklistPayload : undefined,
|
||||||
|
checklistTemplateIds: checklistTemplateIds.length > 0 ? checklistTemplateIds : undefined,
|
||||||
customFields: customFieldsPayload.length > 0 ? customFieldsPayload : undefined,
|
customFields: customFieldsPayload.length > 0 ? customFieldsPayload : undefined,
|
||||||
visitDate: visitDateTimestamp,
|
visitDate: visitDateTimestamp,
|
||||||
})
|
})
|
||||||
|
|
@ -630,6 +721,11 @@ export function NewTicketDialog({
|
||||||
setCustomFieldValues({})
|
setCustomFieldValues({})
|
||||||
setAssigneeInitialized(false)
|
setAssigneeInitialized(false)
|
||||||
setAttachments([])
|
setAttachments([])
|
||||||
|
setManualChecklist([])
|
||||||
|
setAppliedChecklistTemplateIds([])
|
||||||
|
setChecklistTemplateToApply("")
|
||||||
|
setChecklistItemText("")
|
||||||
|
setChecklistItemRequired(true)
|
||||||
// Navegar para o ticket recém-criado
|
// Navegar para o ticket recém-criado
|
||||||
window.location.href = `/tickets/${id}`
|
window.location.href = `/tickets/${id}`
|
||||||
} catch {
|
} catch {
|
||||||
|
|
@ -1264,6 +1360,166 @@ export function NewTicketDialog({
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</FieldGroup>
|
</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>
|
</FieldSet>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</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
|
actionSlot?: ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CLEAR_SELECT_VALUE = "__clear__"
|
||||||
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
|
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
|
||||||
|
|
||||||
const DEFAULT_FORM: TicketFormDefinition = {
|
const DEFAULT_FORM: TicketFormDefinition = {
|
||||||
|
|
@ -483,13 +484,22 @@ function renderFieldEditor(field: TicketFormFieldDefinition) {
|
||||||
<FieldLabel className="flex items-center gap-1">
|
<FieldLabel className="flex items-center gap-1">
|
||||||
{field.label} {field.required ? <span className="text-destructive">*</span> : null}
|
{field.label} {field.required ? <span className="text-destructive">*</span> : null}
|
||||||
</FieldLabel>
|
</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>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent className="max-h-60 overflow-y-auto rounded-xl border border-slate-200 bg-white text-neutral-800 shadow-md">
|
<SelectContent className="max-h-60 overflow-y-auto rounded-xl border border-slate-200 bg-white text-neutral-800 shadow-md">
|
||||||
{!field.required ? (
|
{!field.required ? (
|
||||||
<SelectItem value="" className="text-neutral-500">
|
<SelectItem value={CLEAR_SELECT_VALUE} className="text-neutral-500">
|
||||||
Limpar seleção
|
Limpar seleção
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@ import { TicketSummaryHeader } from "@/components/tickets/ticket-summary-header"
|
||||||
import { TicketTimeline } from "@/components/tickets/ticket-timeline";
|
import { TicketTimeline } from "@/components/tickets/ticket-timeline";
|
||||||
import { TicketCsatCard } from "@/components/tickets/ticket-csat-card";
|
import { TicketCsatCard } from "@/components/tickets/ticket-csat-card";
|
||||||
import { TicketChatHistory } from "@/components/tickets/ticket-chat-history";
|
import { TicketChatHistory } from "@/components/tickets/ticket-chat-history";
|
||||||
|
import { TicketChecklistCard } from "@/components/tickets/ticket-checklist-card";
|
||||||
import { useAuth } from "@/lib/auth-client";
|
import { useAuth } from "@/lib/auth-client";
|
||||||
|
|
||||||
export function TicketDetailView({ id }: { id: string }) {
|
export function TicketDetailView({ id }: { id: string }) {
|
||||||
|
|
@ -107,6 +108,7 @@ export function TicketDetailView({ id }: { id: string }) {
|
||||||
<TicketCsatCard ticket={ticket} />
|
<TicketCsatCard ticket={ticket} />
|
||||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
<TicketChecklistCard ticket={ticket} />
|
||||||
<TicketComments ticket={ticket} />
|
<TicketComments ticket={ticket} />
|
||||||
<TicketTimeline ticket={ticket} />
|
<TicketTimeline ticket={ticket} />
|
||||||
<TicketChatHistory ticketId={id} />
|
<TicketChatHistory ticketId={id} />
|
||||||
|
|
|
||||||
|
|
@ -175,6 +175,10 @@ export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
|
||||||
const viewerEmailRaw = session?.user?.email ?? machineContext?.assignedUserEmail ?? null
|
const viewerEmailRaw = session?.user?.email ?? machineContext?.assignedUserEmail ?? null
|
||||||
const viewerEmail = (viewerEmailRaw ?? "").trim().toLowerCase()
|
const viewerEmail = (viewerEmailRaw ?? "").trim().toLowerCase()
|
||||||
const [status, setStatus] = useState<TicketStatus>(ticket.status)
|
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 [visitStatusLoading, setVisitStatusLoading] = useState(false)
|
||||||
const rawReopenDeadline = ticket.reopenDeadline ?? null
|
const rawReopenDeadline = ticket.reopenDeadline ?? null
|
||||||
const fallbackClosedMs = ticket.closedAt?.getTime() ?? ticket.resolvedAt?.getTime() ?? 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="absolute right-6 top-6 flex flex-col items-end gap-1">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{status !== "RESOLVED" ? (
|
{status !== "RESOLVED" ? (
|
||||||
<Button
|
checklistRequiredPending > 0 ? (
|
||||||
type="button"
|
<Tooltip>
|
||||||
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"
|
<TooltipTrigger asChild>
|
||||||
onClick={() => setCloseOpen(true)}
|
<span>
|
||||||
>
|
<Button
|
||||||
<CheckCircle2 className="size-4" /> Encerrar
|
type="button"
|
||||||
</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 ? (
|
) : canReopenTicket ? (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,7 @@ function ChartContainer({
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ChartStyle id={chartId} config={config} />
|
<ChartStyle id={chartId} config={config} />
|
||||||
<RechartsPrimitive.ResponsiveContainer>
|
<RechartsPrimitive.ResponsiveContainer initialDimension={{ width: 1, height: 1 }} minWidth={0}>
|
||||||
{children}
|
{children}
|
||||||
</RechartsPrimitive.ResponsiveContainer>
|
</RechartsPrimitive.ResponsiveContainer>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,22 @@ const serverTicketSchema = z.object({
|
||||||
queue: z.string().nullable(),
|
queue: z.string().nullable(),
|
||||||
formTemplate: z.string().nullable().optional(),
|
formTemplate: z.string().nullable().optional(),
|
||||||
formTemplateLabel: 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,
|
requester: serverUserSchema,
|
||||||
assignee: serverUserSchema.nullable(),
|
assignee: serverUserSchema.nullable(),
|
||||||
company: z
|
company: z
|
||||||
|
|
@ -227,6 +243,10 @@ export function mapTicketFromServer(input: unknown) {
|
||||||
...base
|
...base
|
||||||
} = serverTicketSchema.parse(input);
|
} = serverTicketSchema.parse(input);
|
||||||
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
||||||
|
const checklist = (s.checklist ?? []).map((item) => ({
|
||||||
|
...item,
|
||||||
|
required: item.required ?? true,
|
||||||
|
}));
|
||||||
const slaSnapshot = s.slaSnapshot
|
const slaSnapshot = s.slaSnapshot
|
||||||
? {
|
? {
|
||||||
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
||||||
|
|
@ -243,6 +263,7 @@ export function mapTicketFromServer(input: unknown) {
|
||||||
const ui = {
|
const ui = {
|
||||||
...base,
|
...base,
|
||||||
status: normalizeTicketStatus(s.status),
|
status: normalizeTicketStatus(s.status),
|
||||||
|
checklist,
|
||||||
company: s.company
|
company: s.company
|
||||||
? { id: s.company.id, name: s.company.name, isAvulso: s.company.isAvulso ?? false }
|
? { id: s.company.id, name: s.company.name, isAvulso: s.company.isAvulso ?? false }
|
||||||
: undefined,
|
: undefined,
|
||||||
|
|
@ -325,6 +346,10 @@ export function mapTicketWithDetailsFromServer(input: unknown) {
|
||||||
...base
|
...base
|
||||||
} = serverTicketWithDetailsSchema.parse(input);
|
} = serverTicketWithDetailsSchema.parse(input);
|
||||||
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
const s = { csatScore, csatMaxScore, csatComment, csatRatedAt, csatRatedBy, ...base };
|
||||||
|
const checklist = (s.checklist ?? []).map((item) => ({
|
||||||
|
...item,
|
||||||
|
required: item.required ?? true,
|
||||||
|
}));
|
||||||
const slaSnapshot = s.slaSnapshot
|
const slaSnapshot = s.slaSnapshot
|
||||||
? {
|
? {
|
||||||
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
categoryId: s.slaSnapshot.categoryId ? String(s.slaSnapshot.categoryId) : undefined,
|
||||||
|
|
@ -360,6 +385,7 @@ export function mapTicketWithDetailsFromServer(input: unknown) {
|
||||||
...base,
|
...base,
|
||||||
customFields,
|
customFields,
|
||||||
status: normalizeTicketStatus(base.status),
|
status: normalizeTicketStatus(base.status),
|
||||||
|
checklist,
|
||||||
category: base.category ?? undefined,
|
category: base.category ?? undefined,
|
||||||
subcategory: base.subcategory ?? undefined,
|
subcategory: base.subcategory ?? undefined,
|
||||||
lastTimelineEntry: base.lastTimelineEntry ?? undefined,
|
lastTimelineEntry: base.lastTimelineEntry ?? undefined,
|
||||||
|
|
|
||||||
|
|
@ -134,6 +134,20 @@ export const ticketCustomFieldValueSchema = z.object({
|
||||||
})
|
})
|
||||||
export type TicketCustomFieldValue = z.infer<typeof ticketCustomFieldValueSchema>
|
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({
|
export const ticketSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
reference: z.number(),
|
reference: z.number(),
|
||||||
|
|
@ -196,6 +210,7 @@ export const ticketSchema = z.object({
|
||||||
csatRatedBy: z.string().nullable().optional(),
|
csatRatedBy: z.string().nullable().optional(),
|
||||||
category: ticketCategorySummarySchema.nullable().optional(),
|
category: ticketCategorySummarySchema.nullable().optional(),
|
||||||
subcategory: ticketSubcategorySummarySchema.nullable().optional(),
|
subcategory: ticketSubcategorySummarySchema.nullable().optional(),
|
||||||
|
checklist: z.array(ticketChecklistItemSchema).default([]),
|
||||||
workSummary: z
|
workSummary: z
|
||||||
.object({
|
.object({
|
||||||
totalWorkedMs: z.number(),
|
totalWorkedMs: z.number(),
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,14 @@
|
||||||
|
import net from "net"
|
||||||
import tls from "tls"
|
import tls from "tls"
|
||||||
|
|
||||||
type SmtpConfig = {
|
type SmtpConfig = {
|
||||||
host: string
|
host: string
|
||||||
port: number
|
port: number
|
||||||
|
domain?: string
|
||||||
username: string
|
username: string
|
||||||
password: string
|
password: string
|
||||||
from: string
|
from: string
|
||||||
|
starttls?: boolean
|
||||||
tls?: boolean
|
tls?: boolean
|
||||||
rejectUnauthorized?: boolean
|
rejectUnauthorized?: boolean
|
||||||
timeoutMs?: number
|
timeoutMs?: number
|
||||||
|
|
@ -29,74 +32,253 @@ function extractEnvelopeAddress(from: string): string {
|
||||||
return from
|
return from
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendSmtpMail(cfg: SmtpConfig, to: string | string[], subject: string, html: string) {
|
type SmtpSocket = net.Socket | tls.TLSSocket
|
||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
;(async () => {
|
type SmtpResponse = { code: number; lines: string[] }
|
||||||
await wait(/^220 /)
|
|
||||||
send(`EHLO ${cfg.host}`)
|
function createSmtpReader(socket: SmtpSocket, timeoutMs: number) {
|
||||||
await wait(/^250-/)
|
let buffer = ""
|
||||||
await wait(/^250 /)
|
let current: SmtpResponse | null = null
|
||||||
send("AUTH LOGIN")
|
const queue: SmtpResponse[] = []
|
||||||
await wait(/^334 /)
|
let pending:
|
||||||
send(b64(cfg.username))
|
| { resolve: (response: SmtpResponse) => void; reject: (error: unknown) => void; timer: ReturnType<typeof setTimeout> }
|
||||||
await wait(/^334 /)
|
| null = null
|
||||||
send(b64(cfg.password))
|
|
||||||
await wait(/^235 /)
|
const finalize = (response: SmtpResponse) => {
|
||||||
const envelopeFrom = extractEnvelopeAddress(cfg.from)
|
if (pending) {
|
||||||
send(`MAIL FROM:<${envelopeFrom}>`)
|
clearTimeout(pending.timer)
|
||||||
await wait(/^250 /)
|
const resolve = pending.resolve
|
||||||
const rcpts: string[] = Array.isArray(to)
|
pending = null
|
||||||
? to
|
resolve(response)
|
||||||
: String(to)
|
return
|
||||||
.split(/[;,]/)
|
}
|
||||||
.map((s) => s.trim())
|
queue.push(response)
|
||||||
.filter(Boolean)
|
}
|
||||||
for (const rcpt of rcpts) {
|
|
||||||
send(`RCPT TO:<${rcpt}>`)
|
const onData = (data: Buffer) => {
|
||||||
await wait(/^250 /)
|
buffer += data.toString("utf8")
|
||||||
}
|
const lines = buffer.split(/\r?\n/)
|
||||||
send("DATA")
|
buffer = lines.pop() ?? ""
|
||||||
await wait(/^354 /)
|
|
||||||
const headers = [
|
for (const line of lines) {
|
||||||
`From: ${cfg.from}`,
|
if (!line) continue
|
||||||
`To: ${Array.isArray(to) ? to.join(", ") : to}`,
|
const match = line.match(/^(\d{3})([ -])\s?(.*)$/)
|
||||||
`Subject: ${subject}`,
|
if (!match) continue
|
||||||
"MIME-Version: 1.0",
|
|
||||||
"Content-Type: text/html; charset=UTF-8",
|
const code = Number(match[1])
|
||||||
].join("\r\n")
|
const isFinal = match[2] === " "
|
||||||
send(headers + "\r\n\r\n" + html + "\r\n.")
|
|
||||||
await wait(/^250 /)
|
if (!current) current = { code, lines: [] }
|
||||||
send("QUIT")
|
current.lines.push(line)
|
||||||
socket.end()
|
|
||||||
resolve()
|
if (isFinal) {
|
||||||
})().catch(reject)
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -51,18 +51,34 @@ describe("sendSmtpMail - integracao", () => {
|
||||||
// Para rodar: SMTP_INTEGRATION_TEST=true bun test tests/email-smtp.test.ts
|
// Para rodar: SMTP_INTEGRATION_TEST=true bun test tests/email-smtp.test.ts
|
||||||
const { sendSmtpMail } = await import("@/server/email-smtp")
|
const { sendSmtpMail } = await import("@/server/email-smtp")
|
||||||
|
|
||||||
|
const host = process.env.SMTP_HOST
|
||||||
|
const port = process.env.SMTP_PORT
|
||||||
|
const username = process.env.SMTP_USER
|
||||||
|
const password = process.env.SMTP_PASS
|
||||||
|
const fromEmail = process.env.SMTP_FROM_EMAIL
|
||||||
|
const fromName = process.env.SMTP_FROM_NAME ?? "Sistema de Chamados"
|
||||||
|
|
||||||
|
if (!host || !port || !username || !password || !fromEmail) {
|
||||||
|
throw new Error(
|
||||||
|
"Variáveis SMTP ausentes. Defina SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM_EMAIL (e opcionalmente SMTP_FROM_NAME, SMTP_SECURE, SMTP_TEST_TO)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
host: process.env.SMTP_HOST ?? "smtp.c.inova.com.br",
|
host,
|
||||||
port: Number(process.env.SMTP_PORT ?? 587),
|
port: Number(port),
|
||||||
username: process.env.SMTP_USER ?? "envio@rever.com.br",
|
username,
|
||||||
password: process.env.SMTP_PASS ?? "CAAJQm6ZT6AUdhXRTDYu",
|
password,
|
||||||
from: process.env.SMTP_FROM_EMAIL ?? "Sistema de Chamados <envio@rever.com.br>",
|
from: `"${fromName}" <${fromEmail}>`,
|
||||||
|
tls: (process.env.SMTP_SECURE ?? "false").toLowerCase() === "true",
|
||||||
|
starttls: (process.env.SMTP_SECURE ?? "false").toLowerCase() !== "true",
|
||||||
timeoutMs: 30000,
|
timeoutMs: 30000,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enviar email de teste
|
const to = process.env.SMTP_TEST_TO ?? fromEmail
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
sendSmtpMail(config, "envio@rever.com.br", "Teste automatico do sistema", "<p>Este e um teste automatico.</p>")
|
sendSmtpMail(config, to, "Teste automático do sistema", "<p>Este é um teste automático.</p>")
|
||||||
).resolves.toBeUndefined()
|
).resolves.toBeUndefined()
|
||||||
})
|
}, { timeout: 60000 })
|
||||||
})
|
})
|
||||||
|
|
|
||||||
77
tests/ticket-checklist.test.ts
Normal file
77
tests/ticket-checklist.test.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
import { describe, expect, it } from "bun:test"
|
||||||
|
|
||||||
|
import type { Id } from "../convex/_generated/dataModel"
|
||||||
|
import { applyChecklistTemplateToItems, checklistBlocksResolution } from "../convex/ticketChecklist"
|
||||||
|
|
||||||
|
describe("convex.ticketChecklist", () => {
|
||||||
|
it("aplica template no checklist de forma idempotente", () => {
|
||||||
|
const now = 123
|
||||||
|
const template = {
|
||||||
|
_id: "tpl_1" as Id<"ticketChecklistTemplates">,
|
||||||
|
items: [
|
||||||
|
{ id: "i1", text: "Validar backup", required: true },
|
||||||
|
{ id: "i2", text: "Reiniciar serviço" }, // required default true
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
const generatedIds = ["c1", "c2"]
|
||||||
|
let idx = 0
|
||||||
|
const first = applyChecklistTemplateToItems([], template, {
|
||||||
|
now,
|
||||||
|
actorId: "user_1" as Id<"users">,
|
||||||
|
generateId: () => generatedIds[idx++]!,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(first.added).toBe(2)
|
||||||
|
expect(first.checklist).toHaveLength(2)
|
||||||
|
expect(first.checklist[0]).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: "c1",
|
||||||
|
text: "Validar backup",
|
||||||
|
done: false,
|
||||||
|
required: true,
|
||||||
|
templateId: template._id,
|
||||||
|
templateItemId: "i1",
|
||||||
|
createdAt: now,
|
||||||
|
createdBy: "user_1",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(first.checklist[1]).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: "c2",
|
||||||
|
text: "Reiniciar serviço",
|
||||||
|
required: true,
|
||||||
|
templateItemId: "i2",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const second = applyChecklistTemplateToItems(first.checklist, template, {
|
||||||
|
now: now + 1,
|
||||||
|
actorId: "user_2" as Id<"users">,
|
||||||
|
generateId: () => "should_not_add",
|
||||||
|
})
|
||||||
|
expect(second.added).toBe(0)
|
||||||
|
expect(second.checklist).toHaveLength(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("bloqueia encerramento quando há item obrigatório pendente", () => {
|
||||||
|
expect(
|
||||||
|
checklistBlocksResolution([
|
||||||
|
{ id: "1", text: "Obrigatório", done: false, required: true },
|
||||||
|
])
|
||||||
|
).toBe(true)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
checklistBlocksResolution([
|
||||||
|
{ id: "1", text: "Opcional", done: false, required: false },
|
||||||
|
])
|
||||||
|
).toBe(false)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
checklistBlocksResolution([
|
||||||
|
{ id: "1", text: "Obrigatório", done: true, required: true },
|
||||||
|
])
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
|
@ -199,6 +199,38 @@ describe("convex.tickets.resolveTicketHandler", () => {
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it("impede encerrar ticket quando há checklist obrigatório pendente", async () => {
|
||||||
|
const ticketMain = buildTicket({
|
||||||
|
checklist: [{ id: "c1", text: "Validar backup", done: false, required: true }] as unknown as TicketDoc["checklist"],
|
||||||
|
})
|
||||||
|
|
||||||
|
const { ctx, patch } = createResolveCtx({
|
||||||
|
[String(ticketMain._id)]: ticketMain,
|
||||||
|
})
|
||||||
|
|
||||||
|
mockedRequireStaff.mockResolvedValue({
|
||||||
|
user: {
|
||||||
|
_id: "user_agent" as Id<"users">,
|
||||||
|
_creationTime: NOW - 5_000,
|
||||||
|
tenantId: "tenant-1",
|
||||||
|
name: "Agente",
|
||||||
|
email: "agente@example.com",
|
||||||
|
role: "ADMIN",
|
||||||
|
teams: [],
|
||||||
|
},
|
||||||
|
role: "ADMIN",
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
resolveTicketHandler(ctx, {
|
||||||
|
ticketId: ticketMain._id,
|
||||||
|
actorId: "user_agent" as Id<"users">,
|
||||||
|
})
|
||||||
|
).rejects.toThrow("checklist")
|
||||||
|
|
||||||
|
expect(patch).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("convex.tickets.reopenTicketHandler", () => {
|
describe("convex.tickets.reopenTicketHandler", () => {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue