@fayz-ai/plugin-automations 0.15.29 → 0.15.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,764 @@
1
+ import { useProviderTemplates, ProviderTemplateBadge, providerApprovalFor, getFayzAutomationsClient } from './chunk-63YAGMWV.js';
2
+ import * as React3 from 'react';
3
+ import React3__default from 'react';
4
+ import { Mail, MessageSquare, Smartphone, Zap, RotateCcw, Check, Clock, Monitor, RefreshCw, History, Send, AlertTriangle, CircleCheck, CircleSlash, ChevronRight } from 'lucide-react';
5
+ import { SubpageHeader, Card, Button, WhatsAppIcon, Badge, Switch, Hint, HeaderTabs, Input, Textarea, toast, PhoneField } from '@fayz-ai/ui';
6
+ import { useOrganizationStore, resolveFayzAgentConnection, adminNavigateTo, useAgentSurface, AskAIButton } from '@fayz-ai/admin';
7
+ import { usePluginRuntimeOptional, resolveMessage, renderMessageTemplate, loadEventRuns, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
8
+ export { resolveMessages } from '@fayz-ai/core';
9
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
10
+
11
+ var PREFLIGHT_FUNCTION = "tyxter-payment-preflight";
12
+ async function readReadiness() {
13
+ const supabase = getSupabaseClientOptional();
14
+ const tenantId = getActiveTenantId();
15
+ if (!supabase || !tenantId) return null;
16
+ const { data, error } = await supabase.functions.invoke(PREFLIGHT_FUNCTION, {
17
+ body: { action: "status", tenantId }
18
+ });
19
+ if (error) return null;
20
+ const payments = data?.payments;
21
+ return payments ?? null;
22
+ }
23
+ function canOfferPayment(readiness) {
24
+ return Boolean(readiness?.ready) && readiness?.mode !== null && readiness?.mode !== void 0;
25
+ }
26
+ function usePaymentReadiness() {
27
+ const [readiness, setReadiness] = React3.useState(null);
28
+ const [loading, setLoading] = React3.useState(true);
29
+ React3.useEffect(() => {
30
+ let cancelled = false;
31
+ void readReadiness().then((value) => {
32
+ if (!cancelled) setReadiness(value);
33
+ }).catch(() => {
34
+ }).finally(() => {
35
+ if (!cancelled) setLoading(false);
36
+ });
37
+ return () => {
38
+ cancelled = true;
39
+ };
40
+ }, []);
41
+ return { readiness, loading };
42
+ }
43
+ var SEND_FUNCTION = "messaging-send";
44
+ function readFunctionError(error, data) {
45
+ const payload = data ?? null;
46
+ if (payload?.error) return { ok: false, error: payload.error, message: payload.message };
47
+ const context = error?.context;
48
+ if (context?.error) return { ok: false, error: context.error, message: context.message };
49
+ return { ok: false, error: "send_failed", message: error instanceof Error ? error.message : void 0 };
50
+ }
51
+ async function sendTestMessage(input) {
52
+ const supabase = getSupabaseClientOptional();
53
+ const tenantId = getActiveTenantId();
54
+ if (!supabase || !tenantId) return { ok: false, error: "not_available" };
55
+ const { data, error } = await supabase.functions.invoke(SEND_FUNCTION, {
56
+ body: {
57
+ test: true,
58
+ tenantId,
59
+ channel: input.channel,
60
+ eventKey: input.eventKey,
61
+ to: input.to,
62
+ variables: input.variables,
63
+ subject: { type: "test", id: crypto.randomUUID() },
64
+ ...input.template ? { template: input.template } : {}
65
+ }
66
+ });
67
+ if (error || data?.error) return readFunctionError(error, data);
68
+ return { ok: true };
69
+ }
70
+ function useOrganizationStoreLike() {
71
+ return useOrganizationStore((s) => s.currentOrg?.id);
72
+ }
73
+ var STATUS = {
74
+ sent: { label: "Enviado", hint: "A mensagem saiu.", variant: "success", Icon: CircleCheck },
75
+ recorded: {
76
+ label: "Disparou",
77
+ // Today's honest state: the trigger works, the send doesn't exist yet.
78
+ hint: "O gatilho disparou e ficou registrado. O envio autom\xE1tico ainda n\xE3o est\xE1 ligado neste ambiente.",
79
+ variant: "info",
80
+ Icon: History
81
+ },
82
+ skipped: { label: "Ignorado", hint: "O gatilho disparou, mas nada foi enviado \u2014 automa\xE7\xE3o desligada ou sem canal.", variant: "warning", Icon: CircleSlash },
83
+ failed: { label: "Falhou", hint: "A tentativa de envio quebrou. O erro est\xE1 na linha.", variant: "destructive", Icon: AlertTriangle }
84
+ };
85
+ function when(iso) {
86
+ const then = new Date(iso).getTime();
87
+ const diff = Date.now() - then;
88
+ const min = Math.round(diff / 6e4);
89
+ if (min < 1) return "agora";
90
+ if (min < 60) return `h\xE1 ${min} min`;
91
+ const h = Math.round(min / 60);
92
+ if (h < 24) return `h\xE1 ${h} h`;
93
+ return new Date(iso).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
94
+ }
95
+ function RunRow({ run }) {
96
+ const [open, setOpen] = React3__default.useState(false);
97
+ const cfg = STATUS[run.status] ?? STATUS.recorded;
98
+ const { Icon } = cfg;
99
+ return /* @__PURE__ */ jsxs("div", { className: "border-b border-border last:border-b-0", children: [
100
+ /* @__PURE__ */ jsxs(
101
+ Button,
102
+ {
103
+ variant: "bare",
104
+ size: "bare",
105
+ type: "button",
106
+ onClick: () => setOpen(!open),
107
+ className: "flex w-full items-center justify-start gap-3 rounded-none px-4 py-2.5 text-left font-normal transition-colors hover:bg-muted/40",
108
+ children: [
109
+ /* @__PURE__ */ jsx(ChevronRight, { className: `h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${open ? "rotate-90" : ""}` }),
110
+ /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
111
+ /* @__PURE__ */ jsx(Badge, { variant: cfg.variant, children: cfg.label }),
112
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-sm text-muted-foreground", children: typeof run.payload.record_name === "string" ? run.payload.record_name : typeof run.payload.customer_name === "string" ? run.payload.customer_name : typeof run.payload.contact_name === "string" ? run.payload.contact_name : run.subjectId ?? "\u2014" }),
113
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: when(run.occurredAt) })
114
+ ]
115
+ }
116
+ ),
117
+ open && /* @__PURE__ */ jsxs("div", { className: "space-y-3 bg-muted/20 px-4 pb-4 pt-1", children: [
118
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: cfg.hint }),
119
+ /* @__PURE__ */ jsxs("div", { children: [
120
+ /* @__PURE__ */ jsx("p", { className: "mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", children: "Dados do disparo" }),
121
+ /* @__PURE__ */ jsx("pre", { className: "overflow-x-auto rounded-md border border-border bg-card p-3 font-mono text-[11px] leading-relaxed", children: JSON.stringify(run.payload, null, 2) })
122
+ ] }),
123
+ run.result && /* @__PURE__ */ jsxs("div", { children: [
124
+ /* @__PURE__ */ jsx("p", { className: "mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", children: "Resultado" }),
125
+ /* @__PURE__ */ jsx("pre", { className: "overflow-x-auto rounded-md border border-border bg-card p-3 font-mono text-[11px] leading-relaxed", children: JSON.stringify(run.result, null, 2) })
126
+ ] }),
127
+ run.error && /* @__PURE__ */ jsx("p", { className: "rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 font-mono text-[11px] text-destructive", children: run.error })
128
+ ] })
129
+ ] });
130
+ }
131
+ function RunLog({ eventKey, tenantId, enabled }) {
132
+ const [runs, setRuns] = React3__default.useState(null);
133
+ const [loading, setLoading] = React3__default.useState(false);
134
+ const load = React3__default.useCallback(async () => {
135
+ setLoading(true);
136
+ setRuns(await loadEventRuns(eventKey, { tenantId, limit: 20 }));
137
+ setLoading(false);
138
+ }, [eventKey, tenantId]);
139
+ React3__default.useEffect(() => {
140
+ void load();
141
+ }, [load]);
142
+ return /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
143
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
144
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
145
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Execu\xE7\xF5es recentes" }),
146
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Cada vez que este gatilho disparou nesta conta." })
147
+ ] }),
148
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => void load(), disabled: loading, children: /* @__PURE__ */ jsx(RefreshCw, { className: `h-3.5 w-3.5 ${loading ? "animate-spin" : ""}` }) })
149
+ ] }),
150
+ runs === null ? /* @__PURE__ */ jsx("div", { className: "space-y-2 p-4", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-8 animate-pulse rounded bg-muted/40" }, i)) }) : runs.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 px-4 py-10 text-center", children: [
151
+ /* @__PURE__ */ jsx(History, { className: "h-7 w-7 text-muted-foreground/40", strokeWidth: 1.5 }),
152
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Nenhum disparo ainda" }),
153
+ /* @__PURE__ */ jsx("p", { className: "max-w-sm text-xs text-muted-foreground", children: enabled ? "Assim que este evento acontecer, ele aparece aqui \u2014 mesmo antes de existir envio." : "A automa\xE7\xE3o est\xE1 desligada. O gatilho continua sendo registrado aqui quando o evento acontecer." })
154
+ ] }) : /* @__PURE__ */ jsx("div", { children: runs.map((run) => /* @__PURE__ */ jsx(RunRow, { run }, run.id)) })
155
+ ] });
156
+ }
157
+ var EXEC_STATUS = {
158
+ success: { label: "Executada", variant: "success", Icon: CircleCheck },
159
+ error: { label: "Falhou", variant: "destructive", Icon: AlertTriangle }
160
+ };
161
+ function ExecutionRow({ execution }) {
162
+ const cfg = EXEC_STATUS[execution.status] ?? { label: execution.status, variant: "info", Icon: History };
163
+ const { Icon } = cfg;
164
+ return /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-4 py-2.5 last:border-b-0", children: [
165
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
166
+ /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
167
+ /* @__PURE__ */ jsx(Badge, { variant: cfg.variant, children: cfg.label }),
168
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-sm text-muted-foreground", children: execution.automationName }),
169
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: when(execution.executedAt) })
170
+ ] }),
171
+ execution.error && /* @__PURE__ */ jsx("p", { className: "ml-6 mt-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 font-mono text-[11px] text-destructive", children: execution.error })
172
+ ] });
173
+ }
174
+ function FayzRunLog({ connection, eventKey, tenantId, enabled }) {
175
+ const [executions, setExecutions] = React3__default.useState(null);
176
+ const [loading, setLoading] = React3__default.useState(false);
177
+ const load = React3__default.useCallback(async () => {
178
+ if (!tenantId) return;
179
+ setLoading(true);
180
+ try {
181
+ setExecutions(await getFayzAutomationsClient(connection).listExecutions({ tenantId, eventKey, limit: 20 }));
182
+ } catch (err) {
183
+ console.warn("[automations] could not load platform executions", err);
184
+ setExecutions([]);
185
+ } finally {
186
+ setLoading(false);
187
+ }
188
+ }, [connection, eventKey, tenantId]);
189
+ React3__default.useEffect(() => {
190
+ void load();
191
+ }, [load]);
192
+ return /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
193
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
194
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
195
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Execu\xE7\xF5es recentes" }),
196
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "O que a plataforma Fayz executou para este gatilho nesta conta." })
197
+ ] }),
198
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => void load(), disabled: loading, children: /* @__PURE__ */ jsx(RefreshCw, { className: `h-3.5 w-3.5 ${loading ? "animate-spin" : ""}` }) })
199
+ ] }),
200
+ executions === null ? /* @__PURE__ */ jsx("div", { className: "space-y-2 p-4", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-8 animate-pulse rounded bg-muted/40" }, i)) }) : executions.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 px-4 py-10 text-center", children: [
201
+ /* @__PURE__ */ jsx(History, { className: "h-7 w-7 text-muted-foreground/40", strokeWidth: 1.5 }),
202
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Nenhuma execu\xE7\xE3o ainda" }),
203
+ /* @__PURE__ */ jsx("p", { className: "max-w-sm text-xs text-muted-foreground", children: enabled ? "Assim que este evento acontecer, a plataforma executa a automa\xE7\xE3o e o resultado aparece aqui." : "A automa\xE7\xE3o est\xE1 desligada \u2014 a plataforma n\xE3o executa nada para este gatilho." })
204
+ ] }) : /* @__PURE__ */ jsx("div", { children: executions.map((e) => /* @__PURE__ */ jsx(ExecutionRow, { execution: e }, e.id)) })
205
+ ] });
206
+ }
207
+
208
+ // src/views/whatsapp-preview-bg.ts
209
+ var WHATSAPP_PREVIEW_BG = "https://assets.fayz.ai/connectors/whatsapp-background.jpg";
210
+ var ACTION_CATALOG = [
211
+ { id: "confirm", label: "Confirma", kind: "reply", hint: "O cliente confirma o hor\xE1rio no toque." },
212
+ { id: "cancel", label: "Cancela", kind: "reply", hint: "O cliente desmarca sem precisar ligar." },
213
+ { id: "pay", label: "Pagar", kind: "payment", hint: "O cliente recebe o Pix na conversa." }
214
+ ];
215
+ function nextActions(current, id, on) {
216
+ const kept = new Set(current.filter((a) => a.id !== id).map((a) => a.id));
217
+ if (on) kept.add(id);
218
+ const labels = new Map(current.map((a) => [a.id, a.label]));
219
+ return ACTION_CATALOG.filter((a) => kept.has(a.id)).map((a) => ({ id: a.id, label: labels.get(a.id) ?? a.label, kind: a.kind }));
220
+ }
221
+ var TEST_ERROR = {
222
+ template_not_approved: "O modelo ainda n\xE3o foi aprovado pela Meta \u2014 sincronize os modelos e tente de novo.",
223
+ no_sender: "Este app ainda n\xE3o tem um n\xFAmero de WhatsApp ativo. Veja Conversas \u2192 Tyxter.",
224
+ not_connected: "O WhatsApp ainda n\xE3o est\xE1 conectado neste app. Veja Conversas \u2192 Tyxter.",
225
+ contact_opted_out: "Este contato pediu para n\xE3o receber mensagens.",
226
+ invalid_recipient: "Esse destino n\xE3o parece v\xE1lido.",
227
+ not_a_member: "A sua sess\xE3o n\xE3o pertence a este neg\xF3cio.",
228
+ not_available: "O envio de teste n\xE3o est\xE1 dispon\xEDvel neste ambiente.",
229
+ email_not_configured: "O envio de e-mail n\xE3o est\xE1 configurado neste app.",
230
+ template_not_found: "Escreva a mensagem antes de testar.",
231
+ email_rejected: "O provedor de e-mail recusou a mensagem.",
232
+ email_credential_rejected: "A chave de e-mail do app foi recusada pelo provedor.",
233
+ email_rate_limited: "O provedor pediu uma pausa \u2014 tente de novo em instantes."
234
+ };
235
+ function TestSendStrip({ eventKey, channel, placeholders, template }) {
236
+ const isEmail = channel === "email";
237
+ const [recipient, setRecipient] = React3__default.useState("");
238
+ const [sending, setSending] = React3__default.useState(false);
239
+ const valid = isEmail ? /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(recipient.trim()) : recipient.replace(/\D/g, "").length >= 10;
240
+ const send = async () => {
241
+ setSending(true);
242
+ try {
243
+ const variables = Object.fromEntries(placeholders.map((p) => {
244
+ const key = p.replace(/[{}]/g, "").trim();
245
+ return [key, SAMPLE[key] ?? key];
246
+ }));
247
+ const result = await sendTestMessage({ eventKey, channel, to: recipient.trim(), variables, template });
248
+ if (result.ok) {
249
+ toast.success(isEmail ? "Teste enviado \u2014 confira a caixa de entrada desse e-mail" : "Teste enviado \u2014 confira o WhatsApp desse n\xFAmero");
250
+ } else {
251
+ toast.error(TEST_ERROR[result.error ?? ""] ?? result.message ?? "N\xE3o foi poss\xEDvel enviar o teste");
252
+ }
253
+ } finally {
254
+ setSending(false);
255
+ }
256
+ };
257
+ return (
258
+ // Sem moldura própria: o strip vive dentro do Card da aba Testar, e uma
259
+ // borda aqui era o anel duplicado de sempre.
260
+ /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-end gap-2", children: [
261
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
262
+ /* @__PURE__ */ jsx("label", { className: "mb-1 block text-xs font-medium text-muted-foreground", children: isEmail ? "E-mail que recebe o teste" : "N\xFAmero que recebe o teste" }),
263
+ isEmail ? /* @__PURE__ */ jsx(
264
+ Input,
265
+ {
266
+ type: "email",
267
+ value: recipient,
268
+ onChange: (e) => setRecipient(e.target.value),
269
+ placeholder: "voce@exemplo.com",
270
+ disabled: sending,
271
+ "aria-label": "E-mail que recebe o teste"
272
+ }
273
+ ) : /* @__PURE__ */ jsx(
274
+ PhoneField,
275
+ {
276
+ value: recipient,
277
+ onChange: setRecipient,
278
+ placeholder: "(21) 99999-9999",
279
+ disabled: sending,
280
+ "aria-label": "N\xFAmero que recebe o teste"
281
+ }
282
+ )
283
+ ] }),
284
+ /* @__PURE__ */ jsxs(Button, { variant: "outline", onClick: () => void send(), disabled: !valid || sending, children: [
285
+ /* @__PURE__ */ jsx(Send, { className: "mr-2 h-3.5 w-3.5" }),
286
+ sending ? "Enviando\u2026" : "Enviar teste"
287
+ ] })
288
+ ] })
289
+ );
290
+ }
291
+ var TABS = [
292
+ { value: "preview", label: "Pr\xE9via" },
293
+ { value: "code", label: "C\xF3digo" },
294
+ // O que já aconteceu. Fica ao lado do texto, e não numa tela à parte, porque
295
+ // é a mesma pergunta em dois tempos: o que vai sair, e o que saiu.
296
+ { value: "runs", label: "Execu\xE7\xF5es" }
297
+ ];
298
+ var TEST_TAB = { value: "test", label: "Testar" };
299
+ var CHANNEL_LABEL = {
300
+ email: "E-mail",
301
+ whatsapp: "WhatsApp",
302
+ sms: "SMS",
303
+ push: "Push",
304
+ webchat: "Chat"
305
+ };
306
+ var CHANNEL_ICON = {
307
+ email: Mail,
308
+ whatsapp: WhatsAppIcon,
309
+ sms: Smartphone,
310
+ push: MessageSquare,
311
+ webchat: MessageSquare
312
+ };
313
+ var WRITE_MESSAGE_TOOL = {
314
+ id: "automations.writeMessage",
315
+ name: "writeAutomationMessage",
316
+ description: "Writes the subject and body of the automation message the user has open, into the editor (it does NOT save \u2014 the user does). Use ONLY the placeholders listed in the surface state, spelled exactly, including the braces: an invented one renders as literal text in a message a customer reads. Match the channel: e-mail takes a subject and paragraphs; WhatsApp and SMS take no subject and few lines.",
317
+ icon: "MessageSquare",
318
+ mode: "read",
319
+ execution: { plane: "client" },
320
+ category: "Automations",
321
+ parameters: {
322
+ type: "object",
323
+ properties: {
324
+ subject: { type: "string", description: "Subject line. Leave empty for channels that have none." },
325
+ body: { type: "string", description: "Message body, with placeholders where they belong." }
326
+ },
327
+ required: ["body"]
328
+ }
329
+ };
330
+ var SAMPLE = {
331
+ store_name: "Sua Loja",
332
+ company_name: "Sua Empresa",
333
+ customer_name: "Maria Silva",
334
+ contact_name: "Maria Silva",
335
+ lead_name: "Maria Silva",
336
+ order_number: "1042",
337
+ order_total: "R$ 189,90",
338
+ order_items: "1 \xD7 Camiseta Cl\xE1ssica \u2014 R$ 89,90\n2 \xD7 Caneca Esmaltada \u2014 R$ 100,00",
339
+ tracking_code: "BR123456789BR",
340
+ cart_url: "https://sualoja.com.br/carrinho",
341
+ deal_name: "Proposta \u2014 Reforma da fachada",
342
+ deal_value: "R$ 12.400,00",
343
+ stage_name: "Negocia\xE7\xE3o",
344
+ owner_name: "Jo\xE3o Pereira",
345
+ appointment_date: "12/08/2026",
346
+ appointment_time: "14:30"
347
+ };
348
+ function AutomationDetailPage({ eventKey, channel, store, backTo = "/automations", embedded, onDone }) {
349
+ const tenantId = useOrganizationStoreLike();
350
+ const runtime = usePluginRuntimeOptional();
351
+ const fayzConnection = React3__default.useMemo(() => resolveFayzAgentConnection(), []);
352
+ const [message, setMessage] = React3__default.useState(void 0);
353
+ const [tab, setTab] = React3__default.useState("preview");
354
+ const [device, setDevice] = React3__default.useState("desktop");
355
+ const [draft, setDraft] = React3__default.useState(null);
356
+ const [labelDrafts, setLabelDrafts] = React3__default.useState({});
357
+ const [saving, setSaving] = React3__default.useState(false);
358
+ const providerTemplates = useProviderTemplates();
359
+ const { readiness, loading: readinessLoading } = usePaymentReadiness();
360
+ const back = React3__default.useCallback(
361
+ () => onDone ? onDone() : adminNavigateTo(backTo),
362
+ [onDone, backTo]
363
+ );
364
+ const surfaceRef = React3__default.useRef({ message, draft });
365
+ surfaceRef.current = { message, draft };
366
+ const agentSurface = React3__default.useMemo(() => ({
367
+ id: "automations.message",
368
+ pluginId: "automations",
369
+ instructions: "The user is editing one automation message. `placeholders` in the surface state are the ONLY variables that resolve \u2014 copy them verbatim, braces included. Call writeAutomationMessage once with the whole text; the editor fills and the user reviews before saving.",
370
+ describe: () => {
371
+ const o = surfaceRef.current;
372
+ if (!o.message) return { title: "Automa\xE7\xE3o" };
373
+ const current2 = o.draft ?? { subject: o.message.subject, body: o.message.body };
374
+ return {
375
+ title: `Automa\xE7\xE3o \u2014 ${o.message.event?.title ?? o.message.event?.name ?? ""}`,
376
+ state: {
377
+ event: o.message.event?.name ?? null,
378
+ channel: o.message.channel,
379
+ hasSubject: o.message.channel === "email",
380
+ placeholders: Object.keys(SAMPLE).map((key) => `{{${key}}}`),
381
+ currentSubject: current2.subject,
382
+ currentBody: current2.body
383
+ }
384
+ };
385
+ },
386
+ tools: [{
387
+ tool: WRITE_MESSAGE_TOOL,
388
+ execute: (args) => {
389
+ const o = surfaceRef.current;
390
+ if (!o.message) return { ok: false, error: "no_message_open" };
391
+ const current2 = o.draft ?? { subject: o.message.subject, body: o.message.body };
392
+ const body = String(args.body ?? "").trim();
393
+ if (!body) return { ok: false, error: "empty_body" };
394
+ const subject = args.subject === void 0 ? current2.subject : String(args.subject);
395
+ setDraft({ subject, body });
396
+ setTab("code");
397
+ return { ok: true, filled: true, saved: false, note: "Draft filled \u2014 the user still has to press Save." };
398
+ }
399
+ }]
400
+ }), []);
401
+ useAgentSurface(agentSurface);
402
+ const reload = React3__default.useCallback(async () => {
403
+ if (!eventKey || !channel) {
404
+ setMessage(null);
405
+ return;
406
+ }
407
+ let overrides = [];
408
+ try {
409
+ overrides = await store.list(tenantId);
410
+ } catch (err) {
411
+ console.warn("[automations] could not load overrides; showing defaults", err);
412
+ }
413
+ const found = resolveMessage(decodeURIComponent(eventKey), channel, overrides, runtime?.events ?? []);
414
+ setMessage(found);
415
+ if (found) setDraft({ subject: found.subject, body: found.body });
416
+ }, [eventKey, channel, store, tenantId, runtime]);
417
+ React3__default.useEffect(() => {
418
+ void reload();
419
+ }, [reload]);
420
+ const header = embedded ? null : /* @__PURE__ */ jsx(
421
+ SubpageHeader,
422
+ {
423
+ title: message === void 0 ? "" : message?.override?.name ?? message?.event.title ?? message?.event.name ?? "Automa\xE7\xE3o",
424
+ parentLabel: "Automa\xE7\xF5es",
425
+ onBack: back
426
+ }
427
+ );
428
+ if (message === void 0) {
429
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
430
+ header,
431
+ /* @__PURE__ */ jsx("div", { className: "h-8 w-64 animate-pulse rounded bg-muted" }),
432
+ /* @__PURE__ */ jsx(Card, { className: "h-96 animate-pulse" })
433
+ ] });
434
+ }
435
+ if (!message) {
436
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
437
+ header,
438
+ /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-2 p-12 text-center", children: [
439
+ /* @__PURE__ */ jsx(Mail, { className: "h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
440
+ /* @__PURE__ */ jsx("p", { className: "font-semibold", children: "Automa\xE7\xE3o n\xE3o encontrada" }),
441
+ /* @__PURE__ */ jsxs("p", { className: "max-w-sm text-sm text-muted-foreground", children: [
442
+ "O evento ",
443
+ /* @__PURE__ */ jsx("code", { className: "font-mono", children: eventKey }),
444
+ " n\xE3o est\xE1 no cat\xE1logo \u2014 o m\xF3dulo que o registra pode n\xE3o estar instalado nesta conta."
445
+ ] }),
446
+ /* @__PURE__ */ jsx(Button, { variant: "outline", className: "mt-2", onClick: back, children: "Voltar para Automa\xE7\xF5es" })
447
+ ] })
448
+ ] });
449
+ }
450
+ const event = message.event;
451
+ const fallback = { subject: message.override ? void 0 : message.subject, body: message.body };
452
+ const ChannelIcon = CHANNEL_ICON[message.channel] ?? Zap;
453
+ const isWhatsapp = message.channel === "whatsapp";
454
+ const current = draft ?? { subject: message.subject, body: message.body };
455
+ const dirty = current.subject !== message.subject || current.body !== message.body;
456
+ const hasSubject = message.channel === "email";
457
+ const patch = async (input) => {
458
+ setSaving(true);
459
+ try {
460
+ await store.upsert(input, tenantId);
461
+ await reload();
462
+ } catch (err) {
463
+ console.warn("[automations] save failed", err);
464
+ toast.error("N\xE3o foi poss\xEDvel salvar");
465
+ } finally {
466
+ setSaving(false);
467
+ }
468
+ };
469
+ const save = () => void patch({
470
+ eventKey: event.name,
471
+ channel: message.channel,
472
+ // Igual ao padrão volta a ser "sem personalização", não uma cópia.
473
+ subject: current.subject.trim() === (fallback?.subject ?? "") ? null : current.subject.trim() || null,
474
+ body: current.body.trim() === fallback?.body ? null : current.body.trim() || null
475
+ });
476
+ const reset = async () => {
477
+ setDraft({ subject: fallback?.subject ?? "", body: fallback?.body ?? "" });
478
+ setSaving(true);
479
+ try {
480
+ await store.reset(event.name, message.channel, tenantId);
481
+ await reload();
482
+ toast.success("Texto restaurado");
483
+ } catch (err) {
484
+ console.warn("[automations] reset failed", err);
485
+ toast.error("N\xE3o foi poss\xEDvel restaurar");
486
+ } finally {
487
+ setSaving(false);
488
+ }
489
+ };
490
+ const previewSubject = renderMessageTemplate(current.subject, SAMPLE);
491
+ const previewBody = renderMessageTemplate(current.body, SAMPLE);
492
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
493
+ header,
494
+ /* @__PURE__ */ jsxs("div", { className: embedded ? "space-y-3" : "flex flex-wrap items-start gap-3", children: [
495
+ /* @__PURE__ */ jsxs("div", { className: embedded ? "flex items-start gap-3" : "contents", children: [
496
+ /* @__PURE__ */ jsx(
497
+ "span",
498
+ {
499
+ className: `flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border ${isWhatsapp ? "border-[#25D366]/30 bg-[#25D366]/10 text-[#1faf55]" : "border-border text-muted-foreground"}`,
500
+ children: /* @__PURE__ */ jsx(ChannelIcon, { className: "h-4 w-4" })
501
+ }
502
+ ),
503
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
504
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
505
+ /* @__PURE__ */ jsx(Badge, { variant: "outline", children: CHANNEL_LABEL[message.channel] }),
506
+ /* @__PURE__ */ jsx(Badge, { variant: "outline", children: message.kind === "marketing" ? "Marketing" : "Transacional" }),
507
+ message.customized && /* @__PURE__ */ jsx(Badge, { variant: "info", children: "Personalizado" })
508
+ ] }),
509
+ /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm text-muted-foreground", children: event.description }),
510
+ /* @__PURE__ */ jsx("div", { className: "mt-1.5", children: /* @__PURE__ */ jsx(
511
+ ProviderTemplateBadge,
512
+ {
513
+ approval: providerApprovalFor(providerTemplates, event.name, message.channel),
514
+ showDetail: true
515
+ }
516
+ ) })
517
+ ] })
518
+ ] }),
519
+ /* @__PURE__ */ jsxs("div", { className: embedded ? "flex items-center gap-2" : "flex shrink-0 flex-wrap items-center gap-2", children: [
520
+ /* @__PURE__ */ jsx(
521
+ Switch,
522
+ {
523
+ size: "md",
524
+ checked: message.enabled,
525
+ onCheckedChange: (next) => void patch({ eventKey: event.name, channel: message.channel, enabled: next }),
526
+ disabled: saving,
527
+ label: message.enabled ? "Ativa" : "Inativa"
528
+ }
529
+ ),
530
+ /* @__PURE__ */ jsxs("div", { className: embedded ? "ml-auto flex items-center gap-2" : "contents", children: [
531
+ /* @__PURE__ */ jsx(Hint, { label: "Descarta o texto personalizado e volta ao padr\xE3o do produto.", children: /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsxs(
532
+ Button,
533
+ {
534
+ variant: embedded ? "ghost" : "outline",
535
+ size: embedded ? "icon" : void 0,
536
+ onClick: () => void reset(),
537
+ disabled: !message.customized || saving,
538
+ "aria-label": embedded ? "Restaurar padr\xE3o" : void 0,
539
+ children: [
540
+ /* @__PURE__ */ jsx(RotateCcw, { className: embedded ? "h-4 w-4" : "mr-2 h-4 w-4" }),
541
+ !embedded && "Restaurar padr\xE3o"
542
+ ]
543
+ }
544
+ ) }) }),
545
+ /* @__PURE__ */ jsx(
546
+ AskAIButton,
547
+ {
548
+ variant: embedded ? "ghost" : "outline",
549
+ label: embedded ? "" : void 0,
550
+ hint: "Descreva o tom da mensagem\u2026",
551
+ intro: {
552
+ role: "setup",
553
+ persona: "Redator das automa\xE7\xF5es",
554
+ pitch: "Diga como esta mensagem deve soar.",
555
+ description: "Escrevo o assunto e o corpo desta automa\xE7\xE3o usando as vari\xE1veis que ela tem \xE0 disposi\xE7\xE3o. O texto cai no editor ao lado para voc\xEA revisar \u2014 nada \xE9 salvo sem voc\xEA.",
556
+ suggestions: [
557
+ { label: "Mais curta e direta" },
558
+ { label: "Mais calorosa, com o nome do cliente" },
559
+ { label: "Formal, para um p\xFAblico corporativo" }
560
+ ]
561
+ }
562
+ }
563
+ ),
564
+ dirty || saving ? /* @__PURE__ */ jsx(Button, { onClick: save, disabled: saving, children: saving ? "Salvando\u2026" : "Salvar" }) : /* @__PURE__ */ jsxs("span", { className: "inline-flex h-9 items-center gap-1 px-2 text-xs font-medium text-muted-foreground", children: [
565
+ /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }),
566
+ "Salvo"
567
+ ] })
568
+ ] })
569
+ ] })
570
+ ] }),
571
+ /* @__PURE__ */ jsx(
572
+ HeaderTabs,
573
+ {
574
+ tabs: isWhatsapp || message.channel === "email" ? [...TABS, TEST_TAB] : TABS,
575
+ value: tab,
576
+ onChange: setTab,
577
+ "aria-label": "Visualiza\xE7\xE3o"
578
+ }
579
+ ),
580
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-border pb-4 text-xs text-muted-foreground", children: [
581
+ /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
582
+ /* @__PURE__ */ jsx(Zap, { className: "h-3.5 w-3.5" }),
583
+ "Gatilho:",
584
+ /* @__PURE__ */ jsx("code", { className: "rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-foreground", children: event.name })
585
+ ] }),
586
+ /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
587
+ /* @__PURE__ */ jsx(Clock, { className: "h-3.5 w-3.5" }),
588
+ event.trigger
589
+ ] }),
590
+ hasSubject && current.subject && /* @__PURE__ */ jsxs("span", { className: "min-w-0 truncate", children: [
591
+ "Assunto: ",
592
+ current.subject
593
+ ] })
594
+ ] }),
595
+ tab === "runs" ? (
596
+ // Atrás de um projeto Fayz o histórico verdadeiro é o da plataforma —
597
+ // é ela quem executa. Fora dele, o coletor local continua valendo.
598
+ fayzConnection ? /* @__PURE__ */ jsx(FayzRunLog, { connection: fayzConnection, eventKey: event.name, tenantId, enabled: message.enabled }) : /* @__PURE__ */ jsx(RunLog, { eventKey: event.name, tenantId, enabled: message.enabled })
599
+ ) : tab === "preview" ? /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
600
+ !embedded && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
601
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Pr\xE9via" }),
602
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: ["desktop", "mobile"].map((d) => /* @__PURE__ */ jsx(
603
+ Button,
604
+ {
605
+ variant: "bare",
606
+ size: "bare",
607
+ type: "button",
608
+ onClick: () => setDevice(d),
609
+ "aria-label": d === "desktop" ? "Computador" : "Celular",
610
+ className: `flex h-7 w-7 items-center justify-center rounded-md transition-colors ${device === d ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted/60"}`,
611
+ children: d === "desktop" ? /* @__PURE__ */ jsx(Monitor, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Smartphone, { className: "h-4 w-4" })
612
+ },
613
+ d
614
+ )) })
615
+ ] }),
616
+ /* @__PURE__ */ jsxs("div", { className: embedded ? "bg-muted/30 p-4" : "bg-muted/30 p-6", children: [
617
+ /* @__PURE__ */ jsx(
618
+ "div",
619
+ {
620
+ className: `mx-auto overflow-hidden rounded-card bg-card shadow-sm transition-[max-width] ${device === "mobile" ? "max-w-[380px]" : hasSubject ? "max-w-[600px]" : "max-w-[420px]"}`,
621
+ children: hasSubject ? /* @__PURE__ */ jsxs(Fragment, { children: [
622
+ /* @__PURE__ */ jsxs("div", { "aria-hidden": true, className: "flex items-center gap-1.5 border-b border-border bg-muted/40 px-4 py-2.5", children: [
623
+ /* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#ff5f57]" }),
624
+ /* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#febc2e]" }),
625
+ /* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#28c840]" })
626
+ ] }),
627
+ /* @__PURE__ */ jsxs("div", { className: "px-6 pb-4 pt-5", children: [
628
+ /* @__PURE__ */ jsx("p", { className: "text-base font-semibold leading-snug", children: previewSubject }),
629
+ /* @__PURE__ */ jsxs("div", { className: "mt-4 flex items-center gap-3", children: [
630
+ /* @__PURE__ */ jsx("span", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary", children: (SAMPLE.store_name ?? "S").charAt(0) }),
631
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
632
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: SAMPLE.store_name }),
633
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "para mim" })
634
+ ] }),
635
+ /* @__PURE__ */ jsx("span", { className: "ml-auto shrink-0 text-xs text-muted-foreground", children: "09:41" })
636
+ ] })
637
+ ] }),
638
+ /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap border-t border-border px-6 py-5 text-sm leading-relaxed", children: previewBody })
639
+ ] }) : /* @__PURE__ */ jsxs(
640
+ "div",
641
+ {
642
+ className: "p-4",
643
+ style: isWhatsapp ? { backgroundImage: `url(${WHATSAPP_PREVIEW_BG})`, backgroundSize: "cover", backgroundPosition: "center" } : void 0,
644
+ children: [
645
+ /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap rounded-2xl rounded-tl-sm bg-[#dcf8c6] px-3 py-2 text-sm leading-relaxed text-[#111b21] shadow-sm", children: previewBody }),
646
+ message.actions.length > 0 && /* @__PURE__ */ jsx("div", { className: "mt-1 space-y-1", children: message.actions.map((action) => /* @__PURE__ */ jsx(
647
+ "div",
648
+ {
649
+ className: "rounded-lg bg-white px-3 py-1.5 text-center text-sm font-medium text-[#1e7fd6] shadow-sm",
650
+ children: action.label
651
+ },
652
+ action.id
653
+ )) })
654
+ ]
655
+ }
656
+ )
657
+ }
658
+ ),
659
+ /* @__PURE__ */ jsx("p", { className: "mt-4 text-center text-xs text-muted-foreground", children: "Dados de exemplo \u2014 nenhum registro real foi usado." })
660
+ ] })
661
+ ] }) : tab === "test" ? /* @__PURE__ */ jsxs(Card, { className: "p-4", children: [
662
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: isWhatsapp ? "Envio real, pelo mesmo caminho da automa\xE7\xE3o \u2014 modelo aprovado, n\xFAmero ativo e entrega de verdade, com os dados de exemplo." : "Envio real, pelo mesmo caminho da automa\xE7\xE3o \u2014 vai o texto que est\xE1 na tela, salvo ou n\xE3o, com os dados de exemplo." }),
663
+ /* @__PURE__ */ jsx(
664
+ TestSendStrip,
665
+ {
666
+ eventKey: event.name,
667
+ channel: message.channel,
668
+ placeholders: message.placeholders,
669
+ template: message.channel === "email" ? { subject: current.subject, body: current.body } : void 0
670
+ }
671
+ )
672
+ ] }) : /* @__PURE__ */ jsxs(Card, { className: "space-y-4 p-4", children: [
673
+ hasSubject && /* @__PURE__ */ jsxs("div", { children: [
674
+ /* @__PURE__ */ jsx("label", { className: "mb-1 block text-xs font-medium text-muted-foreground", children: "Assunto" }),
675
+ /* @__PURE__ */ jsx(
676
+ Input,
677
+ {
678
+ value: current.subject,
679
+ onChange: (e) => setDraft({ ...current, subject: e.target.value })
680
+ }
681
+ )
682
+ ] }),
683
+ /* @__PURE__ */ jsxs("div", { children: [
684
+ /* @__PURE__ */ jsx("label", { className: "mb-1 block text-xs font-medium text-muted-foreground", children: "Mensagem" }),
685
+ /* @__PURE__ */ jsx(
686
+ Textarea,
687
+ {
688
+ rows: 14,
689
+ value: current.body,
690
+ onChange: (e) => setDraft({ ...current, body: e.target.value }),
691
+ className: "font-mono text-xs leading-relaxed"
692
+ }
693
+ )
694
+ ] }),
695
+ message.channel === "whatsapp" && /* @__PURE__ */ jsxs("div", { children: [
696
+ /* @__PURE__ */ jsx("p", { className: "mb-1.5 text-xs font-medium text-muted-foreground", children: "Bot\xF5es \u2014 o cliente responde no toque, sem digitar" }),
697
+ /* @__PURE__ */ jsx("div", { className: "space-y-2", children: ACTION_CATALOG.map((action) => {
698
+ const active = message.actions.find((a) => a.id === action.id);
699
+ const on = Boolean(active);
700
+ const gated = action.id === "pay" && !canOfferPayment(readiness);
701
+ const blocked = gated && !readinessLoading;
702
+ const labelValue = labelDrafts[action.id] ?? active?.label ?? action.label;
703
+ const commitLabel = () => {
704
+ const next = labelValue.trim();
705
+ setLabelDrafts((d) => {
706
+ const { [action.id]: _, ...rest } = d;
707
+ return rest;
708
+ });
709
+ if (!active || !next || next === active.label) return;
710
+ void patch({
711
+ eventKey: event.name,
712
+ channel: message.channel,
713
+ actions: message.actions.map((a) => a.id === action.id ? { ...a, label: next } : a)
714
+ });
715
+ };
716
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1", children: [
717
+ /* @__PURE__ */ jsx(
718
+ Switch,
719
+ {
720
+ size: "md",
721
+ checked: on,
722
+ disabled: saving || gated,
723
+ onCheckedChange: (next) => void patch({
724
+ eventKey: event.name,
725
+ channel: message.channel,
726
+ actions: nextActions(message.actions, action.id, next)
727
+ }),
728
+ label: on ? "" : action.label
729
+ }
730
+ ),
731
+ on && // O texto do botão como a cliente vê. 25 caracteres é o
732
+ // teto da Meta para QUICK_REPLY; mudar o texto de um
733
+ // modelo já aprovado dispara nova aprovação — a
734
+ // pastilha de status acima conta essa história.
735
+ /* @__PURE__ */ jsx("div", { className: "w-36", children: /* @__PURE__ */ jsx(
736
+ Input,
737
+ {
738
+ value: labelValue,
739
+ maxLength: 25,
740
+ disabled: saving,
741
+ "aria-label": `Texto do bot\xE3o ${action.label}`,
742
+ onChange: (e) => setLabelDrafts((d) => ({ ...d, [action.id]: e.target.value })),
743
+ onBlur: commitLabel,
744
+ onKeyDown: (e) => {
745
+ if (e.key === "Enter") e.target.blur();
746
+ },
747
+ className: "h-auto px-2 py-1"
748
+ }
749
+ ) }),
750
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: blocked ? "Para cobrar por aqui, configure a conta de pagamento em Conversas \u2192 Tyxter." : action.hint })
751
+ ] }, action.id);
752
+ }) })
753
+ ] }),
754
+ /* @__PURE__ */ jsxs("div", { children: [
755
+ /* @__PURE__ */ jsx("p", { className: "mb-1.5 text-xs font-medium text-muted-foreground", children: "Campos deste evento \u2014 o envio substitui pelo dado real" }),
756
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: message.placeholders.map((p) => /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground", children: p }, p)) })
757
+ ] })
758
+ ] })
759
+ ] });
760
+ }
761
+
762
+ export { AutomationDetailPage, nextActions, useOrganizationStoreLike };
763
+ //# sourceMappingURL=chunk-TCSHZ3VF.js.map
764
+ //# sourceMappingURL=chunk-TCSHZ3VF.js.map