@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.
- package/dist/AutomationDetailPage-UHY7KHQK.js +4 -0
- package/dist/AutomationDetailPage-UHY7KHQK.js.map +1 -0
- package/dist/AutomationsList-3UTTQSIX.js +478 -0
- package/dist/AutomationsList-3UTTQSIX.js.map +1 -0
- package/dist/FlowsPage-6SUXT2LP.js +509 -0
- package/dist/FlowsPage-6SUXT2LP.js.map +1 -0
- package/dist/chunk-63YAGMWV.js +258 -0
- package/dist/chunk-63YAGMWV.js.map +1 -0
- package/dist/chunk-TCSHZ3VF.js +764 -0
- package/dist/chunk-TCSHZ3VF.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -2974
- package/dist/index.js.map +1 -1
- package/dist/migrations/main.browser.js +9 -0
- package/dist/migrations/main.browser.js.map +1 -0
- package/dist/migrations/main.js +998 -0
- package/dist/migrations/main.js.map +1 -0
- package/dist/views/AutomationsList.d.ts.map +1 -1
- package/package.json +10 -4
package/dist/index.js
CHANGED
|
@@ -1,1478 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import { toast, Card, PageHeaderActions, Button, Switch, DataTable, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, PageTabs, WhatsAppIcon, SubpageHeader, Badge, Hint, HeaderTabs, Textarea, PhoneField } from '@fayz-ai/ui';
|
|
8
|
-
import { createFayzAutomationsClient, FayzAutomationsError } from '@fayz-ai/sdk/automations';
|
|
9
|
-
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
1
|
+
import { createFayzTemplateStore } from './chunk-63YAGMWV.js';
|
|
2
|
+
export { PROVIDER_TEMPLATES_TABLE, createFayzTemplateStore, loadProviderTemplates, providerApprovalFor, providerTemplateFor } from './chunk-63YAGMWV.js';
|
|
3
|
+
import React from 'react';
|
|
4
|
+
import { lazyComponent, startEventLog, getSupabaseClientOptional, normalizeMessageActions } from '@fayz-ai/core';
|
|
5
|
+
import { resolveFayzAgentConnection, registerRailPage } from '@fayz-ai/admin';
|
|
6
|
+
import { MIGRATIONS } from '#migrations/main';
|
|
10
7
|
|
|
11
|
-
// src/index.ts
|
|
12
|
-
var PREFLIGHT_FUNCTION = "tyxter-payment-preflight";
|
|
13
|
-
async function readReadiness() {
|
|
14
|
-
const supabase = getSupabaseClientOptional();
|
|
15
|
-
const tenantId = getActiveTenantId();
|
|
16
|
-
if (!supabase || !tenantId) return null;
|
|
17
|
-
const { data, error } = await supabase.functions.invoke(PREFLIGHT_FUNCTION, {
|
|
18
|
-
body: { action: "status", tenantId }
|
|
19
|
-
});
|
|
20
|
-
if (error) return null;
|
|
21
|
-
const payments = data?.payments;
|
|
22
|
-
return payments ?? null;
|
|
23
|
-
}
|
|
24
|
-
function canOfferPayment(readiness) {
|
|
25
|
-
return Boolean(readiness?.ready) && readiness?.mode !== null && readiness?.mode !== void 0;
|
|
26
|
-
}
|
|
27
|
-
function usePaymentReadiness() {
|
|
28
|
-
const [readiness, setReadiness] = React4.useState(null);
|
|
29
|
-
const [loading, setLoading] = React4.useState(true);
|
|
30
|
-
React4.useEffect(() => {
|
|
31
|
-
let cancelled = false;
|
|
32
|
-
void readReadiness().then((value) => {
|
|
33
|
-
if (!cancelled) setReadiness(value);
|
|
34
|
-
}).catch(() => {
|
|
35
|
-
}).finally(() => {
|
|
36
|
-
if (!cancelled) setLoading(false);
|
|
37
|
-
});
|
|
38
|
-
return () => {
|
|
39
|
-
cancelled = true;
|
|
40
|
-
};
|
|
41
|
-
}, []);
|
|
42
|
-
return { readiness, loading };
|
|
43
|
-
}
|
|
44
|
-
var SEND_FUNCTION = "messaging-send";
|
|
45
|
-
function readFunctionError(error, data) {
|
|
46
|
-
const payload = data ?? null;
|
|
47
|
-
if (payload?.error) return { ok: false, error: payload.error, message: payload.message };
|
|
48
|
-
const context = error?.context;
|
|
49
|
-
if (context?.error) return { ok: false, error: context.error, message: context.message };
|
|
50
|
-
return { ok: false, error: "send_failed", message: error instanceof Error ? error.message : void 0 };
|
|
51
|
-
}
|
|
52
|
-
async function sendTestMessage(input) {
|
|
53
|
-
const supabase = getSupabaseClientOptional();
|
|
54
|
-
const tenantId = getActiveTenantId();
|
|
55
|
-
if (!supabase || !tenantId) return { ok: false, error: "not_available" };
|
|
56
|
-
const { data, error } = await supabase.functions.invoke(SEND_FUNCTION, {
|
|
57
|
-
body: {
|
|
58
|
-
test: true,
|
|
59
|
-
tenantId,
|
|
60
|
-
channel: input.channel,
|
|
61
|
-
eventKey: input.eventKey,
|
|
62
|
-
to: input.to,
|
|
63
|
-
variables: input.variables,
|
|
64
|
-
subject: { type: "test", id: crypto.randomUUID() },
|
|
65
|
-
...input.template ? { template: input.template } : {}
|
|
66
|
-
}
|
|
67
|
-
});
|
|
68
|
-
if (error || data?.error) return readFunctionError(error, data);
|
|
69
|
-
return { ok: true };
|
|
70
|
-
}
|
|
71
|
-
function useOrganizationStoreLike() {
|
|
72
|
-
return useOrganizationStore((s) => s.currentOrg?.id);
|
|
73
|
-
}
|
|
74
|
-
function toTemplate(automation) {
|
|
75
|
-
const eventKey = automation.triggerConfig?.eventKey;
|
|
76
|
-
if (!eventKey) return null;
|
|
77
|
-
const action = automation.actions?.[0];
|
|
78
|
-
return {
|
|
79
|
-
id: automation.id,
|
|
80
|
-
tenantId: automation.tenantId ?? "",
|
|
81
|
-
eventKey,
|
|
82
|
-
channel: automation.triggerConfig.sourceChannel ?? "email",
|
|
83
|
-
enabled: automation.enabled,
|
|
84
|
-
// Empty and absent mean the same — "no customisation", the catalogue default.
|
|
85
|
-
subject: action?.config?.subject || null,
|
|
86
|
-
body: action?.config?.body || null,
|
|
87
|
-
// The automation name belongs to the platform, not a user rename: the
|
|
88
|
-
// catalogue title still owns the screen.
|
|
89
|
-
name: null,
|
|
90
|
-
// The platform's automation action carries a subject and a body and nothing
|
|
91
|
-
// else, so there is nowhere for a customised button to live yet. NULL, not
|
|
92
|
-
// [], because the catalogue default is what still applies — an empty list
|
|
93
|
-
// would read as "this tenant removed the buttons".
|
|
94
|
-
actions: null,
|
|
95
|
-
updatedAt: automation.updatedAt
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
function catalogDefaultEnabled(eventKey, channel) {
|
|
99
|
-
const def = getMessageDefaults().find((d) => d.eventKey === eventKey);
|
|
100
|
-
return def?.defaultEnabled?.[channel] ?? false;
|
|
101
|
-
}
|
|
102
|
-
async function defaultSessionToken() {
|
|
103
|
-
const session = (await getFayzSupabaseClientOptional()?.auth.getSession())?.data.session;
|
|
104
|
-
return session?.access_token ?? null;
|
|
105
|
-
}
|
|
106
|
-
function createFayzTemplateStore(connection, deps = {}) {
|
|
107
|
-
const client = deps.client ?? createFayzAutomationsClient({
|
|
108
|
-
baseUrl: connection.apiBaseUrl,
|
|
109
|
-
projectId: connection.projectId,
|
|
110
|
-
publishableKey: connection.publishableKey
|
|
111
|
-
});
|
|
112
|
-
const getSessionToken = deps.getSessionToken ?? defaultSessionToken;
|
|
113
|
-
const ids = /* @__PURE__ */ new Map();
|
|
114
|
-
const keyOf = (eventKey, channel) => `${eventKey}:${channel}`;
|
|
115
|
-
async function refresh(tenantId) {
|
|
116
|
-
const automations = await client.list({ tenantId });
|
|
117
|
-
ids.clear();
|
|
118
|
-
const rows = [];
|
|
119
|
-
for (const automation of automations) {
|
|
120
|
-
const row = toTemplate(automation);
|
|
121
|
-
if (!row) continue;
|
|
122
|
-
ids.set(keyOf(row.eventKey, row.channel), automation.id);
|
|
123
|
-
rows.push(row);
|
|
124
|
-
}
|
|
125
|
-
return rows;
|
|
126
|
-
}
|
|
127
|
-
const LIST_TTL_MS = 3e4;
|
|
128
|
-
let cache = null;
|
|
129
|
-
function invalidate() {
|
|
130
|
-
cache = null;
|
|
131
|
-
}
|
|
132
|
-
function load(tenantId) {
|
|
133
|
-
if (cache && cache.tenantId === tenantId && Date.now() - cache.at < LIST_TTL_MS) return cache.promise;
|
|
134
|
-
const promise = refresh(tenantId);
|
|
135
|
-
promise.catch(() => {
|
|
136
|
-
if (cache?.promise === promise) cache = null;
|
|
137
|
-
});
|
|
138
|
-
cache = { tenantId, at: Date.now(), promise };
|
|
139
|
-
return promise;
|
|
140
|
-
}
|
|
141
|
-
async function requireToken() {
|
|
142
|
-
const token = await getSessionToken();
|
|
143
|
-
if (!token) throw new Error("Sess\xE3o expirada \u2014 entre de novo.");
|
|
144
|
-
return token;
|
|
145
|
-
}
|
|
146
|
-
async function resolveId(eventKey, channel, tenantId) {
|
|
147
|
-
const key = keyOf(eventKey, channel);
|
|
148
|
-
if (!ids.has(key)) await load(tenantId);
|
|
149
|
-
return ids.get(key);
|
|
150
|
-
}
|
|
151
|
-
return {
|
|
152
|
-
async list(tenantId) {
|
|
153
|
-
if (!tenantId) return [];
|
|
154
|
-
return load(tenantId);
|
|
155
|
-
},
|
|
156
|
-
async upsert(input, tenantId) {
|
|
157
|
-
if (!tenantId) throw new Error("@fayz-ai/plugin-automations: tenantId is required");
|
|
158
|
-
const appSessionToken = await requireToken();
|
|
159
|
-
const key = keyOf(input.eventKey, input.channel);
|
|
160
|
-
let id = await resolveId(input.eventKey, input.channel, tenantId);
|
|
161
|
-
if (!id) {
|
|
162
|
-
const action = {};
|
|
163
|
-
if (input.subject != null) action.subject = input.subject;
|
|
164
|
-
if (input.body != null) action.body = input.body;
|
|
165
|
-
try {
|
|
166
|
-
const created = await client.create({
|
|
167
|
-
tenantId,
|
|
168
|
-
appSessionToken,
|
|
169
|
-
eventKey: input.eventKey,
|
|
170
|
-
sourceChannel: input.channel,
|
|
171
|
-
// The platform has no "inherit from catalogue": materialise the default.
|
|
172
|
-
enabled: input.enabled ?? catalogDefaultEnabled(input.eventKey, input.channel),
|
|
173
|
-
...Object.keys(action).length ? { action } : {}
|
|
174
|
-
});
|
|
175
|
-
ids.set(key, created.id);
|
|
176
|
-
invalidate();
|
|
177
|
-
const row2 = toTemplate(created);
|
|
178
|
-
if (!row2) throw new Error("@fayz-ai/plugin-automations: platform did not round-trip eventKey");
|
|
179
|
-
return row2;
|
|
180
|
-
} catch (err) {
|
|
181
|
-
if (!(err instanceof FayzAutomationsError) || err.status !== 409) throw err;
|
|
182
|
-
invalidate();
|
|
183
|
-
await refresh(tenantId);
|
|
184
|
-
id = ids.get(key);
|
|
185
|
-
if (!id) throw err;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
const updated = await client.update({
|
|
189
|
-
id,
|
|
190
|
-
tenantId,
|
|
191
|
-
appSessionToken,
|
|
192
|
-
// Only what was sent: omitting has to mean "leave it alone", as in the local store.
|
|
193
|
-
...typeof input.enabled === "boolean" ? { enabled: input.enabled } : {},
|
|
194
|
-
...input.subject !== void 0 || input.body !== void 0 ? {
|
|
195
|
-
action: {
|
|
196
|
-
...input.subject !== void 0 ? { subject: input.subject } : {},
|
|
197
|
-
...input.body !== void 0 ? { body: input.body } : {}
|
|
198
|
-
}
|
|
199
|
-
} : {}
|
|
200
|
-
});
|
|
201
|
-
invalidate();
|
|
202
|
-
const row = toTemplate(updated);
|
|
203
|
-
if (!row) throw new Error("@fayz-ai/plugin-automations: platform did not round-trip eventKey");
|
|
204
|
-
return row;
|
|
205
|
-
},
|
|
206
|
-
async reset(eventKey, channel, tenantId) {
|
|
207
|
-
if (!tenantId) return;
|
|
208
|
-
const id = await resolveId(eventKey, channel, tenantId);
|
|
209
|
-
if (!id) return;
|
|
210
|
-
const appSessionToken = await requireToken();
|
|
211
|
-
await client.update({ id, tenantId, appSessionToken, action: { subject: null, body: null } });
|
|
212
|
-
invalidate();
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
var cachedClient = null;
|
|
217
|
-
function getFayzAutomationsClient(connection) {
|
|
218
|
-
const key = `${connection.apiBaseUrl}|${connection.projectId}|${connection.publishableKey}`;
|
|
219
|
-
if (cachedClient?.key === key) return cachedClient.client;
|
|
220
|
-
const client = createFayzAutomationsClient({
|
|
221
|
-
baseUrl: connection.apiBaseUrl,
|
|
222
|
-
projectId: connection.projectId,
|
|
223
|
-
publishableKey: connection.publishableKey
|
|
224
|
-
});
|
|
225
|
-
cachedClient = { key, client };
|
|
226
|
-
return client;
|
|
227
|
-
}
|
|
228
|
-
var STATUS = {
|
|
229
|
-
sent: { label: "Enviado", hint: "A mensagem saiu.", variant: "success", Icon: CircleCheck },
|
|
230
|
-
recorded: {
|
|
231
|
-
label: "Disparou",
|
|
232
|
-
// Today's honest state: the trigger works, the send doesn't exist yet.
|
|
233
|
-
hint: "O gatilho disparou e ficou registrado. O envio autom\xE1tico ainda n\xE3o est\xE1 ligado neste ambiente.",
|
|
234
|
-
variant: "info",
|
|
235
|
-
Icon: History
|
|
236
|
-
},
|
|
237
|
-
skipped: { label: "Ignorado", hint: "O gatilho disparou, mas nada foi enviado \u2014 automa\xE7\xE3o desligada ou sem canal.", variant: "warning", Icon: CircleSlash },
|
|
238
|
-
failed: { label: "Falhou", hint: "A tentativa de envio quebrou. O erro est\xE1 na linha.", variant: "destructive", Icon: AlertTriangle }
|
|
239
|
-
};
|
|
240
|
-
function when(iso) {
|
|
241
|
-
const then = new Date(iso).getTime();
|
|
242
|
-
const diff = Date.now() - then;
|
|
243
|
-
const min = Math.round(diff / 6e4);
|
|
244
|
-
if (min < 1) return "agora";
|
|
245
|
-
if (min < 60) return `h\xE1 ${min} min`;
|
|
246
|
-
const h = Math.round(min / 60);
|
|
247
|
-
if (h < 24) return `h\xE1 ${h} h`;
|
|
248
|
-
return new Date(iso).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
|
249
|
-
}
|
|
250
|
-
function RunRow({ run }) {
|
|
251
|
-
const [open, setOpen] = React4__default.useState(false);
|
|
252
|
-
const cfg = STATUS[run.status] ?? STATUS.recorded;
|
|
253
|
-
const { Icon } = cfg;
|
|
254
|
-
return /* @__PURE__ */ jsxs("div", { className: "border-b border-border last:border-b-0", children: [
|
|
255
|
-
/* @__PURE__ */ jsxs(
|
|
256
|
-
Button,
|
|
257
|
-
{
|
|
258
|
-
variant: "bare",
|
|
259
|
-
size: "bare",
|
|
260
|
-
type: "button",
|
|
261
|
-
onClick: () => setOpen(!open),
|
|
262
|
-
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",
|
|
263
|
-
children: [
|
|
264
|
-
/* @__PURE__ */ jsx(ChevronRight, { className: `h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${open ? "rotate-90" : ""}` }),
|
|
265
|
-
/* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
|
|
266
|
-
/* @__PURE__ */ jsx(Badge, { variant: cfg.variant, children: cfg.label }),
|
|
267
|
-
/* @__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" }),
|
|
268
|
-
/* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: when(run.occurredAt) })
|
|
269
|
-
]
|
|
270
|
-
}
|
|
271
|
-
),
|
|
272
|
-
open && /* @__PURE__ */ jsxs("div", { className: "space-y-3 bg-muted/20 px-4 pb-4 pt-1", children: [
|
|
273
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: cfg.hint }),
|
|
274
|
-
/* @__PURE__ */ jsxs("div", { children: [
|
|
275
|
-
/* @__PURE__ */ jsx("p", { className: "mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", children: "Dados do disparo" }),
|
|
276
|
-
/* @__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) })
|
|
277
|
-
] }),
|
|
278
|
-
run.result && /* @__PURE__ */ jsxs("div", { children: [
|
|
279
|
-
/* @__PURE__ */ jsx("p", { className: "mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", children: "Resultado" }),
|
|
280
|
-
/* @__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) })
|
|
281
|
-
] }),
|
|
282
|
-
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 })
|
|
283
|
-
] })
|
|
284
|
-
] });
|
|
285
|
-
}
|
|
286
|
-
function RunLog({ eventKey, tenantId, enabled }) {
|
|
287
|
-
const [runs, setRuns] = React4__default.useState(null);
|
|
288
|
-
const [loading, setLoading] = React4__default.useState(false);
|
|
289
|
-
const load = React4__default.useCallback(async () => {
|
|
290
|
-
setLoading(true);
|
|
291
|
-
setRuns(await loadEventRuns(eventKey, { tenantId, limit: 20 }));
|
|
292
|
-
setLoading(false);
|
|
293
|
-
}, [eventKey, tenantId]);
|
|
294
|
-
React4__default.useEffect(() => {
|
|
295
|
-
void load();
|
|
296
|
-
}, [load]);
|
|
297
|
-
return /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
|
|
298
|
-
/* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
|
|
299
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
300
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Execu\xE7\xF5es recentes" }),
|
|
301
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Cada vez que este gatilho disparou nesta conta." })
|
|
302
|
-
] }),
|
|
303
|
-
/* @__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" : ""}` }) })
|
|
304
|
-
] }),
|
|
305
|
-
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: [
|
|
306
|
-
/* @__PURE__ */ jsx(History, { className: "h-7 w-7 text-muted-foreground/40", strokeWidth: 1.5 }),
|
|
307
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Nenhum disparo ainda" }),
|
|
308
|
-
/* @__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." })
|
|
309
|
-
] }) : /* @__PURE__ */ jsx("div", { children: runs.map((run) => /* @__PURE__ */ jsx(RunRow, { run }, run.id)) })
|
|
310
|
-
] });
|
|
311
|
-
}
|
|
312
|
-
var EXEC_STATUS = {
|
|
313
|
-
success: { label: "Executada", variant: "success", Icon: CircleCheck },
|
|
314
|
-
error: { label: "Falhou", variant: "destructive", Icon: AlertTriangle }
|
|
315
|
-
};
|
|
316
|
-
function ExecutionRow({ execution }) {
|
|
317
|
-
const cfg = EXEC_STATUS[execution.status] ?? { label: execution.status, variant: "info", Icon: History };
|
|
318
|
-
const { Icon } = cfg;
|
|
319
|
-
return /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-4 py-2.5 last:border-b-0", children: [
|
|
320
|
-
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
321
|
-
/* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
|
|
322
|
-
/* @__PURE__ */ jsx(Badge, { variant: cfg.variant, children: cfg.label }),
|
|
323
|
-
/* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-sm text-muted-foreground", children: execution.automationName }),
|
|
324
|
-
/* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: when(execution.executedAt) })
|
|
325
|
-
] }),
|
|
326
|
-
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 })
|
|
327
|
-
] });
|
|
328
|
-
}
|
|
329
|
-
function FayzRunLog({ connection, eventKey, tenantId, enabled }) {
|
|
330
|
-
const [executions, setExecutions] = React4__default.useState(null);
|
|
331
|
-
const [loading, setLoading] = React4__default.useState(false);
|
|
332
|
-
const load = React4__default.useCallback(async () => {
|
|
333
|
-
if (!tenantId) return;
|
|
334
|
-
setLoading(true);
|
|
335
|
-
try {
|
|
336
|
-
setExecutions(await getFayzAutomationsClient(connection).listExecutions({ tenantId, eventKey, limit: 20 }));
|
|
337
|
-
} catch (err) {
|
|
338
|
-
console.warn("[automations] could not load platform executions", err);
|
|
339
|
-
setExecutions([]);
|
|
340
|
-
} finally {
|
|
341
|
-
setLoading(false);
|
|
342
|
-
}
|
|
343
|
-
}, [connection, eventKey, tenantId]);
|
|
344
|
-
React4__default.useEffect(() => {
|
|
345
|
-
void load();
|
|
346
|
-
}, [load]);
|
|
347
|
-
return /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
|
|
348
|
-
/* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
|
|
349
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
350
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Execu\xE7\xF5es recentes" }),
|
|
351
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "O que a plataforma Fayz executou para este gatilho nesta conta." })
|
|
352
|
-
] }),
|
|
353
|
-
/* @__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" : ""}` }) })
|
|
354
|
-
] }),
|
|
355
|
-
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: [
|
|
356
|
-
/* @__PURE__ */ jsx(History, { className: "h-7 w-7 text-muted-foreground/40", strokeWidth: 1.5 }),
|
|
357
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Nenhuma execu\xE7\xE3o ainda" }),
|
|
358
|
-
/* @__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." })
|
|
359
|
-
] }) : /* @__PURE__ */ jsx("div", { children: executions.map((e) => /* @__PURE__ */ jsx(ExecutionRow, { execution: e }, e.id)) })
|
|
360
|
-
] });
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// src/views/whatsapp-preview-bg.ts
|
|
364
|
-
var WHATSAPP_PREVIEW_BG = "https://assets.fayz.ai/connectors/whatsapp-background.jpg";
|
|
365
|
-
var PROVIDER_TEMPLATES_TABLE = "plg_automations_provider_templates";
|
|
366
|
-
function rowToProviderTemplate(row) {
|
|
367
|
-
return {
|
|
368
|
-
id: row.id,
|
|
369
|
-
tenantId: row.tenant_id ?? null,
|
|
370
|
-
eventKey: row.event_key,
|
|
371
|
-
channel: row.channel ?? "whatsapp",
|
|
372
|
-
provider: row.provider ?? "tyxter",
|
|
373
|
-
templateName: row.template_name ?? "",
|
|
374
|
-
status: row.status ?? "draft",
|
|
375
|
-
rejectionReason: row.rejection_reason || null,
|
|
376
|
-
updatedAt: row.updated_at ?? row.created_at ?? null
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
async function loadProviderTemplates() {
|
|
380
|
-
const client = getSupabaseClientOptional();
|
|
381
|
-
if (!client) return [];
|
|
382
|
-
try {
|
|
383
|
-
const { data, error } = await client.from(PROVIDER_TEMPLATES_TABLE).select("*");
|
|
384
|
-
if (error) throw error;
|
|
385
|
-
return (data ?? []).map(rowToProviderTemplate);
|
|
386
|
-
} catch (err) {
|
|
387
|
-
console.warn("[automations] could not load provider template status", err);
|
|
388
|
-
return [];
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
function providerTemplateFor(rows, eventKey, channel) {
|
|
392
|
-
const matching = rows.filter((r) => r.eventKey === eventKey && r.channel === channel);
|
|
393
|
-
return {
|
|
394
|
-
own: matching.find((r) => r.tenantId !== null) ?? null,
|
|
395
|
-
fallback: matching.find((r) => r.tenantId === null) ?? null
|
|
396
|
-
};
|
|
397
|
-
}
|
|
398
|
-
function providerApprovalFor(rows, eventKey, channel) {
|
|
399
|
-
if (channel !== "whatsapp") return null;
|
|
400
|
-
const { own, fallback } = providerTemplateFor(rows, eventKey, channel);
|
|
401
|
-
const row = own ?? fallback;
|
|
402
|
-
if (!row) return null;
|
|
403
|
-
const fallbackApproved = fallback?.status === "approved";
|
|
404
|
-
switch (row.status) {
|
|
405
|
-
case "approved":
|
|
406
|
-
return { tone: "ok", label: "Aprovado pela Meta" };
|
|
407
|
-
case "rejected":
|
|
408
|
-
return {
|
|
409
|
-
tone: fallbackApproved && own ? "waiting" : "error",
|
|
410
|
-
label: fallbackApproved && own ? "Seu texto foi recusado" : "Recusado pela Meta",
|
|
411
|
-
detail: row.rejectionReason ? `Motivo: ${row.rejectionReason}` : "A Meta n\xE3o disse o motivo."
|
|
412
|
-
};
|
|
413
|
-
case "paused":
|
|
414
|
-
return {
|
|
415
|
-
tone: "error",
|
|
416
|
-
label: "Pausado pela Meta",
|
|
417
|
-
detail: row.rejectionReason ?? "Costuma ser excesso de marca\xE7\xF5es de spam pelos clientes."
|
|
418
|
-
};
|
|
419
|
-
case "disabled":
|
|
420
|
-
return { tone: "error", label: "Desativado pela Meta", detail: row.rejectionReason ?? void 0 };
|
|
421
|
-
case "submitted":
|
|
422
|
-
return {
|
|
423
|
-
tone: "waiting",
|
|
424
|
-
label: "Aguardando aprova\xE7\xE3o da Meta",
|
|
425
|
-
detail: fallbackApproved && own ? "At\xE9 l\xE1 a mensagem sai com o texto padr\xE3o." : "A revis\xE3o costuma levar algumas horas."
|
|
426
|
-
};
|
|
427
|
-
default:
|
|
428
|
-
return { tone: "waiting", label: "Ainda n\xE3o enviado para aprova\xE7\xE3o" };
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
var TONE_VARIANT = {
|
|
432
|
-
ok: "success",
|
|
433
|
-
waiting: "warning",
|
|
434
|
-
error: "destructive"
|
|
435
|
-
};
|
|
436
|
-
function ProviderTemplateBadge({ approval, showDetail }) {
|
|
437
|
-
if (!approval) return null;
|
|
438
|
-
if (approval.tone === "ok" && !showDetail) return null;
|
|
439
|
-
return /* @__PURE__ */ jsxs("span", { className: "inline-flex flex-wrap items-center gap-1.5", children: [
|
|
440
|
-
/* @__PURE__ */ jsx(Badge, { variant: TONE_VARIANT[approval.tone], children: approval.label }),
|
|
441
|
-
showDetail && approval.detail && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: approval.detail })
|
|
442
|
-
] });
|
|
443
|
-
}
|
|
444
|
-
function useProviderTemplates() {
|
|
445
|
-
const [rows, setRows] = React4__default.useState([]);
|
|
446
|
-
React4__default.useEffect(() => {
|
|
447
|
-
let cancelled = false;
|
|
448
|
-
void loadProviderTemplates().then((data) => {
|
|
449
|
-
if (!cancelled) setRows(data);
|
|
450
|
-
});
|
|
451
|
-
return () => {
|
|
452
|
-
cancelled = true;
|
|
453
|
-
};
|
|
454
|
-
}, []);
|
|
455
|
-
return rows;
|
|
456
|
-
}
|
|
457
|
-
var ACTION_CATALOG = [
|
|
458
|
-
{ id: "confirm", label: "Confirma", kind: "reply", hint: "O cliente confirma o hor\xE1rio no toque." },
|
|
459
|
-
{ id: "cancel", label: "Cancela", kind: "reply", hint: "O cliente desmarca sem precisar ligar." },
|
|
460
|
-
{ id: "pay", label: "Pagar", kind: "payment", hint: "O cliente recebe o Pix na conversa." }
|
|
461
|
-
];
|
|
462
|
-
function nextActions(current, id, on) {
|
|
463
|
-
const kept = new Set(current.filter((a) => a.id !== id).map((a) => a.id));
|
|
464
|
-
if (on) kept.add(id);
|
|
465
|
-
const labels = new Map(current.map((a) => [a.id, a.label]));
|
|
466
|
-
return ACTION_CATALOG.filter((a) => kept.has(a.id)).map((a) => ({ id: a.id, label: labels.get(a.id) ?? a.label, kind: a.kind }));
|
|
467
|
-
}
|
|
468
|
-
var TEST_ERROR = {
|
|
469
|
-
template_not_approved: "O modelo ainda n\xE3o foi aprovado pela Meta \u2014 sincronize os modelos e tente de novo.",
|
|
470
|
-
no_sender: "Este app ainda n\xE3o tem um n\xFAmero de WhatsApp ativo. Veja Conversas \u2192 Tyxter.",
|
|
471
|
-
not_connected: "O WhatsApp ainda n\xE3o est\xE1 conectado neste app. Veja Conversas \u2192 Tyxter.",
|
|
472
|
-
contact_opted_out: "Este contato pediu para n\xE3o receber mensagens.",
|
|
473
|
-
invalid_recipient: "Esse destino n\xE3o parece v\xE1lido.",
|
|
474
|
-
not_a_member: "A sua sess\xE3o n\xE3o pertence a este neg\xF3cio.",
|
|
475
|
-
not_available: "O envio de teste n\xE3o est\xE1 dispon\xEDvel neste ambiente.",
|
|
476
|
-
email_not_configured: "O envio de e-mail n\xE3o est\xE1 configurado neste app.",
|
|
477
|
-
template_not_found: "Escreva a mensagem antes de testar.",
|
|
478
|
-
email_rejected: "O provedor de e-mail recusou a mensagem.",
|
|
479
|
-
email_credential_rejected: "A chave de e-mail do app foi recusada pelo provedor.",
|
|
480
|
-
email_rate_limited: "O provedor pediu uma pausa \u2014 tente de novo em instantes."
|
|
481
|
-
};
|
|
482
|
-
function TestSendStrip({ eventKey, channel, placeholders, template }) {
|
|
483
|
-
const isEmail = channel === "email";
|
|
484
|
-
const [recipient, setRecipient] = React4__default.useState("");
|
|
485
|
-
const [sending, setSending] = React4__default.useState(false);
|
|
486
|
-
const valid = isEmail ? /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(recipient.trim()) : recipient.replace(/\D/g, "").length >= 10;
|
|
487
|
-
const send = async () => {
|
|
488
|
-
setSending(true);
|
|
489
|
-
try {
|
|
490
|
-
const variables = Object.fromEntries(placeholders.map((p) => {
|
|
491
|
-
const key = p.replace(/[{}]/g, "").trim();
|
|
492
|
-
return [key, SAMPLE[key] ?? key];
|
|
493
|
-
}));
|
|
494
|
-
const result = await sendTestMessage({ eventKey, channel, to: recipient.trim(), variables, template });
|
|
495
|
-
if (result.ok) {
|
|
496
|
-
toast.success(isEmail ? "Teste enviado \u2014 confira a caixa de entrada desse e-mail" : "Teste enviado \u2014 confira o WhatsApp desse n\xFAmero");
|
|
497
|
-
} else {
|
|
498
|
-
toast.error(TEST_ERROR[result.error ?? ""] ?? result.message ?? "N\xE3o foi poss\xEDvel enviar o teste");
|
|
499
|
-
}
|
|
500
|
-
} finally {
|
|
501
|
-
setSending(false);
|
|
502
|
-
}
|
|
503
|
-
};
|
|
504
|
-
return (
|
|
505
|
-
// Sem moldura própria: o strip vive dentro do Card da aba Testar, e uma
|
|
506
|
-
// borda aqui era o anel duplicado de sempre.
|
|
507
|
-
/* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-end gap-2", children: [
|
|
508
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
|
|
509
|
-
/* @__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" }),
|
|
510
|
-
isEmail ? /* @__PURE__ */ jsx(
|
|
511
|
-
Input,
|
|
512
|
-
{
|
|
513
|
-
type: "email",
|
|
514
|
-
value: recipient,
|
|
515
|
-
onChange: (e) => setRecipient(e.target.value),
|
|
516
|
-
placeholder: "voce@exemplo.com",
|
|
517
|
-
disabled: sending,
|
|
518
|
-
"aria-label": "E-mail que recebe o teste"
|
|
519
|
-
}
|
|
520
|
-
) : /* @__PURE__ */ jsx(
|
|
521
|
-
PhoneField,
|
|
522
|
-
{
|
|
523
|
-
value: recipient,
|
|
524
|
-
onChange: setRecipient,
|
|
525
|
-
placeholder: "(21) 99999-9999",
|
|
526
|
-
disabled: sending,
|
|
527
|
-
"aria-label": "N\xFAmero que recebe o teste"
|
|
528
|
-
}
|
|
529
|
-
)
|
|
530
|
-
] }),
|
|
531
|
-
/* @__PURE__ */ jsxs(Button, { variant: "outline", onClick: () => void send(), disabled: !valid || sending, children: [
|
|
532
|
-
/* @__PURE__ */ jsx(Send, { className: "mr-2 h-3.5 w-3.5" }),
|
|
533
|
-
sending ? "Enviando\u2026" : "Enviar teste"
|
|
534
|
-
] })
|
|
535
|
-
] })
|
|
536
|
-
);
|
|
537
|
-
}
|
|
538
|
-
var TABS = [
|
|
539
|
-
{ value: "preview", label: "Pr\xE9via" },
|
|
540
|
-
{ value: "code", label: "C\xF3digo" },
|
|
541
|
-
// O que já aconteceu. Fica ao lado do texto, e não numa tela à parte, porque
|
|
542
|
-
// é a mesma pergunta em dois tempos: o que vai sair, e o que saiu.
|
|
543
|
-
{ value: "runs", label: "Execu\xE7\xF5es" }
|
|
544
|
-
];
|
|
545
|
-
var TEST_TAB = { value: "test", label: "Testar" };
|
|
546
|
-
var CHANNEL_LABEL = {
|
|
547
|
-
email: "E-mail",
|
|
548
|
-
whatsapp: "WhatsApp",
|
|
549
|
-
sms: "SMS",
|
|
550
|
-
push: "Push",
|
|
551
|
-
webchat: "Chat"
|
|
552
|
-
};
|
|
553
|
-
var CHANNEL_ICON = {
|
|
554
|
-
email: Mail,
|
|
555
|
-
whatsapp: WhatsAppIcon,
|
|
556
|
-
sms: Smartphone,
|
|
557
|
-
push: MessageSquare,
|
|
558
|
-
webchat: MessageSquare
|
|
559
|
-
};
|
|
560
|
-
var WRITE_MESSAGE_TOOL = {
|
|
561
|
-
id: "automations.writeMessage",
|
|
562
|
-
name: "writeAutomationMessage",
|
|
563
|
-
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.",
|
|
564
|
-
icon: "MessageSquare",
|
|
565
|
-
mode: "read",
|
|
566
|
-
execution: { plane: "client" },
|
|
567
|
-
category: "Automations",
|
|
568
|
-
parameters: {
|
|
569
|
-
type: "object",
|
|
570
|
-
properties: {
|
|
571
|
-
subject: { type: "string", description: "Subject line. Leave empty for channels that have none." },
|
|
572
|
-
body: { type: "string", description: "Message body, with placeholders where they belong." }
|
|
573
|
-
},
|
|
574
|
-
required: ["body"]
|
|
575
|
-
}
|
|
576
|
-
};
|
|
577
|
-
var SAMPLE = {
|
|
578
|
-
store_name: "Sua Loja",
|
|
579
|
-
company_name: "Sua Empresa",
|
|
580
|
-
customer_name: "Maria Silva",
|
|
581
|
-
contact_name: "Maria Silva",
|
|
582
|
-
lead_name: "Maria Silva",
|
|
583
|
-
order_number: "1042",
|
|
584
|
-
order_total: "R$ 189,90",
|
|
585
|
-
order_items: "1 \xD7 Camiseta Cl\xE1ssica \u2014 R$ 89,90\n2 \xD7 Caneca Esmaltada \u2014 R$ 100,00",
|
|
586
|
-
tracking_code: "BR123456789BR",
|
|
587
|
-
cart_url: "https://sualoja.com.br/carrinho",
|
|
588
|
-
deal_name: "Proposta \u2014 Reforma da fachada",
|
|
589
|
-
deal_value: "R$ 12.400,00",
|
|
590
|
-
stage_name: "Negocia\xE7\xE3o",
|
|
591
|
-
owner_name: "Jo\xE3o Pereira",
|
|
592
|
-
appointment_date: "12/08/2026",
|
|
593
|
-
appointment_time: "14:30"
|
|
594
|
-
};
|
|
595
|
-
function AutomationDetailPage({ eventKey, channel, store: store2, backTo = "/automations", embedded, onDone }) {
|
|
596
|
-
const tenantId = useOrganizationStoreLike();
|
|
597
|
-
const runtime = usePluginRuntimeOptional();
|
|
598
|
-
const fayzConnection = React4__default.useMemo(() => resolveFayzAgentConnection(), []);
|
|
599
|
-
const [message, setMessage] = React4__default.useState(void 0);
|
|
600
|
-
const [tab, setTab] = React4__default.useState("preview");
|
|
601
|
-
const [device, setDevice] = React4__default.useState("desktop");
|
|
602
|
-
const [draft, setDraft] = React4__default.useState(null);
|
|
603
|
-
const [labelDrafts, setLabelDrafts] = React4__default.useState({});
|
|
604
|
-
const [saving, setSaving] = React4__default.useState(false);
|
|
605
|
-
const providerTemplates = useProviderTemplates();
|
|
606
|
-
const { readiness, loading: readinessLoading } = usePaymentReadiness();
|
|
607
|
-
const back = React4__default.useCallback(
|
|
608
|
-
() => onDone ? onDone() : adminNavigateTo(backTo),
|
|
609
|
-
[onDone, backTo]
|
|
610
|
-
);
|
|
611
|
-
const surfaceRef = React4__default.useRef({ message, draft });
|
|
612
|
-
surfaceRef.current = { message, draft };
|
|
613
|
-
const agentSurface = React4__default.useMemo(() => ({
|
|
614
|
-
id: "automations.message",
|
|
615
|
-
pluginId: "automations",
|
|
616
|
-
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.",
|
|
617
|
-
describe: () => {
|
|
618
|
-
const o = surfaceRef.current;
|
|
619
|
-
if (!o.message) return { title: "Automa\xE7\xE3o" };
|
|
620
|
-
const current2 = o.draft ?? { subject: o.message.subject, body: o.message.body };
|
|
621
|
-
return {
|
|
622
|
-
title: `Automa\xE7\xE3o \u2014 ${o.message.event?.title ?? o.message.event?.name ?? ""}`,
|
|
623
|
-
state: {
|
|
624
|
-
event: o.message.event?.name ?? null,
|
|
625
|
-
channel: o.message.channel,
|
|
626
|
-
hasSubject: o.message.channel === "email",
|
|
627
|
-
placeholders: Object.keys(SAMPLE).map((key) => `{{${key}}}`),
|
|
628
|
-
currentSubject: current2.subject,
|
|
629
|
-
currentBody: current2.body
|
|
630
|
-
}
|
|
631
|
-
};
|
|
632
|
-
},
|
|
633
|
-
tools: [{
|
|
634
|
-
tool: WRITE_MESSAGE_TOOL,
|
|
635
|
-
execute: (args) => {
|
|
636
|
-
const o = surfaceRef.current;
|
|
637
|
-
if (!o.message) return { ok: false, error: "no_message_open" };
|
|
638
|
-
const current2 = o.draft ?? { subject: o.message.subject, body: o.message.body };
|
|
639
|
-
const body = String(args.body ?? "").trim();
|
|
640
|
-
if (!body) return { ok: false, error: "empty_body" };
|
|
641
|
-
const subject = args.subject === void 0 ? current2.subject : String(args.subject);
|
|
642
|
-
setDraft({ subject, body });
|
|
643
|
-
setTab("code");
|
|
644
|
-
return { ok: true, filled: true, saved: false, note: "Draft filled \u2014 the user still has to press Save." };
|
|
645
|
-
}
|
|
646
|
-
}]
|
|
647
|
-
}), []);
|
|
648
|
-
useAgentSurface(agentSurface);
|
|
649
|
-
const reload = React4__default.useCallback(async () => {
|
|
650
|
-
if (!eventKey || !channel) {
|
|
651
|
-
setMessage(null);
|
|
652
|
-
return;
|
|
653
|
-
}
|
|
654
|
-
let overrides = [];
|
|
655
|
-
try {
|
|
656
|
-
overrides = await store2.list(tenantId);
|
|
657
|
-
} catch (err) {
|
|
658
|
-
console.warn("[automations] could not load overrides; showing defaults", err);
|
|
659
|
-
}
|
|
660
|
-
const found = resolveMessage(decodeURIComponent(eventKey), channel, overrides, runtime?.events ?? []);
|
|
661
|
-
setMessage(found);
|
|
662
|
-
if (found) setDraft({ subject: found.subject, body: found.body });
|
|
663
|
-
}, [eventKey, channel, store2, tenantId, runtime]);
|
|
664
|
-
React4__default.useEffect(() => {
|
|
665
|
-
void reload();
|
|
666
|
-
}, [reload]);
|
|
667
|
-
const header = embedded ? null : /* @__PURE__ */ jsx(
|
|
668
|
-
SubpageHeader,
|
|
669
|
-
{
|
|
670
|
-
title: message === void 0 ? "" : message?.override?.name ?? message?.event.title ?? message?.event.name ?? "Automa\xE7\xE3o",
|
|
671
|
-
parentLabel: "Automa\xE7\xF5es",
|
|
672
|
-
onBack: back
|
|
673
|
-
}
|
|
674
|
-
);
|
|
675
|
-
if (message === void 0) {
|
|
676
|
-
return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
|
|
677
|
-
header,
|
|
678
|
-
/* @__PURE__ */ jsx("div", { className: "h-8 w-64 animate-pulse rounded bg-muted" }),
|
|
679
|
-
/* @__PURE__ */ jsx(Card, { className: "h-96 animate-pulse" })
|
|
680
|
-
] });
|
|
681
|
-
}
|
|
682
|
-
if (!message) {
|
|
683
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
684
|
-
header,
|
|
685
|
-
/* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-2 p-12 text-center", children: [
|
|
686
|
-
/* @__PURE__ */ jsx(Mail, { className: "h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
|
|
687
|
-
/* @__PURE__ */ jsx("p", { className: "font-semibold", children: "Automa\xE7\xE3o n\xE3o encontrada" }),
|
|
688
|
-
/* @__PURE__ */ jsxs("p", { className: "max-w-sm text-sm text-muted-foreground", children: [
|
|
689
|
-
"O evento ",
|
|
690
|
-
/* @__PURE__ */ jsx("code", { className: "font-mono", children: eventKey }),
|
|
691
|
-
" n\xE3o est\xE1 no cat\xE1logo \u2014 o m\xF3dulo que o registra pode n\xE3o estar instalado nesta conta."
|
|
692
|
-
] }),
|
|
693
|
-
/* @__PURE__ */ jsx(Button, { variant: "outline", className: "mt-2", onClick: back, children: "Voltar para Automa\xE7\xF5es" })
|
|
694
|
-
] })
|
|
695
|
-
] });
|
|
696
|
-
}
|
|
697
|
-
const event = message.event;
|
|
698
|
-
const fallback = { subject: message.override ? void 0 : message.subject, body: message.body };
|
|
699
|
-
const ChannelIcon = CHANNEL_ICON[message.channel] ?? Zap;
|
|
700
|
-
const isWhatsapp = message.channel === "whatsapp";
|
|
701
|
-
const current = draft ?? { subject: message.subject, body: message.body };
|
|
702
|
-
const dirty = current.subject !== message.subject || current.body !== message.body;
|
|
703
|
-
const hasSubject = message.channel === "email";
|
|
704
|
-
const patch = async (input) => {
|
|
705
|
-
setSaving(true);
|
|
706
|
-
try {
|
|
707
|
-
await store2.upsert(input, tenantId);
|
|
708
|
-
await reload();
|
|
709
|
-
} catch (err) {
|
|
710
|
-
console.warn("[automations] save failed", err);
|
|
711
|
-
toast.error("N\xE3o foi poss\xEDvel salvar");
|
|
712
|
-
} finally {
|
|
713
|
-
setSaving(false);
|
|
714
|
-
}
|
|
715
|
-
};
|
|
716
|
-
const save = () => void patch({
|
|
717
|
-
eventKey: event.name,
|
|
718
|
-
channel: message.channel,
|
|
719
|
-
// Igual ao padrão volta a ser "sem personalização", não uma cópia.
|
|
720
|
-
subject: current.subject.trim() === (fallback?.subject ?? "") ? null : current.subject.trim() || null,
|
|
721
|
-
body: current.body.trim() === fallback?.body ? null : current.body.trim() || null
|
|
722
|
-
});
|
|
723
|
-
const reset = async () => {
|
|
724
|
-
setDraft({ subject: fallback?.subject ?? "", body: fallback?.body ?? "" });
|
|
725
|
-
setSaving(true);
|
|
726
|
-
try {
|
|
727
|
-
await store2.reset(event.name, message.channel, tenantId);
|
|
728
|
-
await reload();
|
|
729
|
-
toast.success("Texto restaurado");
|
|
730
|
-
} catch (err) {
|
|
731
|
-
console.warn("[automations] reset failed", err);
|
|
732
|
-
toast.error("N\xE3o foi poss\xEDvel restaurar");
|
|
733
|
-
} finally {
|
|
734
|
-
setSaving(false);
|
|
735
|
-
}
|
|
736
|
-
};
|
|
737
|
-
const previewSubject = renderMessageTemplate(current.subject, SAMPLE);
|
|
738
|
-
const previewBody = renderMessageTemplate(current.body, SAMPLE);
|
|
739
|
-
return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
|
|
740
|
-
header,
|
|
741
|
-
/* @__PURE__ */ jsxs("div", { className: embedded ? "space-y-3" : "flex flex-wrap items-start gap-3", children: [
|
|
742
|
-
/* @__PURE__ */ jsxs("div", { className: embedded ? "flex items-start gap-3" : "contents", children: [
|
|
743
|
-
/* @__PURE__ */ jsx(
|
|
744
|
-
"span",
|
|
745
|
-
{
|
|
746
|
-
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"}`,
|
|
747
|
-
children: /* @__PURE__ */ jsx(ChannelIcon, { className: "h-4 w-4" })
|
|
748
|
-
}
|
|
749
|
-
),
|
|
750
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
|
|
751
|
-
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
752
|
-
/* @__PURE__ */ jsx(Badge, { variant: "outline", children: CHANNEL_LABEL[message.channel] }),
|
|
753
|
-
/* @__PURE__ */ jsx(Badge, { variant: "outline", children: message.kind === "marketing" ? "Marketing" : "Transacional" }),
|
|
754
|
-
message.customized && /* @__PURE__ */ jsx(Badge, { variant: "info", children: "Personalizado" })
|
|
755
|
-
] }),
|
|
756
|
-
/* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm text-muted-foreground", children: event.description }),
|
|
757
|
-
/* @__PURE__ */ jsx("div", { className: "mt-1.5", children: /* @__PURE__ */ jsx(
|
|
758
|
-
ProviderTemplateBadge,
|
|
759
|
-
{
|
|
760
|
-
approval: providerApprovalFor(providerTemplates, event.name, message.channel),
|
|
761
|
-
showDetail: true
|
|
762
|
-
}
|
|
763
|
-
) })
|
|
764
|
-
] })
|
|
765
|
-
] }),
|
|
766
|
-
/* @__PURE__ */ jsxs("div", { className: embedded ? "flex items-center gap-2" : "flex shrink-0 flex-wrap items-center gap-2", children: [
|
|
767
|
-
/* @__PURE__ */ jsx(
|
|
768
|
-
Switch,
|
|
769
|
-
{
|
|
770
|
-
size: "md",
|
|
771
|
-
checked: message.enabled,
|
|
772
|
-
onCheckedChange: (next) => void patch({ eventKey: event.name, channel: message.channel, enabled: next }),
|
|
773
|
-
disabled: saving,
|
|
774
|
-
label: message.enabled ? "Ativa" : "Inativa"
|
|
775
|
-
}
|
|
776
|
-
),
|
|
777
|
-
/* @__PURE__ */ jsxs("div", { className: embedded ? "ml-auto flex items-center gap-2" : "contents", children: [
|
|
778
|
-
/* @__PURE__ */ jsx(Hint, { label: "Descarta o texto personalizado e volta ao padr\xE3o do produto.", children: /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsxs(
|
|
779
|
-
Button,
|
|
780
|
-
{
|
|
781
|
-
variant: embedded ? "ghost" : "outline",
|
|
782
|
-
size: embedded ? "icon" : void 0,
|
|
783
|
-
onClick: () => void reset(),
|
|
784
|
-
disabled: !message.customized || saving,
|
|
785
|
-
"aria-label": embedded ? "Restaurar padr\xE3o" : void 0,
|
|
786
|
-
children: [
|
|
787
|
-
/* @__PURE__ */ jsx(RotateCcw, { className: embedded ? "h-4 w-4" : "mr-2 h-4 w-4" }),
|
|
788
|
-
!embedded && "Restaurar padr\xE3o"
|
|
789
|
-
]
|
|
790
|
-
}
|
|
791
|
-
) }) }),
|
|
792
|
-
/* @__PURE__ */ jsx(
|
|
793
|
-
AskAIButton,
|
|
794
|
-
{
|
|
795
|
-
variant: embedded ? "ghost" : "outline",
|
|
796
|
-
label: embedded ? "" : void 0,
|
|
797
|
-
hint: "Descreva o tom da mensagem\u2026",
|
|
798
|
-
intro: {
|
|
799
|
-
role: "setup",
|
|
800
|
-
persona: "Redator das automa\xE7\xF5es",
|
|
801
|
-
pitch: "Diga como esta mensagem deve soar.",
|
|
802
|
-
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.",
|
|
803
|
-
suggestions: [
|
|
804
|
-
{ label: "Mais curta e direta" },
|
|
805
|
-
{ label: "Mais calorosa, com o nome do cliente" },
|
|
806
|
-
{ label: "Formal, para um p\xFAblico corporativo" }
|
|
807
|
-
]
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
),
|
|
811
|
-
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: [
|
|
812
|
-
/* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }),
|
|
813
|
-
"Salvo"
|
|
814
|
-
] })
|
|
815
|
-
] })
|
|
816
|
-
] })
|
|
817
|
-
] }),
|
|
818
|
-
/* @__PURE__ */ jsx(
|
|
819
|
-
HeaderTabs,
|
|
820
|
-
{
|
|
821
|
-
tabs: isWhatsapp || message.channel === "email" ? [...TABS, TEST_TAB] : TABS,
|
|
822
|
-
value: tab,
|
|
823
|
-
onChange: setTab,
|
|
824
|
-
"aria-label": "Visualiza\xE7\xE3o"
|
|
825
|
-
}
|
|
826
|
-
),
|
|
827
|
-
/* @__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: [
|
|
828
|
-
/* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
|
|
829
|
-
/* @__PURE__ */ jsx(Zap, { className: "h-3.5 w-3.5" }),
|
|
830
|
-
"Gatilho:",
|
|
831
|
-
/* @__PURE__ */ jsx("code", { className: "rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-foreground", children: event.name })
|
|
832
|
-
] }),
|
|
833
|
-
/* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
|
|
834
|
-
/* @__PURE__ */ jsx(Clock, { className: "h-3.5 w-3.5" }),
|
|
835
|
-
event.trigger
|
|
836
|
-
] }),
|
|
837
|
-
hasSubject && current.subject && /* @__PURE__ */ jsxs("span", { className: "min-w-0 truncate", children: [
|
|
838
|
-
"Assunto: ",
|
|
839
|
-
current.subject
|
|
840
|
-
] })
|
|
841
|
-
] }),
|
|
842
|
-
tab === "runs" ? (
|
|
843
|
-
// Atrás de um projeto Fayz o histórico verdadeiro é o da plataforma —
|
|
844
|
-
// é ela quem executa. Fora dele, o coletor local continua valendo.
|
|
845
|
-
fayzConnection ? /* @__PURE__ */ jsx(FayzRunLog, { connection: fayzConnection, eventKey: event.name, tenantId, enabled: message.enabled }) : /* @__PURE__ */ jsx(RunLog, { eventKey: event.name, tenantId, enabled: message.enabled })
|
|
846
|
-
) : tab === "preview" ? /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
|
|
847
|
-
!embedded && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-border px-4 py-2.5", children: [
|
|
848
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Pr\xE9via" }),
|
|
849
|
-
/* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: ["desktop", "mobile"].map((d) => /* @__PURE__ */ jsx(
|
|
850
|
-
Button,
|
|
851
|
-
{
|
|
852
|
-
variant: "bare",
|
|
853
|
-
size: "bare",
|
|
854
|
-
type: "button",
|
|
855
|
-
onClick: () => setDevice(d),
|
|
856
|
-
"aria-label": d === "desktop" ? "Computador" : "Celular",
|
|
857
|
-
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"}`,
|
|
858
|
-
children: d === "desktop" ? /* @__PURE__ */ jsx(Monitor, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Smartphone, { className: "h-4 w-4" })
|
|
859
|
-
},
|
|
860
|
-
d
|
|
861
|
-
)) })
|
|
862
|
-
] }),
|
|
863
|
-
/* @__PURE__ */ jsxs("div", { className: embedded ? "bg-muted/30 p-4" : "bg-muted/30 p-6", children: [
|
|
864
|
-
/* @__PURE__ */ jsx(
|
|
865
|
-
"div",
|
|
866
|
-
{
|
|
867
|
-
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]"}`,
|
|
868
|
-
children: hasSubject ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
869
|
-
/* @__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: [
|
|
870
|
-
/* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#ff5f57]" }),
|
|
871
|
-
/* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#febc2e]" }),
|
|
872
|
-
/* @__PURE__ */ jsx("span", { className: "h-3 w-3 rounded-full bg-[#28c840]" })
|
|
873
|
-
] }),
|
|
874
|
-
/* @__PURE__ */ jsxs("div", { className: "px-6 pb-4 pt-5", children: [
|
|
875
|
-
/* @__PURE__ */ jsx("p", { className: "text-base font-semibold leading-snug", children: previewSubject }),
|
|
876
|
-
/* @__PURE__ */ jsxs("div", { className: "mt-4 flex items-center gap-3", children: [
|
|
877
|
-
/* @__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) }),
|
|
878
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
879
|
-
/* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: SAMPLE.store_name }),
|
|
880
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "para mim" })
|
|
881
|
-
] }),
|
|
882
|
-
/* @__PURE__ */ jsx("span", { className: "ml-auto shrink-0 text-xs text-muted-foreground", children: "09:41" })
|
|
883
|
-
] })
|
|
884
|
-
] }),
|
|
885
|
-
/* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap border-t border-border px-6 py-5 text-sm leading-relaxed", children: previewBody })
|
|
886
|
-
] }) : /* @__PURE__ */ jsxs(
|
|
887
|
-
"div",
|
|
888
|
-
{
|
|
889
|
-
className: "p-4",
|
|
890
|
-
style: isWhatsapp ? { backgroundImage: `url(${WHATSAPP_PREVIEW_BG})`, backgroundSize: "cover", backgroundPosition: "center" } : void 0,
|
|
891
|
-
children: [
|
|
892
|
-
/* @__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 }),
|
|
893
|
-
message.actions.length > 0 && /* @__PURE__ */ jsx("div", { className: "mt-1 space-y-1", children: message.actions.map((action) => /* @__PURE__ */ jsx(
|
|
894
|
-
"div",
|
|
895
|
-
{
|
|
896
|
-
className: "rounded-lg bg-white px-3 py-1.5 text-center text-sm font-medium text-[#1e7fd6] shadow-sm",
|
|
897
|
-
children: action.label
|
|
898
|
-
},
|
|
899
|
-
action.id
|
|
900
|
-
)) })
|
|
901
|
-
]
|
|
902
|
-
}
|
|
903
|
-
)
|
|
904
|
-
}
|
|
905
|
-
),
|
|
906
|
-
/* @__PURE__ */ jsx("p", { className: "mt-4 text-center text-xs text-muted-foreground", children: "Dados de exemplo \u2014 nenhum registro real foi usado." })
|
|
907
|
-
] })
|
|
908
|
-
] }) : tab === "test" ? /* @__PURE__ */ jsxs(Card, { className: "p-4", children: [
|
|
909
|
-
/* @__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." }),
|
|
910
|
-
/* @__PURE__ */ jsx(
|
|
911
|
-
TestSendStrip,
|
|
912
|
-
{
|
|
913
|
-
eventKey: event.name,
|
|
914
|
-
channel: message.channel,
|
|
915
|
-
placeholders: message.placeholders,
|
|
916
|
-
template: message.channel === "email" ? { subject: current.subject, body: current.body } : void 0
|
|
917
|
-
}
|
|
918
|
-
)
|
|
919
|
-
] }) : /* @__PURE__ */ jsxs(Card, { className: "space-y-4 p-4", children: [
|
|
920
|
-
hasSubject && /* @__PURE__ */ jsxs("div", { children: [
|
|
921
|
-
/* @__PURE__ */ jsx("label", { className: "mb-1 block text-xs font-medium text-muted-foreground", children: "Assunto" }),
|
|
922
|
-
/* @__PURE__ */ jsx(
|
|
923
|
-
Input,
|
|
924
|
-
{
|
|
925
|
-
value: current.subject,
|
|
926
|
-
onChange: (e) => setDraft({ ...current, subject: e.target.value })
|
|
927
|
-
}
|
|
928
|
-
)
|
|
929
|
-
] }),
|
|
930
|
-
/* @__PURE__ */ jsxs("div", { children: [
|
|
931
|
-
/* @__PURE__ */ jsx("label", { className: "mb-1 block text-xs font-medium text-muted-foreground", children: "Mensagem" }),
|
|
932
|
-
/* @__PURE__ */ jsx(
|
|
933
|
-
Textarea,
|
|
934
|
-
{
|
|
935
|
-
rows: 14,
|
|
936
|
-
value: current.body,
|
|
937
|
-
onChange: (e) => setDraft({ ...current, body: e.target.value }),
|
|
938
|
-
className: "font-mono text-xs leading-relaxed"
|
|
939
|
-
}
|
|
940
|
-
)
|
|
941
|
-
] }),
|
|
942
|
-
message.channel === "whatsapp" && /* @__PURE__ */ jsxs("div", { children: [
|
|
943
|
-
/* @__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" }),
|
|
944
|
-
/* @__PURE__ */ jsx("div", { className: "space-y-2", children: ACTION_CATALOG.map((action) => {
|
|
945
|
-
const active = message.actions.find((a) => a.id === action.id);
|
|
946
|
-
const on = Boolean(active);
|
|
947
|
-
const gated = action.id === "pay" && !canOfferPayment(readiness);
|
|
948
|
-
const blocked = gated && !readinessLoading;
|
|
949
|
-
const labelValue = labelDrafts[action.id] ?? active?.label ?? action.label;
|
|
950
|
-
const commitLabel = () => {
|
|
951
|
-
const next = labelValue.trim();
|
|
952
|
-
setLabelDrafts((d) => {
|
|
953
|
-
const { [action.id]: _, ...rest } = d;
|
|
954
|
-
return rest;
|
|
955
|
-
});
|
|
956
|
-
if (!active || !next || next === active.label) return;
|
|
957
|
-
void patch({
|
|
958
|
-
eventKey: event.name,
|
|
959
|
-
channel: message.channel,
|
|
960
|
-
actions: message.actions.map((a) => a.id === action.id ? { ...a, label: next } : a)
|
|
961
|
-
});
|
|
962
|
-
};
|
|
963
|
-
return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1", children: [
|
|
964
|
-
/* @__PURE__ */ jsx(
|
|
965
|
-
Switch,
|
|
966
|
-
{
|
|
967
|
-
size: "md",
|
|
968
|
-
checked: on,
|
|
969
|
-
disabled: saving || gated,
|
|
970
|
-
onCheckedChange: (next) => void patch({
|
|
971
|
-
eventKey: event.name,
|
|
972
|
-
channel: message.channel,
|
|
973
|
-
actions: nextActions(message.actions, action.id, next)
|
|
974
|
-
}),
|
|
975
|
-
label: on ? "" : action.label
|
|
976
|
-
}
|
|
977
|
-
),
|
|
978
|
-
on && // O texto do botão como a cliente vê. 25 caracteres é o
|
|
979
|
-
// teto da Meta para QUICK_REPLY; mudar o texto de um
|
|
980
|
-
// modelo já aprovado dispara nova aprovação — a
|
|
981
|
-
// pastilha de status acima conta essa história.
|
|
982
|
-
/* @__PURE__ */ jsx("div", { className: "w-36", children: /* @__PURE__ */ jsx(
|
|
983
|
-
Input,
|
|
984
|
-
{
|
|
985
|
-
value: labelValue,
|
|
986
|
-
maxLength: 25,
|
|
987
|
-
disabled: saving,
|
|
988
|
-
"aria-label": `Texto do bot\xE3o ${action.label}`,
|
|
989
|
-
onChange: (e) => setLabelDrafts((d) => ({ ...d, [action.id]: e.target.value })),
|
|
990
|
-
onBlur: commitLabel,
|
|
991
|
-
onKeyDown: (e) => {
|
|
992
|
-
if (e.key === "Enter") e.target.blur();
|
|
993
|
-
},
|
|
994
|
-
className: "h-auto px-2 py-1"
|
|
995
|
-
}
|
|
996
|
-
) }),
|
|
997
|
-
/* @__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 })
|
|
998
|
-
] }, action.id);
|
|
999
|
-
}) })
|
|
1000
|
-
] }),
|
|
1001
|
-
/* @__PURE__ */ jsxs("div", { children: [
|
|
1002
|
-
/* @__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" }),
|
|
1003
|
-
/* @__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)) })
|
|
1004
|
-
] })
|
|
1005
|
-
] })
|
|
1006
|
-
] });
|
|
1007
|
-
}
|
|
1008
|
-
|
|
1009
|
-
// src/lib/connector-automations.ts
|
|
1010
|
-
function connectorAutomationRows(connectors) {
|
|
1011
|
-
const out = [];
|
|
1012
|
-
for (const connector of connectors) {
|
|
1013
|
-
if (connector.state !== "connected") continue;
|
|
1014
|
-
for (const auto of connector.definition?.managedAutomations ?? []) {
|
|
1015
|
-
out.push({
|
|
1016
|
-
connectorId: connector.id,
|
|
1017
|
-
connectorName: connector.name,
|
|
1018
|
-
hostPluginId: connector.hostPluginId,
|
|
1019
|
-
icon: connector.icon,
|
|
1020
|
-
logoUrl: connector.logoUrl,
|
|
1021
|
-
eventKey: auto.eventKey,
|
|
1022
|
-
label: auto.label,
|
|
1023
|
-
optional: auto.optional ?? false,
|
|
1024
|
-
...connector.definition?.listDeliveries ? { listDeliveries: connector.definition.listDeliveries.bind(connector.definition) } : {}
|
|
1025
|
-
});
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
return out;
|
|
1029
|
-
}
|
|
1030
|
-
function groupConnectorAutomations(rows) {
|
|
1031
|
-
const groups = [];
|
|
1032
|
-
for (const row of rows) {
|
|
1033
|
-
let group = groups.find((g) => g.connectorId === row.connectorId);
|
|
1034
|
-
if (!group) {
|
|
1035
|
-
group = {
|
|
1036
|
-
connectorId: row.connectorId,
|
|
1037
|
-
connectorName: row.connectorName,
|
|
1038
|
-
hostPluginId: row.hostPluginId,
|
|
1039
|
-
icon: row.icon,
|
|
1040
|
-
logoUrl: row.logoUrl,
|
|
1041
|
-
items: []
|
|
1042
|
-
};
|
|
1043
|
-
groups.push(group);
|
|
1044
|
-
}
|
|
1045
|
-
group.items.push(row);
|
|
1046
|
-
}
|
|
1047
|
-
return groups;
|
|
1048
|
-
}
|
|
1049
|
-
function ConnectorAutomations({ rows }) {
|
|
1050
|
-
if (rows.length === 0) return null;
|
|
1051
|
-
return /* @__PURE__ */ jsx(Fragment, { children: groupConnectorAutomations(rows).map((group) => {
|
|
1052
|
-
const href = connectorRoute({ hostPluginId: group.hostPluginId });
|
|
1053
|
-
return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
|
|
1054
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: group.connectorName }),
|
|
1055
|
-
group.items.map((row) => /* @__PURE__ */ jsx(
|
|
1056
|
-
AutomationCard,
|
|
1057
|
-
{
|
|
1058
|
-
row,
|
|
1059
|
-
group,
|
|
1060
|
-
href
|
|
1061
|
-
},
|
|
1062
|
-
`${group.connectorId}:${row.eventKey}`
|
|
1063
|
-
))
|
|
1064
|
-
] }, group.connectorId);
|
|
1065
|
-
}) });
|
|
1066
|
-
}
|
|
1067
|
-
function AutomationCard({
|
|
1068
|
-
row,
|
|
1069
|
-
group,
|
|
1070
|
-
href
|
|
1071
|
-
}) {
|
|
1072
|
-
const [open, setOpen] = React4__default.useState(false);
|
|
1073
|
-
return /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
|
|
1074
|
-
/* @__PURE__ */ jsxs(
|
|
1075
|
-
"div",
|
|
1076
|
-
{
|
|
1077
|
-
role: "button",
|
|
1078
|
-
tabIndex: 0,
|
|
1079
|
-
onClick: () => adminNavigateTo(href),
|
|
1080
|
-
onKeyDown: (e) => {
|
|
1081
|
-
if (e.key === "Enter" || e.key === " ") {
|
|
1082
|
-
e.preventDefault();
|
|
1083
|
-
adminNavigateTo(href);
|
|
1084
|
-
}
|
|
1085
|
-
},
|
|
1086
|
-
className: "flex cursor-pointer items-start gap-4 p-4 transition-colors hover:bg-muted/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
|
1087
|
-
children: [
|
|
1088
|
-
/* @__PURE__ */ jsx(
|
|
1089
|
-
ConnectorMark,
|
|
1090
|
-
{
|
|
1091
|
-
connector: {
|
|
1092
|
-
id: group.connectorId,
|
|
1093
|
-
name: group.connectorName,
|
|
1094
|
-
icon: group.icon,
|
|
1095
|
-
logoUrl: group.logoUrl
|
|
1096
|
-
},
|
|
1097
|
-
size: "sm"
|
|
1098
|
-
}
|
|
1099
|
-
),
|
|
1100
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
|
|
1101
|
-
/* @__PURE__ */ jsx("p", { className: "font-medium", children: row.label }),
|
|
1102
|
-
/* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
|
|
1103
|
-
"Quando ",
|
|
1104
|
-
/* @__PURE__ */ jsx("code", { className: "font-mono text-xs", children: row.eventKey }),
|
|
1105
|
-
" acontece aqui."
|
|
1106
|
-
] })
|
|
1107
|
-
] }),
|
|
1108
|
-
/* @__PURE__ */ jsx("span", { className: "shrink-0 pt-0.5 text-right text-xs text-muted-foreground", children: row.optional ? `Opcional \u2014 desligue em ${group.connectorName}` : `Ligada pela integra\xE7\xE3o \xB7 sai ao desconectar ${group.connectorName}` })
|
|
1109
|
-
]
|
|
1110
|
-
}
|
|
1111
|
-
),
|
|
1112
|
-
row.listDeliveries && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1113
|
-
/* @__PURE__ */ jsxs(
|
|
1114
|
-
Button,
|
|
1115
|
-
{
|
|
1116
|
-
variant: "bare",
|
|
1117
|
-
size: "bare",
|
|
1118
|
-
type: "button",
|
|
1119
|
-
onClick: () => setOpen(!open),
|
|
1120
|
-
"aria-expanded": open,
|
|
1121
|
-
className: "flex w-full items-center justify-start gap-2 rounded-none border-t border-border px-4 py-2 text-left font-normal transition-colors hover:bg-muted/40",
|
|
1122
|
-
children: [
|
|
1123
|
-
/* @__PURE__ */ jsx(ChevronRight, { className: `h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${open ? "rotate-90" : ""}` }),
|
|
1124
|
-
/* @__PURE__ */ jsxs("span", { className: "text-xs font-medium", children: [
|
|
1125
|
-
"O que j\xE1 foi para o ",
|
|
1126
|
-
group.connectorName
|
|
1127
|
-
] })
|
|
1128
|
-
]
|
|
1129
|
-
}
|
|
1130
|
-
),
|
|
1131
|
-
open && /* @__PURE__ */ jsx("div", { className: "border-t border-border p-4", children: /* @__PURE__ */ jsx(
|
|
1132
|
-
ConnectorDeliveries,
|
|
1133
|
-
{
|
|
1134
|
-
load: (options) => row.listDeliveries({ ...options, eventKey: row.eventKey }),
|
|
1135
|
-
providerName: group.connectorName
|
|
1136
|
-
}
|
|
1137
|
-
) })
|
|
1138
|
-
] })
|
|
1139
|
-
] });
|
|
1140
|
-
}
|
|
1141
|
-
var CONFIGURE_TOOL = {
|
|
1142
|
-
id: "automations.configure",
|
|
1143
|
-
name: "configureAutomation",
|
|
1144
|
-
description: "Turns an automation on or off, and/or rewrites its message. Use the `event` and `channel` values exactly as they appear in the surface state. Placeholders must come from that automation's own list \u2014 an invented one renders as literal text in a message a customer reads. To review several, call once per automation.",
|
|
1145
|
-
icon: "Zap",
|
|
1146
|
-
mode: "persist",
|
|
1147
|
-
execution: { plane: "client" },
|
|
1148
|
-
category: "Automations",
|
|
1149
|
-
parameters: {
|
|
1150
|
-
type: "object",
|
|
1151
|
-
properties: {
|
|
1152
|
-
event: { type: "string", description: "Event key from the surface state." },
|
|
1153
|
-
channel: { type: "string", description: "Channel of that automation (email | whatsapp | sms | in_app)." },
|
|
1154
|
-
enabled: { type: "boolean", description: "Turn it on or off. Omit to leave as is." },
|
|
1155
|
-
subject: { type: "string", description: "New subject. Email only." },
|
|
1156
|
-
body: { type: "string", description: "New message body." }
|
|
1157
|
-
},
|
|
1158
|
-
required: ["event", "channel"]
|
|
1159
|
-
}
|
|
1160
|
-
};
|
|
1161
|
-
var ASK_AI_ACTION = {
|
|
1162
|
-
label: "Criar com IA",
|
|
1163
|
-
hint: "O que revisar nas automa\xE7\xF5es\u2026",
|
|
1164
|
-
intro: {
|
|
1165
|
-
role: "setup",
|
|
1166
|
-
persona: "Redator das automa\xE7\xF5es",
|
|
1167
|
-
pitch: "Diga o que revisar nas automa\xE7\xF5es.",
|
|
1168
|
-
description: "Vejo todas as automa\xE7\xF5es deste app, quais est\xE3o ligadas e o texto de cada uma. Posso ligar, desligar e reescrever \u2014 em uma ou em v\xE1rias de uma vez. Voc\xEA confirma cada mudan\xE7a.",
|
|
1169
|
-
suggestions: [
|
|
1170
|
-
{ label: "Revise as mensagens de pedido no tom da minha marca" },
|
|
1171
|
-
{ label: "Ligue as automa\xE7\xF5es de entrega" },
|
|
1172
|
-
{ label: "Deixe as mensagens de WhatsApp mais curtas" }
|
|
1173
|
-
]
|
|
1174
|
-
}
|
|
1175
|
-
};
|
|
1176
|
-
var CHANNEL_ICON2 = {
|
|
1177
|
-
email: Mail,
|
|
1178
|
-
// The brand glyph, not a generic bubble: in a list of channels, WhatsApp
|
|
1179
|
-
// is recognized by its mark before its label.
|
|
1180
|
-
whatsapp: WhatsAppIcon,
|
|
1181
|
-
sms: Smartphone,
|
|
1182
|
-
push: MessageSquare,
|
|
1183
|
-
webchat: MessageSquare
|
|
1184
|
-
};
|
|
1185
|
-
var CHANNEL_LABEL2 = {
|
|
1186
|
-
email: "E-mail",
|
|
1187
|
-
whatsapp: "WhatsApp",
|
|
1188
|
-
sms: "SMS",
|
|
1189
|
-
push: "Push",
|
|
1190
|
-
webchat: "Chat"
|
|
1191
|
-
};
|
|
1192
|
-
var KIND_TABS = [
|
|
1193
|
-
{ value: "all", label: "Todos", icon: Zap },
|
|
1194
|
-
{ value: "transactional", label: "Transacionais", icon: Receipt },
|
|
1195
|
-
{ value: "marketing", label: "Marketing", icon: Megaphone }
|
|
1196
|
-
];
|
|
1197
|
-
var KIND_HINT = {
|
|
1198
|
-
all: "Tudo que o produto sabe enviar, por qualquer canal.",
|
|
1199
|
-
transactional: "Disparados por uma a\xE7\xE3o da pessoa. N\xE3o precisam de opt-in.",
|
|
1200
|
-
marketing: "Iniciativa da empresa. S\xF3 para quem aceitou receber."
|
|
1201
|
-
};
|
|
1202
|
-
function iconFor(name) {
|
|
1203
|
-
if (!name) return Zap;
|
|
1204
|
-
const icons = LucideIcons;
|
|
1205
|
-
return icons[name] ?? Zap;
|
|
1206
|
-
}
|
|
1207
|
-
function readSelection(basePath) {
|
|
1208
|
-
const hash = window.location.hash.slice(1) || "/";
|
|
1209
|
-
if (!hash.startsWith(basePath + "/")) return null;
|
|
1210
|
-
const [eventKey, channel] = hash.slice(basePath.length + 1).split("/");
|
|
1211
|
-
if (!eventKey || !channel) return null;
|
|
1212
|
-
return { eventKey, channel };
|
|
1213
|
-
}
|
|
1214
|
-
function AutomationsList({ store: store2, variant = "page", basePath = "/automations" }) {
|
|
1215
|
-
const tenantId = useOrganizationStoreLike();
|
|
1216
|
-
const runtime = usePluginRuntimeOptional();
|
|
1217
|
-
const [messages, setMessages] = React4__default.useState(null);
|
|
1218
|
-
const [kind, setKind] = React4__default.useState("all");
|
|
1219
|
-
const { connectors } = useConnectors({ includeGrants: false, includeCatalog: false });
|
|
1220
|
-
const owned = React4__default.useMemo(() => connectorAutomationRows(connectors ?? []), [connectors]);
|
|
1221
|
-
const providerTemplates = useProviderTemplates();
|
|
1222
|
-
const [selected, setSelected] = React4__default.useState(() => readSelection(basePath));
|
|
1223
|
-
React4__default.useEffect(() => {
|
|
1224
|
-
const sync = () => setSelected(readSelection(basePath));
|
|
1225
|
-
sync();
|
|
1226
|
-
window.addEventListener("hashchange", sync);
|
|
1227
|
-
return () => window.removeEventListener("hashchange", sync);
|
|
1228
|
-
}, [basePath]);
|
|
1229
|
-
const reload = React4__default.useCallback(async () => {
|
|
1230
|
-
let overrides = [];
|
|
1231
|
-
try {
|
|
1232
|
-
overrides = await store2.list(tenantId);
|
|
1233
|
-
} catch (err) {
|
|
1234
|
-
console.warn("[automations] could not load template overrides; showing defaults", err);
|
|
1235
|
-
}
|
|
1236
|
-
setMessages(resolveMessages(overrides, runtime?.events ?? []));
|
|
1237
|
-
}, [store2, tenantId, runtime]);
|
|
1238
|
-
React4__default.useEffect(() => {
|
|
1239
|
-
void reload();
|
|
1240
|
-
}, [reload]);
|
|
1241
|
-
const surfaceRef = React4__default.useRef({ messages, store: store2, tenantId, reload, basePath });
|
|
1242
|
-
surfaceRef.current = { messages, store: store2, tenantId, reload, basePath };
|
|
1243
|
-
const agentSurface = React4__default.useMemo(() => ({
|
|
1244
|
-
id: "automations.list",
|
|
1245
|
-
pluginId: "automations",
|
|
1246
|
-
instructions: "The user is on the automations list. `automations` in the surface state is the complete set \u2014 use each entry's `event` and `channel` verbatim, and each entry's own `placeholders` when rewriting its text. Call configureAutomation once per automation you change; say afterwards which ones you touched.",
|
|
1247
|
-
describe: () => {
|
|
1248
|
-
const o = surfaceRef.current;
|
|
1249
|
-
return {
|
|
1250
|
-
title: "Automa\xE7\xF5es",
|
|
1251
|
-
state: {
|
|
1252
|
-
automations: (o.messages ?? []).map((m) => ({
|
|
1253
|
-
event: m.event.name,
|
|
1254
|
-
title: m.event.title,
|
|
1255
|
-
channel: m.channel,
|
|
1256
|
-
enabled: m.enabled,
|
|
1257
|
-
customized: Boolean(m.customized),
|
|
1258
|
-
subject: m.subject,
|
|
1259
|
-
body: m.body,
|
|
1260
|
-
// `fields` é o contrato do evento — os mesmos descritores que viram
|
|
1261
|
-
// as merge fields do editor. É de lá que saem os placeholders.
|
|
1262
|
-
placeholders: (m.event.fields ?? []).map((f) => `{{${f.name}}}`)
|
|
1263
|
-
}))
|
|
1264
|
-
}
|
|
1265
|
-
};
|
|
1266
|
-
},
|
|
1267
|
-
tools: [{
|
|
1268
|
-
tool: CONFIGURE_TOOL,
|
|
1269
|
-
execute: async (args) => {
|
|
1270
|
-
const o = surfaceRef.current;
|
|
1271
|
-
const found = (o.messages ?? []).find(
|
|
1272
|
-
(m) => m.event.name === args.event && m.channel === args.channel
|
|
1273
|
-
);
|
|
1274
|
-
if (!found) {
|
|
1275
|
-
return {
|
|
1276
|
-
ok: false,
|
|
1277
|
-
error: "unknown_automation",
|
|
1278
|
-
available: (o.messages ?? []).map((m) => `${m.event.name}/${m.channel}`)
|
|
1279
|
-
};
|
|
1280
|
-
}
|
|
1281
|
-
try {
|
|
1282
|
-
await o.store.upsert({
|
|
1283
|
-
eventKey: found.event.name,
|
|
1284
|
-
channel: found.channel,
|
|
1285
|
-
...args.enabled === void 0 ? {} : { enabled: Boolean(args.enabled) },
|
|
1286
|
-
...args.subject === void 0 ? {} : { subject: String(args.subject) },
|
|
1287
|
-
...args.body === void 0 ? {} : { body: String(args.body) }
|
|
1288
|
-
}, o.tenantId);
|
|
1289
|
-
await o.reload();
|
|
1290
|
-
return {
|
|
1291
|
-
ok: true,
|
|
1292
|
-
event: found.event.name,
|
|
1293
|
-
channel: found.channel,
|
|
1294
|
-
ref: {
|
|
1295
|
-
id: `${found.event.name}/${found.channel}`,
|
|
1296
|
-
label: `${found.event.title ?? found.event.name} \u2014 ${CHANNEL_LABEL2[found.channel] ?? found.channel}`,
|
|
1297
|
-
path: `${o.basePath}/${encodeURIComponent(found.event.name)}/${found.channel}`
|
|
1298
|
-
}
|
|
1299
|
-
};
|
|
1300
|
-
} catch (e) {
|
|
1301
|
-
return { ok: false, error: errorMessage(e) };
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
}]
|
|
1305
|
-
}), []);
|
|
1306
|
-
useAgentSurface(agentSurface);
|
|
1307
|
-
const toggle = async (m, enabled) => {
|
|
1308
|
-
setMessages((prev) => prev?.map((x) => x.event.name === m.event.name && x.channel === m.channel ? { ...x, enabled } : x) ?? null);
|
|
1309
|
-
try {
|
|
1310
|
-
await store2.upsert({ eventKey: m.event.name, channel: m.channel, enabled }, tenantId);
|
|
1311
|
-
await reload();
|
|
1312
|
-
} catch (err) {
|
|
1313
|
-
console.warn("[automations] toggle failed", err);
|
|
1314
|
-
toast.error("N\xE3o foi poss\xEDvel salvar");
|
|
1315
|
-
await reload();
|
|
1316
|
-
}
|
|
1317
|
-
};
|
|
1318
|
-
const visible = (messages ?? []).filter((m) => kind === "all" || m.kind === kind);
|
|
1319
|
-
const ownedVisible = kind === "all" ? owned : [];
|
|
1320
|
-
const activeCount = (messages ?? []).filter((m) => m.enabled).length + owned.length;
|
|
1321
|
-
const totalCount = (messages?.length ?? 0) + owned.length;
|
|
1322
|
-
const groups = [];
|
|
1323
|
-
for (const m of visible) {
|
|
1324
|
-
let g = groups.find((x) => x.module === m.event.pluginId);
|
|
1325
|
-
if (!g) {
|
|
1326
|
-
g = { module: m.event.pluginId, label: m.event.pluginName, items: [] };
|
|
1327
|
-
groups.push(g);
|
|
1328
|
-
}
|
|
1329
|
-
g.items.push(m);
|
|
1330
|
-
}
|
|
1331
|
-
const counter = messages !== null && /* @__PURE__ */ jsxs("span", { className: "text-sm text-muted-foreground", children: [
|
|
1332
|
-
activeCount,
|
|
1333
|
-
" de ",
|
|
1334
|
-
totalCount,
|
|
1335
|
-
" automa\xE7\xF5es ativas"
|
|
1336
|
-
] });
|
|
1337
|
-
return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
|
|
1338
|
-
variant !== "panel" ? /* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
|
|
1339
|
-
PageActions,
|
|
1340
|
-
{
|
|
1341
|
-
actions: [{
|
|
1342
|
-
id: "automations-ai",
|
|
1343
|
-
label: ASK_AI_ACTION.label,
|
|
1344
|
-
icon: WandSparkles,
|
|
1345
|
-
ai: true,
|
|
1346
|
-
intent: "primary",
|
|
1347
|
-
creates: true,
|
|
1348
|
-
onSelect: () => askAI({ hint: ASK_AI_ACTION.hint, intro: ASK_AI_ACTION.intro })
|
|
1349
|
-
}]
|
|
1350
|
-
}
|
|
1351
|
-
) }) : null,
|
|
1352
|
-
variant === "panel" ? /* @__PURE__ */ jsx(
|
|
1353
|
-
SettingsTabs,
|
|
1354
|
-
{
|
|
1355
|
-
tabs: KIND_TABS.map((t) => ({ id: t.value, label: t.label, IconComp: t.icon })),
|
|
1356
|
-
value: kind,
|
|
1357
|
-
onChange: (id) => setKind(id),
|
|
1358
|
-
"aria-label": "Automa\xE7\xF5es",
|
|
1359
|
-
actions: counter
|
|
1360
|
-
}
|
|
1361
|
-
) : (
|
|
1362
|
-
/* Mesma faixa das listas e da sub-nav de módulo. */
|
|
1363
|
-
/* @__PURE__ */ jsx(
|
|
1364
|
-
PageTabs,
|
|
1365
|
-
{
|
|
1366
|
-
className: "mb-0",
|
|
1367
|
-
tabs: KIND_TABS.map((t) => ({ value: t.value, label: t.label, icon: t.icon })),
|
|
1368
|
-
value: kind,
|
|
1369
|
-
onChange: setKind,
|
|
1370
|
-
"aria-label": "Automa\xE7\xF5es",
|
|
1371
|
-
actions: counter
|
|
1372
|
-
}
|
|
1373
|
-
)
|
|
1374
|
-
),
|
|
1375
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: KIND_HINT[kind] }),
|
|
1376
|
-
messages === null ? /* @__PURE__ */ jsx("div", { className: "space-y-3", children: Array.from({ length: 4 }).map((_, i) => /* @__PURE__ */ jsxs(Card, { className: "p-4", children: [
|
|
1377
|
-
/* @__PURE__ */ jsx("div", { className: "h-4 w-40 animate-pulse rounded bg-muted" }),
|
|
1378
|
-
/* @__PURE__ */ jsx("div", { className: "mt-2 h-3 w-64 animate-pulse rounded bg-muted" })
|
|
1379
|
-
] }, i)) }) : groups.length === 0 && ownedVisible.length === 0 ? /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-1 p-12 text-center", children: [
|
|
1380
|
-
/* @__PURE__ */ jsx(Zap, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
|
|
1381
|
-
/* @__PURE__ */ jsx("p", { className: "text-base font-semibold", children: "Nenhuma automa\xE7\xE3o nesta aba" }),
|
|
1382
|
-
/* @__PURE__ */ jsx("p", { className: "max-w-sm text-sm text-muted-foreground", children: "Os eventos v\xEAm dos m\xF3dulos instalados \u2014 a loja traz os do pedido, o CRM os do funil." })
|
|
1383
|
-
] }) : groups.map((group) => /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
|
|
1384
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: group.label }),
|
|
1385
|
-
group.items.map((m) => {
|
|
1386
|
-
const Icon = iconFor(m.event.icon ?? m.event.pluginIcon);
|
|
1387
|
-
const ChannelIcon = CHANNEL_ICON2[m.channel];
|
|
1388
|
-
const href = `${basePath}/${encodeURIComponent(m.event.name)}/${m.channel}`;
|
|
1389
|
-
const isOpen = selected != null && decodeURIComponent(selected.eventKey) === m.event.name && selected.channel === m.channel;
|
|
1390
|
-
return /* @__PURE__ */ jsx(
|
|
1391
|
-
Card,
|
|
1392
|
-
{
|
|
1393
|
-
role: "button",
|
|
1394
|
-
tabIndex: 0,
|
|
1395
|
-
"aria-current": isOpen || void 0,
|
|
1396
|
-
onClick: () => adminNavigateTo(href),
|
|
1397
|
-
onKeyDown: (e) => {
|
|
1398
|
-
if (e.key === "Enter" || e.key === " ") {
|
|
1399
|
-
e.preventDefault();
|
|
1400
|
-
adminNavigateTo(href);
|
|
1401
|
-
}
|
|
1402
|
-
},
|
|
1403
|
-
style: isOpen ? { outline: "2px solid hsl(var(--primary) / 0.65)", outlineOffset: "-2px" } : void 0,
|
|
1404
|
-
className: `cursor-pointer overflow-hidden transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${isOpen ? "" : "hover:border-primary/40"}`,
|
|
1405
|
-
children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-4 p-4", children: [
|
|
1406
|
-
/* @__PURE__ */ jsx("span", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground", children: /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }) }),
|
|
1407
|
-
/* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
|
|
1408
|
-
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
1409
|
-
/* @__PURE__ */ jsx("p", { className: "font-medium", children: m.override?.name ?? m.event.title ?? m.event.name }),
|
|
1410
|
-
/* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground", children: [
|
|
1411
|
-
/* @__PURE__ */ jsx(ChannelIcon, { className: "h-3 w-3" }),
|
|
1412
|
-
CHANNEL_LABEL2[m.channel]
|
|
1413
|
-
] }),
|
|
1414
|
-
m.customized && /* @__PURE__ */ jsx("span", { className: "rounded-full bg-primary/10 px-2 py-0.5 text-[11px] text-primary", children: "personalizado" }),
|
|
1415
|
-
/* @__PURE__ */ jsx(
|
|
1416
|
-
ProviderTemplateBadge,
|
|
1417
|
-
{
|
|
1418
|
-
approval: providerApprovalFor(providerTemplates, m.event.name, m.channel)
|
|
1419
|
-
}
|
|
1420
|
-
)
|
|
1421
|
-
] }),
|
|
1422
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: m.event.description }),
|
|
1423
|
-
/* @__PURE__ */ jsxs("div", { className: "mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", children: [
|
|
1424
|
-
/* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
|
|
1425
|
-
/* @__PURE__ */ jsx(Zap, { className: "h-3 w-3" }),
|
|
1426
|
-
m.event.trigger
|
|
1427
|
-
] }),
|
|
1428
|
-
m.subject && /* @__PURE__ */ jsxs("span", { className: "truncate", children: [
|
|
1429
|
-
"Assunto: ",
|
|
1430
|
-
m.subject
|
|
1431
|
-
] })
|
|
1432
|
-
] })
|
|
1433
|
-
] }),
|
|
1434
|
-
/* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-3", children: [
|
|
1435
|
-
/* @__PURE__ */ jsx(
|
|
1436
|
-
Switch,
|
|
1437
|
-
{
|
|
1438
|
-
checked: m.enabled,
|
|
1439
|
-
onCheckedChange: (next) => void toggle(m, next),
|
|
1440
|
-
label: m.enabled ? "Ativo" : "Inativo",
|
|
1441
|
-
"aria-label": `${m.event.title} \u2014 ${CHANNEL_LABEL2[m.channel]}`
|
|
1442
|
-
}
|
|
1443
|
-
),
|
|
1444
|
-
/* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4 text-muted-foreground" })
|
|
1445
|
-
] })
|
|
1446
|
-
] })
|
|
1447
|
-
},
|
|
1448
|
-
`${m.event.name}:${m.channel}`
|
|
1449
|
-
);
|
|
1450
|
-
})
|
|
1451
|
-
] }, group.module)),
|
|
1452
|
-
messages !== null && /* @__PURE__ */ jsx(ConnectorAutomations, { rows: ownedVisible }),
|
|
1453
|
-
selected && /* @__PURE__ */ jsx(
|
|
1454
|
-
RightRailPage,
|
|
1455
|
-
{
|
|
1456
|
-
title: (messages ?? []).find(
|
|
1457
|
-
(m) => m.event.name === decodeURIComponent(selected.eventKey) && m.channel === selected.channel
|
|
1458
|
-
)?.event.title ?? "Automa\xE7\xE3o",
|
|
1459
|
-
open: true,
|
|
1460
|
-
onClose: () => adminNavigateTo(basePath),
|
|
1461
|
-
width: "max-w-2xl",
|
|
1462
|
-
children: /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto p-4", children: /* @__PURE__ */ jsx(
|
|
1463
|
-
AutomationDetailPage,
|
|
1464
|
-
{
|
|
1465
|
-
eventKey: selected.eventKey,
|
|
1466
|
-
channel: selected.channel,
|
|
1467
|
-
store: store2,
|
|
1468
|
-
backTo: basePath,
|
|
1469
|
-
embedded: true
|
|
1470
|
-
}
|
|
1471
|
-
) })
|
|
1472
|
-
}
|
|
1473
|
-
)
|
|
1474
|
-
] });
|
|
1475
|
-
}
|
|
1476
8
|
var TABLE = "plg_automations_templates";
|
|
1477
9
|
function rowToTemplate(row) {
|
|
1478
10
|
return {
|
|
@@ -1532,503 +64,6 @@ function createSupabaseTemplateStore() {
|
|
|
1532
64
|
}
|
|
1533
65
|
};
|
|
1534
66
|
}
|
|
1535
|
-
function CadenceComposer({ open, onClose, onCreate }) {
|
|
1536
|
-
const t = useTranslation();
|
|
1537
|
-
const runtime = usePluginRuntimeOptional();
|
|
1538
|
-
const events = runtime?.events ?? [];
|
|
1539
|
-
const [name, setName] = React4__default.useState("");
|
|
1540
|
-
const [entryEvent, setEntryEvent] = React4__default.useState("");
|
|
1541
|
-
const [exitEvent, setExitEvent] = React4__default.useState("");
|
|
1542
|
-
const [saving, setSaving] = React4__default.useState(false);
|
|
1543
|
-
React4__default.useEffect(() => {
|
|
1544
|
-
if (!open) return;
|
|
1545
|
-
setName("");
|
|
1546
|
-
setExitEvent("");
|
|
1547
|
-
setEntryEvent(events.find((e) => e.name === "crm.lead_created")?.name ?? events[0]?.name ?? "");
|
|
1548
|
-
}, [open]);
|
|
1549
|
-
const entry = events.find((e) => e.name === entryEvent);
|
|
1550
|
-
async function submit() {
|
|
1551
|
-
if (!name.trim() || !entryEvent || saving) return;
|
|
1552
|
-
setSaving(true);
|
|
1553
|
-
try {
|
|
1554
|
-
await onCreate({
|
|
1555
|
-
name: name.trim(),
|
|
1556
|
-
entryEvent,
|
|
1557
|
-
exitEvents: exitEvent ? [exitEvent] : []
|
|
1558
|
-
});
|
|
1559
|
-
onClose();
|
|
1560
|
-
} catch (e) {
|
|
1561
|
-
toast.error(errorMessage(e));
|
|
1562
|
-
} finally {
|
|
1563
|
-
setSaving(false);
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
|
|
1567
|
-
if (!o) onClose();
|
|
1568
|
-
}, children: /* @__PURE__ */ jsxs(ModalContent, { size: "md", children: [
|
|
1569
|
-
/* @__PURE__ */ jsx(ModalHeader, { children: /* @__PURE__ */ jsx(ModalTitle, { children: t("automations.flow.newTitle") }) }),
|
|
1570
|
-
/* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
|
|
1571
|
-
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
1572
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.nameLabel") }),
|
|
1573
|
-
/* @__PURE__ */ jsx(Input, { value: name, onChange: (e) => setName(e.target.value), placeholder: t("automations.flow.namePlaceholder") })
|
|
1574
|
-
] }),
|
|
1575
|
-
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
1576
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.entryLabel") }),
|
|
1577
|
-
events.length > 0 ? /* @__PURE__ */ jsxs(Select, { value: entryEvent, onValueChange: setEntryEvent, children: [
|
|
1578
|
-
/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("automations.flow.entryPlaceholder") }) }),
|
|
1579
|
-
/* @__PURE__ */ jsx(SelectContent, { children: events.map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name)) })
|
|
1580
|
-
] }) : /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground", children: t("automations.flow.noEvents") }),
|
|
1581
|
-
entry?.trigger && /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: entry.trigger })
|
|
1582
|
-
] }),
|
|
1583
|
-
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
1584
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.exitLabel") }),
|
|
1585
|
-
/* @__PURE__ */ jsxs(Select, { value: exitEvent || "__none__", onValueChange: (v) => setExitEvent(v === "__none__" ? "" : v), children: [
|
|
1586
|
-
/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
1587
|
-
/* @__PURE__ */ jsxs(SelectContent, { children: [
|
|
1588
|
-
/* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t("automations.flow.exitNone") }),
|
|
1589
|
-
events.filter((e) => e.name !== entryEvent).map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name))
|
|
1590
|
-
] })
|
|
1591
|
-
] }),
|
|
1592
|
-
/* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: t("automations.flow.exitHint") })
|
|
1593
|
-
] }),
|
|
1594
|
-
/* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2 rounded-lg bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground", children: [
|
|
1595
|
-
/* @__PURE__ */ jsx(Workflow, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }),
|
|
1596
|
-
t("automations.flow.bornOffHint")
|
|
1597
|
-
] })
|
|
1598
|
-
] }),
|
|
1599
|
-
/* @__PURE__ */ jsxs(ModalFooter, { children: [
|
|
1600
|
-
/* @__PURE__ */ jsx(Button, { variant: "outline", onClick: onClose, children: t("common.cancel") }),
|
|
1601
|
-
/* @__PURE__ */ jsx(Button, { onClick: () => {
|
|
1602
|
-
void submit();
|
|
1603
|
-
}, disabled: saving || !name.trim() || !entryEvent, children: t("automations.flow.create") })
|
|
1604
|
-
] })
|
|
1605
|
-
] }) });
|
|
1606
|
-
}
|
|
1607
|
-
var FLOWS = "plg_automations_flows";
|
|
1608
|
-
var STEPS = "plg_automations_flow_steps";
|
|
1609
|
-
var ENROLLMENTS = "plg_automations_enrollments";
|
|
1610
|
-
var STEP_STATS = "v_automations_flow_steps";
|
|
1611
|
-
function rowToFlow(r) {
|
|
1612
|
-
return {
|
|
1613
|
-
id: r.id,
|
|
1614
|
-
tenantId: r.tenant_id,
|
|
1615
|
-
name: r.name,
|
|
1616
|
-
description: r.description ?? null,
|
|
1617
|
-
entryEvent: r.entry_event,
|
|
1618
|
-
exitEvents: Array.isArray(r.exit_events) ? r.exit_events : [],
|
|
1619
|
-
isActive: r.is_active === true,
|
|
1620
|
-
createdAt: r.created_at,
|
|
1621
|
-
updatedAt: r.updated_at ?? r.created_at
|
|
1622
|
-
};
|
|
1623
|
-
}
|
|
1624
|
-
function rowToStepStats(r) {
|
|
1625
|
-
return {
|
|
1626
|
-
id: r.step_id ?? r.id,
|
|
1627
|
-
flowId: r.flow_id,
|
|
1628
|
-
position: r.position,
|
|
1629
|
-
delayMinutes: r.delay_minutes ?? 0,
|
|
1630
|
-
kind: r.kind === "task" ? "task" : "message",
|
|
1631
|
-
templateKey: r.template_key ?? null,
|
|
1632
|
-
channel: r.channel ?? null,
|
|
1633
|
-
taskTitle: r.task_title ?? null,
|
|
1634
|
-
taskDueDays: r.task_due_days ?? null,
|
|
1635
|
-
queued: Number(r.queued ?? 0),
|
|
1636
|
-
sent: Number(r.sent ?? 0),
|
|
1637
|
-
blocked: Number(r.blocked ?? 0),
|
|
1638
|
-
failed: Number(r.failed ?? 0),
|
|
1639
|
-
cancelled: Number(r.cancelled ?? 0)
|
|
1640
|
-
};
|
|
1641
|
-
}
|
|
1642
|
-
function nextPosition(steps) {
|
|
1643
|
-
if (steps.length === 0) return 10;
|
|
1644
|
-
return Math.max(...steps.map((s) => s.position)) + 10;
|
|
1645
|
-
}
|
|
1646
|
-
function describeDelay(minutes, t) {
|
|
1647
|
-
if (minutes <= 0) return t("automations.flow.delayNow");
|
|
1648
|
-
if (minutes % 1440 === 0) return t("automations.flow.delayDays", { count: String(minutes / 1440) });
|
|
1649
|
-
if (minutes % 60 === 0) return t("automations.flow.delayHours", { count: String(minutes / 60) });
|
|
1650
|
-
return t("automations.flow.delayMinutes", { count: String(minutes) });
|
|
1651
|
-
}
|
|
1652
|
-
function createSupabaseFlowStore() {
|
|
1653
|
-
function client() {
|
|
1654
|
-
const supabase = getSupabaseClientOptional();
|
|
1655
|
-
if (!supabase) throw new Error("Supabase not initialized");
|
|
1656
|
-
return supabase;
|
|
1657
|
-
}
|
|
1658
|
-
const store2 = {
|
|
1659
|
-
async listFlows() {
|
|
1660
|
-
const { data, error } = await client().from(FLOWS).select("*").order("name");
|
|
1661
|
-
if (error) throw new Error(error.message);
|
|
1662
|
-
return (data ?? []).map(rowToFlow);
|
|
1663
|
-
},
|
|
1664
|
-
async saveFlow(input) {
|
|
1665
|
-
const row = {
|
|
1666
|
-
name: input.name,
|
|
1667
|
-
description: input.description ?? null,
|
|
1668
|
-
entry_event: input.entryEvent,
|
|
1669
|
-
exit_events: input.exitEvents ?? []
|
|
1670
|
-
};
|
|
1671
|
-
if (input.id) {
|
|
1672
|
-
const { data: data2, error: error2 } = await client().from(FLOWS).update(row).eq("id", input.id).select().single();
|
|
1673
|
-
if (error2) throw new Error(error2.message);
|
|
1674
|
-
return rowToFlow(data2);
|
|
1675
|
-
}
|
|
1676
|
-
row.tenant_id = getActiveTenantId();
|
|
1677
|
-
const { data, error } = await client().from(FLOWS).insert(row).select().single();
|
|
1678
|
-
if (error) throw new Error(error.message);
|
|
1679
|
-
return rowToFlow(data);
|
|
1680
|
-
},
|
|
1681
|
-
async setFlowActive(id, isActive) {
|
|
1682
|
-
const { error } = await client().from(FLOWS).update({ is_active: isActive, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id);
|
|
1683
|
-
if (error) throw new Error(error.message);
|
|
1684
|
-
},
|
|
1685
|
-
async deleteFlow(id) {
|
|
1686
|
-
const { error } = await client().from(FLOWS).delete().eq("id", id);
|
|
1687
|
-
if (error) throw new Error(error.message);
|
|
1688
|
-
},
|
|
1689
|
-
async listSteps(flowId) {
|
|
1690
|
-
const { data, error } = await client().from(STEP_STATS).select("*").eq("flow_id", flowId).order("position");
|
|
1691
|
-
if (error) throw new Error(error.message);
|
|
1692
|
-
return (data ?? []).map(rowToStepStats);
|
|
1693
|
-
},
|
|
1694
|
-
async saveStep(flowId, input) {
|
|
1695
|
-
const row = {
|
|
1696
|
-
flow_id: flowId,
|
|
1697
|
-
position: input.position,
|
|
1698
|
-
delay_minutes: input.delayMinutes ?? 0,
|
|
1699
|
-
kind: input.kind ?? "message",
|
|
1700
|
-
template_key: input.kind === "task" ? null : input.templateKey ?? null,
|
|
1701
|
-
channel: input.kind === "task" ? null : input.channel ?? null,
|
|
1702
|
-
task_title: input.kind === "task" ? input.taskTitle ?? null : null,
|
|
1703
|
-
task_due_days: input.kind === "task" ? input.taskDueDays ?? null : null
|
|
1704
|
-
};
|
|
1705
|
-
if (input.id) {
|
|
1706
|
-
const { error: error2 } = await client().from(STEPS).update(row).eq("id", input.id);
|
|
1707
|
-
if (error2) throw new Error(error2.message);
|
|
1708
|
-
return;
|
|
1709
|
-
}
|
|
1710
|
-
row.tenant_id = getActiveTenantId();
|
|
1711
|
-
const { error } = await client().from(STEPS).insert(row);
|
|
1712
|
-
if (error) throw new Error(error.message);
|
|
1713
|
-
},
|
|
1714
|
-
async deleteStep(id) {
|
|
1715
|
-
const { error } = await client().from(STEPS).delete().eq("id", id);
|
|
1716
|
-
if (error) throw new Error(error.message);
|
|
1717
|
-
},
|
|
1718
|
-
async countsFor(flowId) {
|
|
1719
|
-
const { data, error } = await client().from(ENROLLMENTS).select("status").eq("flow_id", flowId);
|
|
1720
|
-
if (error) throw new Error(error.message);
|
|
1721
|
-
const rows = data ?? [];
|
|
1722
|
-
return {
|
|
1723
|
-
active: rows.filter((r) => r.status === "active").length,
|
|
1724
|
-
completed: rows.filter((r) => r.status === "completed").length,
|
|
1725
|
-
exited: rows.filter((r) => r.status === "exited").length
|
|
1726
|
-
};
|
|
1727
|
-
}
|
|
1728
|
-
};
|
|
1729
|
-
return store2;
|
|
1730
|
-
}
|
|
1731
|
-
var store = createSupabaseFlowStore();
|
|
1732
|
-
var DELAY_CHOICES = [0, 60, 1440, 2880, 4320, 10080];
|
|
1733
|
-
function useStepColumns(onDelete) {
|
|
1734
|
-
const t = useTranslation();
|
|
1735
|
-
return useMemo(() => [
|
|
1736
|
-
{
|
|
1737
|
-
accessorKey: "position",
|
|
1738
|
-
header: "#",
|
|
1739
|
-
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-muted-foreground", children: getValue() })
|
|
1740
|
-
},
|
|
1741
|
-
{
|
|
1742
|
-
id: "step",
|
|
1743
|
-
header: t("automations.flow.colStep"),
|
|
1744
|
-
cell: ({ row }) => {
|
|
1745
|
-
const s = row.original;
|
|
1746
|
-
const isTask = s.kind === "task";
|
|
1747
|
-
return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [
|
|
1748
|
-
isTask ? /* @__PURE__ */ jsx(ListChecks, { className: "h-3.5 w-3.5 text-muted-foreground" }) : /* @__PURE__ */ jsx(MessageSquare, { className: "h-3.5 w-3.5 text-muted-foreground" }),
|
|
1749
|
-
isTask ? s.taskTitle : s.templateKey,
|
|
1750
|
-
!isTask && s.channel && /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: s.channel })
|
|
1751
|
-
] });
|
|
1752
|
-
}
|
|
1753
|
-
},
|
|
1754
|
-
{
|
|
1755
|
-
accessorKey: "delayMinutes",
|
|
1756
|
-
header: t("automations.flow.colWait"),
|
|
1757
|
-
cell: ({ getValue }) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs text-muted-foreground", children: [
|
|
1758
|
-
/* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
|
|
1759
|
-
describeDelay(getValue(), t)
|
|
1760
|
-
] })
|
|
1761
|
-
},
|
|
1762
|
-
// The scoreboard. Zeroes are shown rather than hidden: a step that has never
|
|
1763
|
-
// sent is the finding, not an empty cell.
|
|
1764
|
-
{
|
|
1765
|
-
accessorKey: "queued",
|
|
1766
|
-
header: t("automations.flow.colQueued"),
|
|
1767
|
-
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
|
|
1768
|
-
},
|
|
1769
|
-
{
|
|
1770
|
-
accessorKey: "sent",
|
|
1771
|
-
header: t("automations.flow.colSent"),
|
|
1772
|
-
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
|
|
1773
|
-
},
|
|
1774
|
-
{
|
|
1775
|
-
accessorKey: "blocked",
|
|
1776
|
-
header: t("automations.flow.colBlocked"),
|
|
1777
|
-
cell: ({ getValue }) => {
|
|
1778
|
-
const n = getValue();
|
|
1779
|
-
return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-warning" : ""}`, children: n });
|
|
1780
|
-
}
|
|
1781
|
-
},
|
|
1782
|
-
{
|
|
1783
|
-
accessorKey: "failed",
|
|
1784
|
-
header: t("automations.flow.colFailed"),
|
|
1785
|
-
cell: ({ getValue }) => {
|
|
1786
|
-
const n = getValue();
|
|
1787
|
-
return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-destructive" : ""}`, children: n });
|
|
1788
|
-
}
|
|
1789
|
-
},
|
|
1790
|
-
{
|
|
1791
|
-
id: "actions",
|
|
1792
|
-
header: "",
|
|
1793
|
-
cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
|
|
1794
|
-
Button,
|
|
1795
|
-
{
|
|
1796
|
-
variant: "bare",
|
|
1797
|
-
size: "bare",
|
|
1798
|
-
onClick: (e) => {
|
|
1799
|
-
e.stopPropagation();
|
|
1800
|
-
onDelete(row.original.id);
|
|
1801
|
-
},
|
|
1802
|
-
title: t("automations.flow.deleteStep"),
|
|
1803
|
-
className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-destructive",
|
|
1804
|
-
children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
|
|
1805
|
-
}
|
|
1806
|
-
) })
|
|
1807
|
-
}
|
|
1808
|
-
], [t, onDelete]);
|
|
1809
|
-
}
|
|
1810
|
-
var COMPOSER_TRIGGER = "h-auto w-auto gap-2 rounded-md border-border px-2 py-1.5 shadow-none";
|
|
1811
|
-
function StepComposer({ steps, onAdd }) {
|
|
1812
|
-
const t = useTranslation();
|
|
1813
|
-
const [kind, setKind] = useState("message");
|
|
1814
|
-
const [delay, setDelay] = useState(1440);
|
|
1815
|
-
const [value, setValue] = useState("");
|
|
1816
|
-
const submit = () => {
|
|
1817
|
-
if (!value.trim()) {
|
|
1818
|
-
toast.error(t(kind === "task" ? "automations.flow.needTitle" : "automations.flow.needTemplate"));
|
|
1819
|
-
return;
|
|
1820
|
-
}
|
|
1821
|
-
onAdd({
|
|
1822
|
-
kind,
|
|
1823
|
-
delayMinutes: delay,
|
|
1824
|
-
position: nextPosition(steps),
|
|
1825
|
-
...kind === "task" ? { taskTitle: value.trim() } : { templateKey: value.trim() }
|
|
1826
|
-
});
|
|
1827
|
-
setValue("");
|
|
1828
|
-
};
|
|
1829
|
-
return /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-dashed p-3", children: [
|
|
1830
|
-
/* @__PURE__ */ jsxs(Select, { value: kind, onValueChange: (v) => {
|
|
1831
|
-
setKind(v);
|
|
1832
|
-
setValue("");
|
|
1833
|
-
}, children: [
|
|
1834
|
-
/* @__PURE__ */ jsx(SelectTrigger, { className: COMPOSER_TRIGGER, children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
1835
|
-
/* @__PURE__ */ jsxs(SelectContent, { children: [
|
|
1836
|
-
/* @__PURE__ */ jsx(SelectItem, { value: "message", children: t("automations.flow.kindMessage") }),
|
|
1837
|
-
/* @__PURE__ */ jsx(SelectItem, { value: "task", children: t("automations.flow.kindTask") })
|
|
1838
|
-
] })
|
|
1839
|
-
] }),
|
|
1840
|
-
/* @__PURE__ */ jsxs(Select, { value: String(delay), onValueChange: (v) => setDelay(Number(v)), children: [
|
|
1841
|
-
/* @__PURE__ */ jsx(SelectTrigger, { className: COMPOSER_TRIGGER, children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
1842
|
-
/* @__PURE__ */ jsx(SelectContent, { children: DELAY_CHOICES.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: String(m), children: describeDelay(m, t) }, m)) })
|
|
1843
|
-
] }),
|
|
1844
|
-
/* @__PURE__ */ jsx("div", { className: "min-w-[200px] flex-1", children: /* @__PURE__ */ jsx(
|
|
1845
|
-
Input,
|
|
1846
|
-
{
|
|
1847
|
-
value,
|
|
1848
|
-
onChange: (e) => setValue(e.target.value),
|
|
1849
|
-
onKeyDown: (e) => {
|
|
1850
|
-
if (e.key === "Enter") submit();
|
|
1851
|
-
},
|
|
1852
|
-
placeholder: t(kind === "task" ? "automations.flow.titlePlaceholder" : "automations.flow.templatePlaceholder"),
|
|
1853
|
-
className: "h-auto rounded-md border-border bg-background px-2 py-1.5 shadow-none"
|
|
1854
|
-
}
|
|
1855
|
-
) }),
|
|
1856
|
-
/* @__PURE__ */ jsxs(Button, { onClick: submit, className: "gap-1", children: [
|
|
1857
|
-
/* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
|
|
1858
|
-
t("automations.flow.addStep")
|
|
1859
|
-
] })
|
|
1860
|
-
] });
|
|
1861
|
-
}
|
|
1862
|
-
function FlowsPage() {
|
|
1863
|
-
const t = useTranslation();
|
|
1864
|
-
const [flows, setFlows] = useState([]);
|
|
1865
|
-
const [loading, setLoading] = useState(true);
|
|
1866
|
-
const [selectedId, setSelectedId] = useState(null);
|
|
1867
|
-
const [steps, setSteps] = useState([]);
|
|
1868
|
-
const [counts, setCounts] = useState(null);
|
|
1869
|
-
const [composerOpen, setComposerOpen] = useState(false);
|
|
1870
|
-
const load = useCallback(async () => {
|
|
1871
|
-
setLoading(true);
|
|
1872
|
-
try {
|
|
1873
|
-
setFlows(await store.listFlows());
|
|
1874
|
-
} catch (e) {
|
|
1875
|
-
toast.error(errorMessage(e));
|
|
1876
|
-
} finally {
|
|
1877
|
-
setLoading(false);
|
|
1878
|
-
}
|
|
1879
|
-
}, []);
|
|
1880
|
-
const selectedRef = useRef(null);
|
|
1881
|
-
selectedRef.current = selectedId;
|
|
1882
|
-
const loadDetail = useCallback(async (flowId) => {
|
|
1883
|
-
try {
|
|
1884
|
-
const [s, c] = await Promise.all([store.listSteps(flowId), store.countsFor(flowId)]);
|
|
1885
|
-
if (selectedRef.current !== flowId) return;
|
|
1886
|
-
setSteps(s);
|
|
1887
|
-
setCounts(c);
|
|
1888
|
-
} catch (e) {
|
|
1889
|
-
toast.error(errorMessage(e));
|
|
1890
|
-
}
|
|
1891
|
-
}, []);
|
|
1892
|
-
const deleteStep = useCallback((id) => {
|
|
1893
|
-
void (async () => {
|
|
1894
|
-
try {
|
|
1895
|
-
await store.deleteStep(id);
|
|
1896
|
-
if (selectedId) await loadDetail(selectedId);
|
|
1897
|
-
} catch (e) {
|
|
1898
|
-
toast.error(errorMessage(e));
|
|
1899
|
-
}
|
|
1900
|
-
})();
|
|
1901
|
-
}, [selectedId, loadDetail]);
|
|
1902
|
-
const stepColumns = useStepColumns(deleteStep);
|
|
1903
|
-
useEffect(() => {
|
|
1904
|
-
void load();
|
|
1905
|
-
}, [load]);
|
|
1906
|
-
useEffect(() => {
|
|
1907
|
-
setSteps([]);
|
|
1908
|
-
setCounts(null);
|
|
1909
|
-
if (selectedId) void loadDetail(selectedId);
|
|
1910
|
-
}, [selectedId, loadDetail]);
|
|
1911
|
-
flows.find((f) => f.id === selectedId) ?? null;
|
|
1912
|
-
async function createFlow(input) {
|
|
1913
|
-
const flow = await store.saveFlow(input);
|
|
1914
|
-
await load();
|
|
1915
|
-
setSelectedId(flow.id);
|
|
1916
|
-
toast.success(t("automations.flow.created"));
|
|
1917
|
-
}
|
|
1918
|
-
async function toggleActive(flow) {
|
|
1919
|
-
if (!flow.isActive) {
|
|
1920
|
-
const s = await store.listSteps(flow.id);
|
|
1921
|
-
if (s.length === 0) {
|
|
1922
|
-
toast.error(t("automations.flow.needStepsToActivate"));
|
|
1923
|
-
return;
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
try {
|
|
1927
|
-
await store.setFlowActive(flow.id, !flow.isActive);
|
|
1928
|
-
await load();
|
|
1929
|
-
} catch (e) {
|
|
1930
|
-
toast.error(errorMessage(e));
|
|
1931
|
-
}
|
|
1932
|
-
}
|
|
1933
|
-
if (loading) {
|
|
1934
|
-
return /* @__PURE__ */ jsx("div", { className: "space-y-2", "aria-busy": "true", "aria-label": t("automations.flow.loading"), children: [0, 1, 2].map((i) => /* @__PURE__ */ jsx(Card, { className: "p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
1935
|
-
/* @__PURE__ */ jsx("div", { className: "h-4 w-4 shrink-0 animate-pulse rounded bg-muted/40" }),
|
|
1936
|
-
/* @__PURE__ */ jsx("div", { className: "h-3.5 animate-pulse rounded bg-muted/40", style: { width: `${34 - i * 6}%` } }),
|
|
1937
|
-
/* @__PURE__ */ jsx("div", { className: "h-4 w-28 animate-pulse rounded-full bg-muted/30" }),
|
|
1938
|
-
/* @__PURE__ */ jsx("div", { className: "ml-auto h-5 w-9 animate-pulse rounded-full bg-muted/30" })
|
|
1939
|
-
] }) }, i)) });
|
|
1940
|
-
}
|
|
1941
|
-
return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
|
|
1942
|
-
/* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
|
|
1943
|
-
PageActions,
|
|
1944
|
-
{
|
|
1945
|
-
actions: [{
|
|
1946
|
-
id: "new-flow",
|
|
1947
|
-
label: t("automations.flow.new"),
|
|
1948
|
-
icon: Plus,
|
|
1949
|
-
intent: "primary",
|
|
1950
|
-
creates: true,
|
|
1951
|
-
onSelect: () => setComposerOpen(true)
|
|
1952
|
-
}]
|
|
1953
|
-
}
|
|
1954
|
-
) }),
|
|
1955
|
-
/* @__PURE__ */ jsx(
|
|
1956
|
-
CadenceComposer,
|
|
1957
|
-
{
|
|
1958
|
-
open: composerOpen,
|
|
1959
|
-
onClose: () => setComposerOpen(false),
|
|
1960
|
-
onCreate: createFlow
|
|
1961
|
-
}
|
|
1962
|
-
),
|
|
1963
|
-
flows.length === 0 ? /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-1 border-dashed py-12 text-center", children: [
|
|
1964
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("automations.flow.emptyTitle") }),
|
|
1965
|
-
/* @__PURE__ */ jsx("p", { className: "max-w-md text-xs text-muted-foreground", children: t("automations.flow.emptyHint") })
|
|
1966
|
-
] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: flows.map((flow) => /* @__PURE__ */ jsxs(Card, { className: "p-3", children: [
|
|
1967
|
-
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
1968
|
-
/* @__PURE__ */ jsxs(
|
|
1969
|
-
Button,
|
|
1970
|
-
{
|
|
1971
|
-
variant: "bare",
|
|
1972
|
-
size: "bare",
|
|
1973
|
-
onClick: () => setSelectedId(selectedId === flow.id ? null : flow.id),
|
|
1974
|
-
className: "flex flex-1 items-center gap-2 text-left font-normal justify-start",
|
|
1975
|
-
children: [
|
|
1976
|
-
/* @__PURE__ */ jsx(
|
|
1977
|
-
ChevronRight,
|
|
1978
|
-
{
|
|
1979
|
-
className: `h-4 w-4 text-muted-foreground transition-transform ${selectedId === flow.id ? "rotate-90" : ""}`
|
|
1980
|
-
}
|
|
1981
|
-
),
|
|
1982
|
-
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: flow.name }),
|
|
1983
|
-
/* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: flow.entryEvent })
|
|
1984
|
-
]
|
|
1985
|
-
}
|
|
1986
|
-
),
|
|
1987
|
-
/* @__PURE__ */ jsx(
|
|
1988
|
-
Switch,
|
|
1989
|
-
{
|
|
1990
|
-
checked: flow.isActive,
|
|
1991
|
-
onCheckedChange: () => {
|
|
1992
|
-
void toggleActive(flow);
|
|
1993
|
-
},
|
|
1994
|
-
"aria-label": t("automations.flow.toggle")
|
|
1995
|
-
}
|
|
1996
|
-
)
|
|
1997
|
-
] }),
|
|
1998
|
-
selectedId === flow.id && /* @__PURE__ */ jsxs("div", { className: "mt-3 border-t pt-3", children: [
|
|
1999
|
-
counts && /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs text-muted-foreground", children: t("automations.flow.counts", {
|
|
2000
|
-
active: String(counts.active),
|
|
2001
|
-
completed: String(counts.completed),
|
|
2002
|
-
exited: String(counts.exited)
|
|
2003
|
-
}) }),
|
|
2004
|
-
/* @__PURE__ */ jsx(
|
|
2005
|
-
DataTable,
|
|
2006
|
-
{
|
|
2007
|
-
columns: stepColumns,
|
|
2008
|
-
data: steps,
|
|
2009
|
-
emptyMessage: /* @__PURE__ */ jsx("p", { className: "py-4 text-xs text-muted-foreground", children: t("automations.flow.noSteps") })
|
|
2010
|
-
}
|
|
2011
|
-
),
|
|
2012
|
-
/* @__PURE__ */ jsx(
|
|
2013
|
-
StepComposer,
|
|
2014
|
-
{
|
|
2015
|
-
steps,
|
|
2016
|
-
onAdd: (input) => {
|
|
2017
|
-
void (async () => {
|
|
2018
|
-
try {
|
|
2019
|
-
await store.saveStep(flow.id, input);
|
|
2020
|
-
await loadDetail(flow.id);
|
|
2021
|
-
} catch (e) {
|
|
2022
|
-
toast.error(errorMessage(e));
|
|
2023
|
-
}
|
|
2024
|
-
})();
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
)
|
|
2028
|
-
] })
|
|
2029
|
-
] }, flow.id)) })
|
|
2030
|
-
] });
|
|
2031
|
-
}
|
|
2032
67
|
|
|
2033
68
|
// src/locales/en.ts
|
|
2034
69
|
var en = {
|
|
@@ -2123,1016 +158,22 @@ var automationsLocales = {
|
|
|
2123
158
|
en,
|
|
2124
159
|
"pt-BR": ptBR
|
|
2125
160
|
};
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
var
|
|
2129
|
-
-- plugins/plugin-automations/migrations/000_baseline.sql \u2014 what installing this provisions, as one file.
|
|
2130
|
-
--
|
|
2131
|
-
-- GENERATED by scripts/emit-unit-baselines.mjs (#338). Do not edit by hand:
|
|
2132
|
-
-- change the schema, regenerate, and let scripts/check-chain-equivalence.mjs
|
|
2133
|
-
-- prove the result still matches.
|
|
2134
|
-
--
|
|
2135
|
-
-- This replaced 4 migration files. They are kept, unapplied, in
|
|
2136
|
-
-- migrations.archive/ \u2014 a year of decisions is worth reading even when it is no
|
|
2137
|
-
-- longer worth replaying.
|
|
2138
|
-
--
|
|
2139
|
-
-- Object order is fixed rather than dependency-sorted: schemas, types,
|
|
2140
|
-
-- sequences, tables, defaults, functions, constraints, views, indexes, foreign
|
|
2141
|
-
-- keys, triggers, row security, policies, grants. Dependencies BETWEEN units
|
|
2142
|
-
-- are carried by the order packages/db/chain.json declares.
|
|
2143
|
-
-- ============================================================================
|
|
2144
|
-
|
|
2145
|
-
-- A LANGUAGE sql function binds its body at CREATE time, and 570 functions
|
|
2146
|
-
-- sorted by name are not sorted by who calls whom. This is what lets them load
|
|
2147
|
-
-- in any order; every body is still compiled on first call, so a genuinely
|
|
2148
|
-
-- broken reference surfaces then rather than never. Session-scoped.
|
|
2149
|
-
SET check_function_bodies = false;
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
-- \u2500\u2500 default privileges: reset \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2154
|
-
-- Cleared BEFORE anything is created, so every object below gets the ACL the
|
|
2155
|
-
-- dump describes rather than the image's defaults on top of it. Restored at
|
|
2156
|
-
-- the end of this file.
|
|
2157
|
-
|
|
2158
|
-
DO $dp$ BEGIN
|
|
2159
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2160
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2161
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2162
|
-
END $dp$;
|
|
2163
|
-
|
|
2164
|
-
DO $dp$ BEGIN
|
|
2165
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2166
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2167
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2168
|
-
END $dp$;
|
|
2169
|
-
|
|
2170
|
-
DO $dp$ BEGIN
|
|
2171
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2172
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2173
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2174
|
-
END $dp$;
|
|
2175
|
-
|
|
2176
|
-
DO $dp$ BEGIN
|
|
2177
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2178
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2179
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2180
|
-
END $dp$;
|
|
2181
|
-
|
|
2182
|
-
DO $dp$ BEGIN
|
|
2183
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2184
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2185
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2186
|
-
END $dp$;
|
|
2187
|
-
|
|
2188
|
-
DO $dp$ BEGIN
|
|
2189
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2190
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2191
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
|
|
2192
|
-
END $dp$;
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
-- \u2500\u2500 table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2196
|
-
|
|
2197
|
-
CREATE TABLE public.plg_automations_provider_templates (
|
|
2198
|
-
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
2199
|
-
tenant_id uuid,
|
|
2200
|
-
event_key text NOT NULL,
|
|
2201
|
-
channel text DEFAULT 'whatsapp'::text NOT NULL,
|
|
2202
|
-
provider text DEFAULT 'tyxter'::text NOT NULL,
|
|
2203
|
-
provider_template_id text,
|
|
2204
|
-
template_name text NOT NULL,
|
|
2205
|
-
language text DEFAULT 'pt_BR'::text NOT NULL,
|
|
2206
|
-
variable_map jsonb DEFAULT '[]'::jsonb NOT NULL,
|
|
2207
|
-
actions_map jsonb DEFAULT '[]'::jsonb NOT NULL,
|
|
2208
|
-
status text DEFAULT 'draft'::text NOT NULL,
|
|
2209
|
-
rejection_reason text,
|
|
2210
|
-
body_snapshot text,
|
|
2211
|
-
submitted_at timestamp with time zone,
|
|
2212
|
-
approved_at timestamp with time zone,
|
|
2213
|
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
2214
|
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
2215
|
-
CONSTRAINT plg_automations_provider_templates_status_check CHECK ((status = ANY (ARRAY['draft'::text, 'submitted'::text, 'approved'::text, 'rejected'::text, 'paused'::text, 'disabled'::text])))
|
|
2216
|
-
);
|
|
2217
|
-
|
|
2218
|
-
CREATE TABLE public.plg_automations_templates (
|
|
2219
|
-
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
2220
|
-
tenant_id uuid NOT NULL,
|
|
2221
|
-
event_key text NOT NULL,
|
|
2222
|
-
channel text DEFAULT 'email'::text NOT NULL,
|
|
2223
|
-
enabled boolean,
|
|
2224
|
-
subject text,
|
|
2225
|
-
body text,
|
|
2226
|
-
name text,
|
|
2227
|
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
2228
|
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
2229
|
-
actions jsonb
|
|
2230
|
-
);
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
-- \u2500\u2500 function \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2234
|
-
|
|
2235
|
-
CREATE FUNCTION public.automations_set_updated_at() RETURNS trigger
|
|
2236
|
-
LANGUAGE plpgsql
|
|
2237
|
-
AS $$
|
|
2238
|
-
BEGIN
|
|
2239
|
-
NEW.updated_at = now();
|
|
2240
|
-
RETURN NEW;
|
|
2241
|
-
END $$;
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
-- \u2500\u2500 constraint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2245
|
-
|
|
2246
|
-
ALTER TABLE ONLY public.plg_automations_provider_templates
|
|
2247
|
-
ADD CONSTRAINT plg_automations_provider_templates_pkey PRIMARY KEY (id);
|
|
2248
|
-
|
|
2249
|
-
ALTER TABLE ONLY public.plg_automations_templates
|
|
2250
|
-
ADD CONSTRAINT plg_automations_templates_pkey PRIMARY KEY (id);
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
-- \u2500\u2500 index \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2254
|
-
|
|
2255
|
-
CREATE INDEX idx_plg_automations_provider_templates_lookup ON public.plg_automations_provider_templates USING btree (event_key, channel, provider, status);
|
|
2256
|
-
|
|
2257
|
-
CREATE INDEX plg_automations_templates_tenant_idx ON public.plg_automations_templates USING btree (tenant_id);
|
|
2258
|
-
|
|
2259
|
-
CREATE UNIQUE INDEX plg_automations_templates_unique_idx ON public.plg_automations_templates USING btree (tenant_id, event_key, channel);
|
|
2260
|
-
|
|
2261
|
-
CREATE UNIQUE INDEX uq_plg_automations_provider_templates_owner ON public.plg_automations_provider_templates USING btree (COALESCE(tenant_id, '00000000-0000-0000-0000-000000000000'::uuid), event_key, channel, provider);
|
|
2262
|
-
|
|
2263
|
-
CREATE UNIQUE INDEX uq_plg_automations_provider_templates_provider_id ON public.plg_automations_provider_templates USING btree (provider, provider_template_id) WHERE (provider_template_id IS NOT NULL);
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
-- \u2500\u2500 fk constraint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2267
|
-
|
|
2268
|
-
ALTER TABLE ONLY public.plg_automations_provider_templates
|
|
2269
|
-
ADD CONSTRAINT plg_automations_provider_templates_tenant_id_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
-- \u2500\u2500 trigger \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2273
|
-
|
|
2274
|
-
CREATE TRIGGER plg_automations_provider_templates_set_updated_at BEFORE UPDATE ON public.plg_automations_provider_templates FOR EACH ROW EXECUTE FUNCTION public.automations_set_updated_at();
|
|
2275
|
-
|
|
2276
|
-
CREATE TRIGGER plg_automations_templates_set_updated_at BEFORE UPDATE ON public.plg_automations_templates FOR EACH ROW EXECUTE FUNCTION public.automations_set_updated_at();
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
-- \u2500\u2500 row security \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2280
|
-
|
|
2281
|
-
ALTER TABLE public.plg_automations_provider_templates ENABLE ROW LEVEL SECURITY;
|
|
2282
|
-
|
|
2283
|
-
ALTER TABLE public.plg_automations_templates ENABLE ROW LEVEL SECURITY;
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
-- \u2500\u2500 policy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2287
|
-
|
|
2288
|
-
CREATE POLICY plg_automations_provider_templates_select ON public.plg_automations_provider_templates FOR SELECT TO authenticated USING (((tenant_id IS NULL) OR (tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids))));
|
|
2289
|
-
|
|
2290
|
-
CREATE POLICY plg_automations_templates_member_all ON public.plg_automations_templates TO authenticated USING ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids))) WITH CHECK ((tenant_id IN ( SELECT public.user_tenant_ids() AS user_tenant_ids)));
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
-- \u2500\u2500 acl \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2294
|
-
|
|
2295
|
-
GRANT ALL ON FUNCTION public.automations_set_updated_at() TO authenticated;
|
|
2296
|
-
GRANT ALL ON FUNCTION public.automations_set_updated_at() TO service_role;
|
|
2297
|
-
|
|
2298
|
-
GRANT MAINTAIN ON TABLE public.plg_automations_provider_templates TO anon;
|
|
2299
|
-
GRANT ALL ON TABLE public.plg_automations_provider_templates TO authenticated;
|
|
2300
|
-
GRANT ALL ON TABLE public.plg_automations_provider_templates TO service_role;
|
|
2301
|
-
|
|
2302
|
-
GRANT MAINTAIN ON TABLE public.plg_automations_templates TO anon;
|
|
2303
|
-
GRANT ALL ON TABLE public.plg_automations_templates TO authenticated;
|
|
2304
|
-
GRANT ALL ON TABLE public.plg_automations_templates TO service_role;
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
-- \u2500\u2500 comment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2308
|
-
|
|
2309
|
-
COMMENT ON COLUMN public.plg_automations_templates.actions IS 'Channel-neutral message actions: [{id: confirm|cancel|pay, label, kind: reply|payment}]. NULL = the catalog default; [] = deliberately no buttons.';
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
-- \u2500\u2500 default privileges: restore \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2313
|
-
-- Put back, so the NEXT thing installed inherits what the chain had.
|
|
2314
|
-
|
|
2315
|
-
DO $dp$ BEGIN
|
|
2316
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
|
|
2317
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2318
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
|
|
2319
|
-
END $dp$;
|
|
2320
|
-
|
|
2321
|
-
DO $dp$ BEGIN
|
|
2322
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
|
|
2323
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2324
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
|
|
2325
|
-
END $dp$;
|
|
2326
|
-
|
|
2327
|
-
DO $dp$ BEGIN
|
|
2328
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
|
|
2329
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2330
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
|
|
2331
|
-
END $dp$;
|
|
2332
|
-
|
|
2333
|
-
DO $dp$ BEGIN
|
|
2334
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
|
|
2335
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2336
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
|
|
2337
|
-
END $dp$;
|
|
2338
|
-
|
|
2339
|
-
DO $dp$ BEGIN
|
|
2340
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
|
|
2341
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2342
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
|
|
2343
|
-
END $dp$;
|
|
2344
|
-
|
|
2345
|
-
DO $dp$ BEGIN
|
|
2346
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
|
|
2347
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2348
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
|
|
2349
|
-
END $dp$;
|
|
2350
|
-
|
|
2351
|
-
DO $dp$ BEGIN
|
|
2352
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
|
|
2353
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2354
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
|
|
2355
|
-
END $dp$;
|
|
2356
|
-
|
|
2357
|
-
DO $dp$ BEGIN
|
|
2358
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
|
|
2359
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2360
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
|
|
2361
|
-
END $dp$;
|
|
2362
|
-
|
|
2363
|
-
DO $dp$ BEGIN
|
|
2364
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
|
|
2365
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2366
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
|
|
2367
|
-
END $dp$;
|
|
2368
|
-
|
|
2369
|
-
DO $dp$ BEGIN
|
|
2370
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
|
|
2371
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2372
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
|
|
2373
|
-
END $dp$;
|
|
2374
|
-
|
|
2375
|
-
DO $dp$ BEGIN
|
|
2376
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
|
|
2377
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2378
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
|
|
2379
|
-
END $dp$;
|
|
2380
|
-
|
|
2381
|
-
DO $dp$ BEGIN
|
|
2382
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
|
|
2383
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2384
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
|
|
2385
|
-
END $dp$;
|
|
2386
|
-
|
|
2387
|
-
DO $dp$ BEGIN
|
|
2388
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon$stmt$;
|
|
2389
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2390
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon$stmt$;
|
|
2391
|
-
END $dp$;
|
|
2392
|
-
|
|
2393
|
-
DO $dp$ BEGIN
|
|
2394
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
|
|
2395
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2396
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
|
|
2397
|
-
END $dp$;
|
|
2398
|
-
|
|
2399
|
-
DO $dp$ BEGIN
|
|
2400
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
|
|
2401
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2402
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
|
|
2403
|
-
END $dp$;
|
|
2404
|
-
|
|
2405
|
-
DO $dp$ BEGIN
|
|
2406
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
|
|
2407
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2408
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
|
|
2409
|
-
END $dp$;
|
|
2410
|
-
|
|
2411
|
-
DO $dp$ BEGIN
|
|
2412
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT MAINTAIN ON TABLES TO anon$stmt$;
|
|
2413
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2414
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT MAINTAIN ON TABLES TO anon$stmt$;
|
|
2415
|
-
END $dp$;
|
|
2416
|
-
|
|
2417
|
-
DO $dp$ BEGIN
|
|
2418
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
|
|
2419
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2420
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
|
|
2421
|
-
END $dp$;
|
|
2422
|
-
|
|
2423
|
-
DO $dp$ BEGIN
|
|
2424
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
|
|
2425
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2426
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
|
|
2427
|
-
END $dp$;
|
|
2428
|
-
|
|
2429
|
-
DO $dp$ BEGIN
|
|
2430
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
|
|
2431
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2432
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
|
|
2433
|
-
END $dp$;
|
|
2434
|
-
|
|
2435
|
-
DO $dp$ BEGIN
|
|
2436
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon$stmt$;
|
|
2437
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2438
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon$stmt$;
|
|
2439
|
-
END $dp$;
|
|
2440
|
-
|
|
2441
|
-
DO $dp$ BEGIN
|
|
2442
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
|
|
2443
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2444
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
|
|
2445
|
-
END $dp$;
|
|
2446
|
-
|
|
2447
|
-
DO $dp$ BEGIN
|
|
2448
|
-
EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
|
|
2449
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2450
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
|
|
2451
|
-
END $dp$;
|
|
2452
|
-
|
|
2453
|
-
DO $dp$ BEGIN
|
|
2454
|
-
EXECUTE $stmt$--
|
|
2455
|
-
-- PostgreSQL database dump complete
|
|
2456
|
-
--$stmt$;
|
|
2457
|
-
EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
|
|
2458
|
-
RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$--
|
|
2459
|
-
-- PostgreSQL database dump complete
|
|
2460
|
-
--$stmt$;
|
|
2461
|
-
END $dp$;
|
|
2462
|
-
`;
|
|
2463
|
-
var MIGRATION_001_THE_FLOW_HAS_STEPS = `-- 001_the_flow_has_steps.sql
|
|
2464
|
-
--
|
|
2465
|
-
-- A CADENCE: the same lead touched on day 0, day 2 and day 5, by itself.
|
|
2466
|
-
--
|
|
2467
|
-
-- This plugin's README has promised "multi-step sequences, and enrollment
|
|
2468
|
-
-- stats" since M1, and \`AutomationsList.tsx\` says plainly what shipped instead:
|
|
2469
|
-
-- "um fluxo de um passo \xE9 o texto com o gatilho escrito na frente". One row per
|
|
2470
|
-
-- (event, channel). Nothing waits, nothing remembers where a person got to, and
|
|
2471
|
-
-- nothing stops when they reply.
|
|
2472
|
-
--
|
|
2473
|
-
-- WHAT THIS DOES NOT BUILD, BECAUSE IT ALREADY EXISTS.
|
|
2474
|
-
--
|
|
2475
|
-
-- * The clock. \`fayz_event_runner\` is a pg_cron job that already calls
|
|
2476
|
-
-- \`event_runner_tick(200)\` every minute. This adds a fifth call to it
|
|
2477
|
-
-- (packages/db 046), guarded like the other four.
|
|
2478
|
-
-- * The delay. \`notifications_enqueue(..., p_scheduled_for, p_dedupe_key)\`
|
|
2479
|
-
-- already means "send this at time T, and not twice". A cadence step is a
|
|
2480
|
-
-- row in that queue with a computed \`scheduled_for\`.
|
|
2481
|
-
-- * Consent, channel preference and quiet-channel fallback \u2014 all inside
|
|
2482
|
-
-- \`notifications_resolve_channel\`, which plugin-notifications 002 just
|
|
2483
|
-
-- taught to read the opt-out correctly. A cadence that dodged the queue
|
|
2484
|
-
-- would dodge consent with it, which is the whole reason it does not.
|
|
2485
|
-
-- * The claim-and-retry shape. \`marketing_run_due\` / \`marketing_campaign_run\`
|
|
2486
|
-
-- already solve "advance a set of enrolled people on a tick" with
|
|
2487
|
-
-- \`FOR UPDATE SKIP LOCKED\`. \`automations_flows_run_due\` is that function
|
|
2488
|
-
-- with a step pointer.
|
|
2489
|
-
--
|
|
2490
|
-
-- THE THREE DECISIONS WORTH ARGUING WITH.
|
|
2491
|
-
--
|
|
2492
|
-
-- 1. THE DELAY IS AN OFFSET FROM THE PREVIOUS STEP, NOT FROM ENROLMENT.
|
|
2493
|
-
-- "Two days after the call" is how a salesperson describes a cadence, and it
|
|
2494
|
-
-- survives inserting a step in the middle. Absolute offsets from day 0 mean
|
|
2495
|
-
-- every later step silently shifts when you add one.
|
|
2496
|
-
--
|
|
2497
|
-
-- 2. THE ENROLMENT CARRIES THE STEP POINTER, AND THE DEDUPE KEY CARRIES THE
|
|
2498
|
-
-- POSITION. \`flow:<enrolment>:<position>\` means replaying a tick, or two
|
|
2499
|
-
-- workers taking the same row, cannot send a step twice \u2014
|
|
2500
|
-
-- \`notifications_enqueue\` refuses a repeated \`dedupe_key\` before it writes
|
|
2501
|
-
-- anything. The SKIP LOCKED claim is the first defence; this is the one that
|
|
2502
|
-
-- survives a crash between the enqueue and the pointer update.
|
|
2503
|
-
--
|
|
2504
|
-
-- 3. A FLOW IS BORN INACTIVE. \`is_active\` defaults false. A cadence that starts
|
|
2505
|
-
-- sending the moment somebody saves a draft is a cadence that sends a draft.
|
|
2506
|
-
--
|
|
2507
|
-
-- WHAT IS STILL MISSING AFTER THIS, AND IS NOT PRETENDED OTHERWISE: e-mail and
|
|
2508
|
-
-- SMS still resolve to \`notifications_send_to_log\`, which records and sends
|
|
2509
|
-
-- nothing. A cadence on those channels will enqueue, drain, and deliver to a
|
|
2510
|
-
-- log row. WhatsApp reaches a provider; in-app reaches the bell.
|
|
2511
|
-
|
|
2512
|
-
SET check_function_bodies = false;
|
|
2513
|
-
|
|
2514
|
-
-- \u2500\u2500 tables \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2515
|
-
|
|
2516
|
-
CREATE TABLE IF NOT EXISTS public.plg_automations_flows (
|
|
2517
|
-
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
2518
|
-
tenant_id uuid NOT NULL,
|
|
2519
|
-
unit_id uuid,
|
|
2520
|
-
name text NOT NULL,
|
|
2521
|
-
description text,
|
|
2522
|
-
-- The fact that puts somebody in. Names an event from the aggregated plugin
|
|
2523
|
-
-- catalog (\`crm.lead_created\`, \`crm.stage_changed\`, \u2026); it is text and not a
|
|
2524
|
-
-- foreign key because the catalog is assembled at runtime from whichever
|
|
2525
|
-
-- plugins an app mounts.
|
|
2526
|
-
entry_event text NOT NULL,
|
|
2527
|
-
-- The facts that take somebody out. Empty means the flow only ends by
|
|
2528
|
-
-- running out of steps.
|
|
2529
|
-
exit_events text[] DEFAULT '{}'::text[] NOT NULL,
|
|
2530
|
-
is_active boolean DEFAULT false NOT NULL,
|
|
2531
|
-
owner_id uuid,
|
|
2532
|
-
created_at timestamptz DEFAULT now() NOT NULL,
|
|
2533
|
-
updated_at timestamptz DEFAULT now() NOT NULL,
|
|
2534
|
-
CONSTRAINT plg_automations_flows_pkey PRIMARY KEY (id)
|
|
2535
|
-
);
|
|
2536
|
-
|
|
2537
|
-
CREATE TABLE IF NOT EXISTS public.plg_automations_flow_steps (
|
|
2538
|
-
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
2539
|
-
tenant_id uuid NOT NULL,
|
|
2540
|
-
flow_id uuid NOT NULL,
|
|
2541
|
-
-- Sparse on purpose (10, 20, 30\u2026): inserting between two steps should not
|
|
2542
|
-
-- renumber the ones after it, and the enrolment's pointer names a position.
|
|
2543
|
-
position integer NOT NULL,
|
|
2544
|
-
-- Minutes to wait AFTER THE PREVIOUS STEP. The first step's delay is measured
|
|
2545
|
-
-- from enrolment, so 0 means "right away".
|
|
2546
|
-
delay_minutes integer DEFAULT 0 NOT NULL,
|
|
2547
|
-
kind text DEFAULT 'message' NOT NULL,
|
|
2548
|
-
-- kind='message': which template, and optionally force a channel. NULL
|
|
2549
|
-
-- channel lets notifications_resolve_channel pick, which is what honours the
|
|
2550
|
-
-- recipient's preference.
|
|
2551
|
-
template_key text,
|
|
2552
|
-
channel text,
|
|
2553
|
-
-- kind='task': what the human is asked to do, and by when.
|
|
2554
|
-
task_title text,
|
|
2555
|
-
task_due_days integer,
|
|
2556
|
-
created_at timestamptz DEFAULT now() NOT NULL,
|
|
2557
|
-
updated_at timestamptz DEFAULT now() NOT NULL,
|
|
2558
|
-
CONSTRAINT plg_automations_flow_steps_pkey PRIMARY KEY (id),
|
|
2559
|
-
CONSTRAINT plg_automations_flow_steps_kind_check
|
|
2560
|
-
CHECK (kind = ANY (ARRAY['message'::text, 'task'::text])),
|
|
2561
|
-
CONSTRAINT plg_automations_flow_steps_delay_check CHECK (delay_minutes >= 0),
|
|
2562
|
-
-- A message step with no template has nothing to send; a task step with no
|
|
2563
|
-
-- title gives the human nothing to read. Either is a step that would fail at
|
|
2564
|
-
-- 3am rather than at save time.
|
|
2565
|
-
CONSTRAINT plg_automations_flow_steps_payload_check CHECK (
|
|
2566
|
-
(kind = 'message' AND template_key IS NOT NULL)
|
|
2567
|
-
OR (kind = 'task' AND task_title IS NOT NULL)
|
|
2568
|
-
)
|
|
2569
|
-
);
|
|
2570
|
-
|
|
2571
|
-
CREATE TABLE IF NOT EXISTS public.plg_automations_enrollments (
|
|
2572
|
-
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
2573
|
-
tenant_id uuid NOT NULL,
|
|
2574
|
-
flow_id uuid NOT NULL,
|
|
2575
|
-
person_id uuid NOT NULL,
|
|
2576
|
-
-- What put them here, for the timeline: ('lead', <id>) or ('deal', <id>).
|
|
2577
|
-
subject_type text,
|
|
2578
|
-
subject_id uuid,
|
|
2579
|
-
status text DEFAULT 'active' NOT NULL,
|
|
2580
|
-
-- The position of the step that runs NEXT. NULL once nothing is left.
|
|
2581
|
-
current_position integer,
|
|
2582
|
-
next_run_at timestamptz DEFAULT now() NOT NULL,
|
|
2583
|
-
entered_at timestamptz DEFAULT now() NOT NULL,
|
|
2584
|
-
exited_at timestamptz,
|
|
2585
|
-
exit_reason text,
|
|
2586
|
-
created_at timestamptz DEFAULT now() NOT NULL,
|
|
2587
|
-
updated_at timestamptz DEFAULT now() NOT NULL,
|
|
2588
|
-
CONSTRAINT plg_automations_enrollments_pkey PRIMARY KEY (id),
|
|
2589
|
-
CONSTRAINT plg_automations_enrollments_status_check
|
|
2590
|
-
CHECK (status = ANY (ARRAY['active'::text, 'completed'::text, 'exited'::text]))
|
|
2591
|
-
);
|
|
2592
|
-
|
|
2593
|
-
-- \u2500\u2500 constraint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2594
|
-
|
|
2595
|
-
ALTER TABLE public.plg_automations_flows
|
|
2596
|
-
DROP CONSTRAINT IF EXISTS plg_automations_flows_tenant_fkey;
|
|
2597
|
-
ALTER TABLE public.plg_automations_flows
|
|
2598
|
-
ADD CONSTRAINT plg_automations_flows_tenant_fkey
|
|
2599
|
-
FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
2600
|
-
|
|
2601
|
-
ALTER TABLE public.plg_automations_flow_steps
|
|
2602
|
-
DROP CONSTRAINT IF EXISTS plg_automations_flow_steps_flow_fkey;
|
|
2603
|
-
ALTER TABLE public.plg_automations_flow_steps
|
|
2604
|
-
ADD CONSTRAINT plg_automations_flow_steps_flow_fkey
|
|
2605
|
-
FOREIGN KEY (flow_id) REFERENCES public.plg_automations_flows(id) ON DELETE CASCADE;
|
|
2606
|
-
|
|
2607
|
-
ALTER TABLE public.plg_automations_enrollments
|
|
2608
|
-
DROP CONSTRAINT IF EXISTS plg_automations_enrollments_flow_fkey;
|
|
2609
|
-
ALTER TABLE public.plg_automations_enrollments
|
|
2610
|
-
ADD CONSTRAINT plg_automations_enrollments_flow_fkey
|
|
2611
|
-
FOREIGN KEY (flow_id) REFERENCES public.plg_automations_flows(id) ON DELETE CASCADE;
|
|
2612
|
-
|
|
2613
|
-
-- \u2500\u2500 index \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2614
|
-
|
|
2615
|
-
CREATE UNIQUE INDEX IF NOT EXISTS plg_automations_flow_steps_position_uq
|
|
2616
|
-
ON public.plg_automations_flow_steps (flow_id, position);
|
|
2617
|
-
CREATE INDEX IF NOT EXISTS plg_automations_flows_tenant_idx
|
|
2618
|
-
ON public.plg_automations_flows (tenant_id);
|
|
2619
|
-
CREATE INDEX IF NOT EXISTS plg_automations_flows_entry_idx
|
|
2620
|
-
ON public.plg_automations_flows (tenant_id, entry_event) WHERE is_active;
|
|
2621
|
-
|
|
2622
|
-
-- One live enrolment per person per flow. Re-entering a cadence somebody is
|
|
2623
|
-
-- already in would double every remaining message.
|
|
2624
|
-
CREATE UNIQUE INDEX IF NOT EXISTS plg_automations_enrollments_live_uq
|
|
2625
|
-
ON public.plg_automations_enrollments (flow_id, person_id) WHERE status = 'active';
|
|
2626
|
-
-- The claim index: the runner only ever asks for due, active rows.
|
|
2627
|
-
CREATE INDEX IF NOT EXISTS plg_automations_enrollments_due_idx
|
|
2628
|
-
ON public.plg_automations_enrollments (next_run_at) WHERE status = 'active';
|
|
2629
|
-
CREATE INDEX IF NOT EXISTS plg_automations_enrollments_person_idx
|
|
2630
|
-
ON public.plg_automations_enrollments (tenant_id, person_id);
|
|
2631
|
-
|
|
2632
|
-
-- \u2500\u2500 row security \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2633
|
-
|
|
2634
|
-
-- ENABLE **and** FORCE. Without FORCE the table owner \u2014 which is the role that
|
|
2635
|
-
-- runs migrations and every SECURITY DEFINER function here \u2014 bypasses these
|
|
2636
|
-
-- policies entirely, and \`packages/db/test/pgtap/900_verification/001_posture.sql\`
|
|
2637
|
-
-- (N14b) fails the whole pool for it.
|
|
2638
|
-
ALTER TABLE public.plg_automations_flows ENABLE ROW LEVEL SECURITY;
|
|
2639
|
-
ALTER TABLE public.plg_automations_flows FORCE ROW LEVEL SECURITY;
|
|
2640
|
-
ALTER TABLE public.plg_automations_flow_steps ENABLE ROW LEVEL SECURITY;
|
|
2641
|
-
ALTER TABLE public.plg_automations_flow_steps FORCE ROW LEVEL SECURITY;
|
|
2642
|
-
ALTER TABLE public.plg_automations_enrollments ENABLE ROW LEVEL SECURITY;
|
|
2643
|
-
ALTER TABLE public.plg_automations_enrollments FORCE ROW LEVEL SECURITY;
|
|
2644
|
-
|
|
2645
|
-
DROP POLICY IF EXISTS plg_automations_flows_authz_select ON public.plg_automations_flows;
|
|
2646
|
-
CREATE POLICY plg_automations_flows_authz_select ON public.plg_automations_flows
|
|
2647
|
-
FOR SELECT TO authenticated USING (
|
|
2648
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2649
|
-
AND (SELECT app.has_permission('automations.read', NULL::uuid)));
|
|
2650
|
-
|
|
2651
|
-
DROP POLICY IF EXISTS plg_automations_flows_authz_insert ON public.plg_automations_flows;
|
|
2652
|
-
CREATE POLICY plg_automations_flows_authz_insert ON public.plg_automations_flows
|
|
2653
|
-
FOR INSERT TO authenticated WITH CHECK (
|
|
2654
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2655
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
|
|
2656
|
-
|
|
2657
|
-
DROP POLICY IF EXISTS plg_automations_flows_authz_update ON public.plg_automations_flows;
|
|
2658
|
-
CREATE POLICY plg_automations_flows_authz_update ON public.plg_automations_flows
|
|
2659
|
-
FOR UPDATE TO authenticated USING (
|
|
2660
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2661
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)))
|
|
2662
|
-
WITH CHECK (
|
|
2663
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2664
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
|
|
2665
|
-
|
|
2666
|
-
DROP POLICY IF EXISTS plg_automations_flows_authz_delete ON public.plg_automations_flows;
|
|
2667
|
-
CREATE POLICY plg_automations_flows_authz_delete ON public.plg_automations_flows
|
|
2668
|
-
FOR DELETE TO authenticated USING (
|
|
2669
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2670
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
|
|
2671
|
-
|
|
2672
|
-
DROP POLICY IF EXISTS plg_automations_flow_steps_authz_select ON public.plg_automations_flow_steps;
|
|
2673
|
-
CREATE POLICY plg_automations_flow_steps_authz_select ON public.plg_automations_flow_steps
|
|
2674
|
-
FOR SELECT TO authenticated USING (
|
|
2675
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2676
|
-
AND (SELECT app.has_permission('automations.read', NULL::uuid)));
|
|
2677
|
-
|
|
2678
|
-
DROP POLICY IF EXISTS plg_automations_flow_steps_authz_insert ON public.plg_automations_flow_steps;
|
|
2679
|
-
-- The parent flow is checked, not just the stamped tenant. A tenant-only
|
|
2680
|
-
-- WITH CHECK lets a caller stamp their OWN tenant_id on a step and hang it off
|
|
2681
|
-
-- somebody else's flow \u2014 and the engine looks steps up by flow_id alone, so the
|
|
2682
|
-
-- injected step runs in that tenant's cadence.
|
|
2683
|
-
CREATE POLICY plg_automations_flow_steps_authz_insert ON public.plg_automations_flow_steps
|
|
2684
|
-
FOR INSERT TO authenticated WITH CHECK (
|
|
2685
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2686
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid))
|
|
2687
|
-
AND EXISTS (SELECT 1 FROM public.plg_automations_flows f
|
|
2688
|
-
WHERE f.id = flow_id AND f.tenant_id = (SELECT app.current_tenant_id())));
|
|
2689
|
-
|
|
2690
|
-
DROP POLICY IF EXISTS plg_automations_flow_steps_authz_update ON public.plg_automations_flow_steps;
|
|
2691
|
-
CREATE POLICY plg_automations_flow_steps_authz_update ON public.plg_automations_flow_steps
|
|
2692
|
-
FOR UPDATE TO authenticated USING (
|
|
2693
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2694
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)))
|
|
2695
|
-
WITH CHECK (
|
|
2696
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2697
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
|
|
2698
|
-
|
|
2699
|
-
DROP POLICY IF EXISTS plg_automations_flow_steps_authz_delete ON public.plg_automations_flow_steps;
|
|
2700
|
-
CREATE POLICY plg_automations_flow_steps_authz_delete ON public.plg_automations_flow_steps
|
|
2701
|
-
FOR DELETE TO authenticated USING (
|
|
2702
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2703
|
-
AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
|
|
2704
|
-
|
|
2705
|
-
-- Enrolments are READ-ONLY to the operator. They are written by the engine, and
|
|
2706
|
-
-- a hand-edited step pointer is a cadence nobody can explain afterwards.
|
|
2707
|
-
-- Leaving a flow is \`automations_flow_exit\`, not an UPDATE.
|
|
2708
|
-
DROP POLICY IF EXISTS plg_automations_enrollments_authz_select ON public.plg_automations_enrollments;
|
|
2709
|
-
CREATE POLICY plg_automations_enrollments_authz_select ON public.plg_automations_enrollments
|
|
2710
|
-
FOR SELECT TO authenticated USING (
|
|
2711
|
-
tenant_id = (SELECT app.current_tenant_id())
|
|
2712
|
-
AND (SELECT app.has_permission('automations.read', NULL::uuid)));
|
|
2713
|
-
|
|
2714
|
-
GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_automations_flows TO authenticated;
|
|
2715
|
-
GRANT ALL ON public.plg_automations_flows TO service_role;
|
|
2716
|
-
GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_automations_flow_steps TO authenticated;
|
|
2717
|
-
GRANT ALL ON public.plg_automations_flow_steps TO service_role;
|
|
2718
|
-
GRANT SELECT ON public.plg_automations_enrollments TO authenticated;
|
|
2719
|
-
GRANT ALL ON public.plg_automations_enrollments TO service_role;
|
|
2720
|
-
|
|
2721
|
-
INSERT INTO app.scaffold_registry
|
|
2722
|
-
(table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)
|
|
2723
|
-
VALUES
|
|
2724
|
-
('public', 'plg_automations_flows', 'automations.flow', 'automations', false, 'enforce', ARRAY[]::text[], false, 'unit_optional', false),
|
|
2725
|
-
('public', 'plg_automations_flow_steps', 'automations.flow_step', 'automations', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),
|
|
2726
|
-
('public', 'plg_automations_enrollments', 'automations.enrollment', 'automations', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)
|
|
2727
|
-
ON CONFLICT DO NOTHING;
|
|
2728
|
-
|
|
2729
|
-
-- \u2500\u2500 function \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2730
|
-
|
|
2731
|
-
-- Put somebody into a flow. Returns the enrolment, or NULL when the flow is
|
|
2732
|
-
-- inactive, has no steps, or the person is already in it.
|
|
2733
|
-
CREATE OR REPLACE FUNCTION public.automations_flow_enroll(
|
|
2734
|
-
p_tenant_id uuid, p_flow_id uuid, p_person_id uuid,
|
|
2735
|
-
p_subject_type text DEFAULT NULL, p_subject_id uuid DEFAULT NULL
|
|
2736
|
-
) RETURNS uuid
|
|
2737
|
-
LANGUAGE plpgsql SECURITY DEFINER
|
|
2738
|
-
SET search_path TO ''
|
|
2739
|
-
AS $$
|
|
2740
|
-
DECLARE v_first record; v_id uuid;
|
|
2741
|
-
BEGIN
|
|
2742
|
-
SELECT s.position, s.delay_minutes INTO v_first
|
|
2743
|
-
FROM public.plg_automations_flow_steps s
|
|
2744
|
-
JOIN public.plg_automations_flows f ON f.id = s.flow_id
|
|
2745
|
-
WHERE s.flow_id = p_flow_id AND f.tenant_id = p_tenant_id AND f.is_active
|
|
2746
|
-
ORDER BY s.position
|
|
2747
|
-
LIMIT 1;
|
|
2748
|
-
|
|
2749
|
-
-- An inactive flow, or one with no steps, enrols nobody. Silently: this is
|
|
2750
|
-
-- called from an event handler, and raising would fail the whole delivery.
|
|
2751
|
-
IF v_first.position IS NULL THEN RETURN NULL; END IF;
|
|
2752
|
-
|
|
2753
|
-
INSERT INTO public.plg_automations_enrollments
|
|
2754
|
-
(tenant_id, flow_id, person_id, subject_type, subject_id, current_position, next_run_at)
|
|
2755
|
-
VALUES
|
|
2756
|
-
(p_tenant_id, p_flow_id, p_person_id, p_subject_type, p_subject_id,
|
|
2757
|
-
v_first.position, now() + make_interval(mins => v_first.delay_minutes))
|
|
2758
|
-
ON CONFLICT DO NOTHING
|
|
2759
|
-
RETURNING id INTO v_id;
|
|
2760
|
-
|
|
2761
|
-
RETURN v_id;
|
|
2762
|
-
END $$;
|
|
2763
|
-
|
|
2764
|
-
-- Take somebody out of every flow they are in. The reason is kept, because
|
|
2765
|
-
-- "left because they replied" and "left because the deal was lost" are the two
|
|
2766
|
-
-- halves of whether a cadence works.
|
|
2767
|
-
CREATE OR REPLACE FUNCTION public.automations_flow_exit(
|
|
2768
|
-
p_tenant_id uuid, p_person_id uuid, p_reason text, p_flow_ids uuid[] DEFAULT NULL
|
|
2769
|
-
) RETURNS integer
|
|
2770
|
-
LANGUAGE plpgsql SECURITY DEFINER
|
|
2771
|
-
SET search_path TO ''
|
|
2772
|
-
AS $$
|
|
2773
|
-
DECLARE v_n integer; v_gone uuid[];
|
|
2774
|
-
BEGIN
|
|
2775
|
-
-- SCOPED TO THE FLOWS THAT ASKED. \`p_flow_ids\` NULL still means "every flow",
|
|
2776
|
-
-- which is what a manual "take this person out" wants; the event handler
|
|
2777
|
-
-- passes the flows whose own \`exit_events\` name the fact.
|
|
2778
|
-
--
|
|
2779
|
-
-- Without the scope, one flow declaring \`crm.deal_won\` pulled the person out
|
|
2780
|
-
-- of EVERY flow they were in and cancelled every queued step \u2014 including a
|
|
2781
|
-
-- flow that declared no exits at all, whose comment says it "only ends by
|
|
2782
|
-
-- running out of steps". Flow-level exit_events were meaningless the moment a
|
|
2783
|
-
-- second flow existed.
|
|
2784
|
-
WITH gone AS (
|
|
2785
|
-
UPDATE public.plg_automations_enrollments
|
|
2786
|
-
SET status = 'exited', exited_at = now(), exit_reason = p_reason,
|
|
2787
|
-
current_position = NULL, updated_at = now()
|
|
2788
|
-
WHERE tenant_id = p_tenant_id AND person_id = p_person_id AND status = 'active'
|
|
2789
|
-
AND (p_flow_ids IS NULL OR flow_id = ANY (p_flow_ids))
|
|
2790
|
-
RETURNING id
|
|
2791
|
-
)
|
|
2792
|
-
SELECT count(*)::integer, array_agg(id) INTO v_n, v_gone FROM gone;
|
|
2793
|
-
|
|
2794
|
-
-- A step already in the queue but not yet sent must not go out after the
|
|
2795
|
-
-- person left. \`cancelled\` was in the status CHECK from the beginning and
|
|
2796
|
-
-- nothing ever wrote it; this is what it was for.
|
|
2797
|
-
--
|
|
2798
|
-
-- Keyed by the ENROLMENTS that just left, not by \`flow:%\` \u2014 the wide pattern
|
|
2799
|
-
-- cancelled the pending steps of flows the person is still in.
|
|
2800
|
-
IF v_n > 0 AND to_regclass('public.plg_notifications_queue') IS NOT NULL THEN
|
|
2801
|
-
UPDATE public.plg_notifications_queue q
|
|
2802
|
-
SET status = 'cancelled', last_error = 'left the flow: ' || p_reason
|
|
2803
|
-
WHERE q.tenant_id = p_tenant_id
|
|
2804
|
-
AND q.person_id = p_person_id
|
|
2805
|
-
AND q.status = 'pending'
|
|
2806
|
-
AND split_part(q.dedupe_key, ':', 1) = 'flow'
|
|
2807
|
-
AND split_part(q.dedupe_key, ':', 2) = ANY (SELECT unnest(v_gone)::text);
|
|
2808
|
-
END IF;
|
|
2809
|
-
|
|
2810
|
-
RETURN v_n;
|
|
2811
|
-
END $$;
|
|
2812
|
-
|
|
2813
|
-
-- The tick. Claims due enrolments, runs ONE step each, moves the pointer.
|
|
2814
|
-
CREATE OR REPLACE FUNCTION public.automations_flows_run_due(p_limit integer DEFAULT 50)
|
|
2815
|
-
RETURNS jsonb
|
|
2816
|
-
LANGUAGE plpgsql SECURITY DEFINER
|
|
2817
|
-
SET search_path TO ''
|
|
2818
|
-
AS $$
|
|
2819
|
-
DECLARE
|
|
2820
|
-
e record; v_step record; v_next record; v_error text;
|
|
2821
|
-
v_ran integer := 0; v_done integer := 0; v_failed integer := 0;
|
|
2822
|
-
BEGIN
|
|
2823
|
-
-- JOINED to the flow, and \`f.is_active\` checked here rather than only in
|
|
2824
|
-
-- \`automations_flow_enroll\`. Switching a flow off used to stop new entrants
|
|
2825
|
-
-- and nothing else: everybody already mid-cadence kept receiving messages
|
|
2826
|
-
-- from a flow the operator had just turned off, which is the opposite of what
|
|
2827
|
-
-- the switch promises.
|
|
2828
|
-
FOR e IN
|
|
2829
|
-
SELECT en.* FROM public.plg_automations_enrollments en
|
|
2830
|
-
JOIN public.plg_automations_flows f ON f.id = en.flow_id AND f.is_active
|
|
2831
|
-
WHERE en.status = 'active' AND en.next_run_at <= now()
|
|
2832
|
-
ORDER BY en.next_run_at
|
|
2833
|
-
LIMIT greatest(p_limit, 0)
|
|
2834
|
-
FOR UPDATE OF en SKIP LOCKED
|
|
2835
|
-
LOOP
|
|
2836
|
-
SELECT * INTO v_step FROM public.plg_automations_flow_steps s
|
|
2837
|
-
WHERE s.flow_id = e.flow_id AND s.position = e.current_position;
|
|
2838
|
-
|
|
2839
|
-
-- The step was deleted while somebody stood on it. Move on rather than
|
|
2840
|
-
-- spinning on a pointer that will never resolve.
|
|
2841
|
-
IF v_step.id IS NULL THEN
|
|
2842
|
-
SELECT * INTO v_next FROM public.plg_automations_flow_steps s
|
|
2843
|
-
WHERE s.flow_id = e.flow_id AND s.position > coalesce(e.current_position, -1)
|
|
2844
|
-
ORDER BY s.position LIMIT 1;
|
|
2845
|
-
ELSE
|
|
2846
|
-
BEGIN
|
|
2847
|
-
IF v_step.kind = 'message' THEN
|
|
2848
|
-
PERFORM public.notifications_enqueue(
|
|
2849
|
-
e.tenant_id, v_step.template_key, e.person_id,
|
|
2850
|
-
jsonb_build_object('flow_id', e.flow_id, 'enrollment_id', e.id, 'step', v_step.position),
|
|
2851
|
-
'flow:' || e.id::text || ':' || v_step.position::text,
|
|
2852
|
-
now(),
|
|
2853
|
-
v_step.channel
|
|
2854
|
-
);
|
|
2855
|
-
ELSIF v_step.kind = 'task' AND to_regclass('public.tasks') IS NOT NULL THEN
|
|
2856
|
-
-- \`tasks_source_uniq (tenant_id, source, source_key)\` makes this
|
|
2857
|
-
-- idempotent for free \u2014 the same step cannot raise two tasks.
|
|
2858
|
-
INSERT INTO public.tasks
|
|
2859
|
-
(tenant_id, title, description, status, due_date, source, source_key)
|
|
2860
|
-
VALUES
|
|
2861
|
-
(e.tenant_id, v_step.task_title,
|
|
2862
|
-
'Automation flow step ' || v_step.position::text,
|
|
2863
|
-
'todo',
|
|
2864
|
-
CASE WHEN v_step.task_due_days IS NOT NULL
|
|
2865
|
-
THEN (now() + make_interval(days => v_step.task_due_days))::date END,
|
|
2866
|
-
'automation:flow', e.id::text || ':' || v_step.position::text)
|
|
2867
|
-
ON CONFLICT DO NOTHING;
|
|
2868
|
-
END IF;
|
|
2869
|
-
v_ran := v_ran + 1;
|
|
2870
|
-
EXCEPTION WHEN OTHERS THEN
|
|
2871
|
-
-- One bad step must not stop the tick for everybody else, so the
|
|
2872
|
-
-- enrolment still leaves this step: a template that no longer exists
|
|
2873
|
-
-- would otherwise wedge the person forever.
|
|
2874
|
-
--
|
|
2875
|
-
-- But it does NOT read as a finished cadence. The first cut let the
|
|
2876
|
-
-- loop fall through to \`completed\`, and because a failed step never
|
|
2877
|
-
-- produces a queue row, \`v_automations_flow_steps\` \u2014 which counts queue
|
|
2878
|
-
-- statuses \u2014 could not show it either. The screen built to answer
|
|
2879
|
-
-- "where do people stop" reported the person as having finished.
|
|
2880
|
-
v_failed := v_failed + 1;
|
|
2881
|
-
v_error := SQLERRM;
|
|
2882
|
-
RAISE NOTICE 'automations_flows_run_due: step % of enrolment % failed (%)',
|
|
2883
|
-
v_step.position, e.id, SQLERRM;
|
|
2884
|
-
END;
|
|
2885
|
-
|
|
2886
|
-
SELECT * INTO v_next FROM public.plg_automations_flow_steps s
|
|
2887
|
-
WHERE s.flow_id = e.flow_id AND s.position > v_step.position
|
|
2888
|
-
ORDER BY s.position LIMIT 1;
|
|
2889
|
-
END IF;
|
|
2890
|
-
|
|
2891
|
-
IF v_next.id IS NULL THEN
|
|
2892
|
-
UPDATE public.plg_automations_enrollments
|
|
2893
|
-
SET status = 'completed', current_position = NULL,
|
|
2894
|
-
exited_at = now(), updated_at = now(),
|
|
2895
|
-
-- A cadence that ended on a step that could not run did not
|
|
2896
|
-
-- finish; saying so is the difference between "nobody answers the
|
|
2897
|
-
-- third message" and "the third message never left".
|
|
2898
|
-
exit_reason = CASE WHEN v_error IS NOT NULL
|
|
2899
|
-
THEN 'last step failed: ' || v_error END
|
|
2900
|
-
WHERE id = e.id;
|
|
2901
|
-
v_done := v_done + 1;
|
|
2902
|
-
ELSE
|
|
2903
|
-
UPDATE public.plg_automations_enrollments
|
|
2904
|
-
SET current_position = v_next.position,
|
|
2905
|
-
next_run_at = now() + make_interval(mins => v_next.delay_minutes),
|
|
2906
|
-
updated_at = now()
|
|
2907
|
-
WHERE id = e.id;
|
|
2908
|
-
END IF;
|
|
2909
|
-
|
|
2910
|
-
v_next := NULL; v_step := NULL; v_error := NULL;
|
|
2911
|
-
END LOOP;
|
|
2912
|
-
|
|
2913
|
-
RETURN jsonb_build_object('steps_ran', v_ran, 'completed', v_done, 'failed', v_failed);
|
|
2914
|
-
END $$;
|
|
2915
|
-
|
|
2916
|
-
REVOKE ALL ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) FROM PUBLIC;
|
|
2917
|
-
GRANT EXECUTE ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) TO service_role;
|
|
2918
|
-
REVOKE ALL ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) FROM PUBLIC;
|
|
2919
|
-
GRANT EXECUTE ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) TO authenticated;
|
|
2920
|
-
GRANT EXECUTE ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) TO service_role;
|
|
2921
|
-
REVOKE ALL ON FUNCTION public.automations_flows_run_due(integer) FROM PUBLIC;
|
|
2922
|
-
GRANT EXECUTE ON FUNCTION public.automations_flows_run_due(integer) TO service_role;
|
|
2923
|
-
|
|
2924
|
-
-- \u2500\u2500 the two handlers the event log calls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2925
|
-
|
|
2926
|
-
-- Who the event is about.
|
|
2927
|
-
--
|
|
2928
|
-
-- \`consume_event_log\` calls a handler with \`to_jsonb(v_event)\` \u2014 the whole
|
|
2929
|
-
-- \`event_log\` ROW. So \`tenant_id\`, \`event_key\`, \`subject_type\` and \`subject_id\`
|
|
2930
|
-
-- are at the top level and everything the emitter chose to send is nested under
|
|
2931
|
-
-- \`payload\`. The first cut read \`person_id\` at the top level, where it never is:
|
|
2932
|
-
-- every delivery answered "payload carries no tenant, person or event", was
|
|
2933
|
-
-- marked DELIVERED, and the cadence enrolled nobody, ever, with nothing
|
|
2934
|
-
-- reporting it.
|
|
2935
|
-
--
|
|
2936
|
-
-- \`subject_id\` first, because that is the convention the shipped handlers use
|
|
2937
|
-
-- (\`plg_notifications_on_fulfillment_completed\` reads exactly that), and it is
|
|
2938
|
-
-- \`text\` on the row. The payload fallbacks are for emitters that name the person
|
|
2939
|
-
-- there instead.
|
|
2940
|
-
CREATE OR REPLACE FUNCTION public.automations_event_person(p_event jsonb)
|
|
2941
|
-
RETURNS uuid
|
|
2942
|
-
LANGUAGE sql IMMUTABLE
|
|
2943
|
-
SET search_path TO ''
|
|
2944
|
-
AS $$
|
|
2945
|
-
SELECT nullif(coalesce(
|
|
2946
|
-
CASE WHEN p_event ->> 'subject_type' IN ('lead', 'person', 'contact')
|
|
2947
|
-
THEN p_event ->> 'subject_id' END,
|
|
2948
|
-
p_event -> 'payload' ->> 'person_id',
|
|
2949
|
-
p_event -> 'payload' ->> 'lead_id',
|
|
2950
|
-
p_event -> 'payload' ->> 'contact_id',
|
|
2951
|
-
p_event ->> 'person_id',
|
|
2952
|
-
p_event ->> 'lead_id'
|
|
2953
|
-
), '')::uuid
|
|
2954
|
-
$$;
|
|
2955
|
-
|
|
2956
|
-
REVOKE ALL ON FUNCTION public.automations_event_person(jsonb) FROM PUBLIC;
|
|
2957
|
-
GRANT EXECUTE ON FUNCTION public.automations_event_person(jsonb) TO service_role;
|
|
2958
|
-
|
|
2959
|
-
-- Enrol on the flow's entry event. The payload names the person; a fact that
|
|
2960
|
-
-- does not carry one cannot start a cadence.
|
|
2961
|
-
CREATE OR REPLACE FUNCTION public.plg_automations_on_entry_event(p_event jsonb)
|
|
2962
|
-
RETURNS jsonb
|
|
2963
|
-
LANGUAGE plpgsql SECURITY DEFINER
|
|
2964
|
-
SET search_path TO ''
|
|
2965
|
-
AS $$
|
|
2966
|
-
DECLARE
|
|
2967
|
-
v_tenant uuid := nullif(p_event ->> 'tenant_id', '')::uuid;
|
|
2968
|
-
v_event text := p_event ->> 'event_key';
|
|
2969
|
-
v_person uuid := public.automations_event_person(p_event);
|
|
2970
|
-
f record; v_n integer := 0;
|
|
2971
|
-
BEGIN
|
|
2972
|
-
IF v_tenant IS NULL OR v_person IS NULL OR v_event IS NULL THEN
|
|
2973
|
-
RETURN jsonb_build_object('enrolled', 0, 'reason', 'event carries no tenant, person or key');
|
|
2974
|
-
END IF;
|
|
2975
|
-
|
|
2976
|
-
FOR f IN SELECT id FROM public.plg_automations_flows
|
|
2977
|
-
WHERE tenant_id = v_tenant AND entry_event = v_event AND is_active
|
|
2978
|
-
LOOP
|
|
2979
|
-
IF public.automations_flow_enroll(
|
|
2980
|
-
v_tenant, f.id, v_person,
|
|
2981
|
-
p_event ->> 'subject_type', nullif(p_event ->> 'subject_id', '')::uuid) IS NOT NULL THEN
|
|
2982
|
-
v_n := v_n + 1;
|
|
2983
|
-
END IF;
|
|
2984
|
-
END LOOP;
|
|
2985
|
-
|
|
2986
|
-
RETURN jsonb_build_object('enrolled', v_n);
|
|
2987
|
-
END $$;
|
|
2988
|
-
|
|
2989
|
-
-- Leave the flows whose own \`exit_events\` name this fact.
|
|
2990
|
-
CREATE OR REPLACE FUNCTION public.plg_automations_on_exit_event(p_event jsonb)
|
|
2991
|
-
RETURNS jsonb
|
|
2992
|
-
LANGUAGE plpgsql SECURITY DEFINER
|
|
2993
|
-
SET search_path TO ''
|
|
2994
|
-
AS $$
|
|
2995
|
-
DECLARE
|
|
2996
|
-
v_tenant uuid := nullif(p_event ->> 'tenant_id', '')::uuid;
|
|
2997
|
-
v_event text := p_event ->> 'event_key';
|
|
2998
|
-
v_person uuid := public.automations_event_person(p_event);
|
|
2999
|
-
v_flows uuid[]; v_n integer := 0;
|
|
3000
|
-
BEGIN
|
|
3001
|
-
IF v_tenant IS NULL OR v_person IS NULL OR v_event IS NULL THEN
|
|
3002
|
-
RETURN jsonb_build_object('exited', 0, 'reason', 'event carries no tenant, person or key');
|
|
3003
|
-
END IF;
|
|
3004
|
-
|
|
3005
|
-
SELECT array_agg(id) INTO v_flows
|
|
3006
|
-
FROM public.plg_automations_flows
|
|
3007
|
-
WHERE tenant_id = v_tenant AND is_active AND v_event = ANY (exit_events);
|
|
3008
|
-
|
|
3009
|
-
IF v_flows IS NOT NULL THEN
|
|
3010
|
-
v_n := public.automations_flow_exit(v_tenant, v_person, v_event, v_flows);
|
|
3011
|
-
END IF;
|
|
3012
|
-
|
|
3013
|
-
RETURN jsonb_build_object('exited', v_n);
|
|
3014
|
-
END $$;
|
|
3015
|
-
|
|
3016
|
-
REVOKE ALL ON FUNCTION public.plg_automations_on_entry_event(jsonb) FROM PUBLIC;
|
|
3017
|
-
GRANT EXECUTE ON FUNCTION public.plg_automations_on_entry_event(jsonb) TO service_role;
|
|
3018
|
-
REVOKE ALL ON FUNCTION public.plg_automations_on_exit_event(jsonb) FROM PUBLIC;
|
|
3019
|
-
GRANT EXECUTE ON FUNCTION public.plg_automations_on_exit_event(jsonb) TO service_role;
|
|
3020
|
-
|
|
3021
|
-
-- \u2500\u2500 subscription \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
3022
|
-
|
|
3023
|
-
-- The manifest DECLARES the reaction; this is what makes the event log call it.
|
|
3024
|
-
-- Both handlers on every CRM fact, because which fact opens a cadence and which
|
|
3025
|
-
-- closes it is the operator's choice: the handler looks the flow up and returns
|
|
3026
|
-
-- immediately when no flow in that tenant names the event.
|
|
3027
|
-
-- Written out one call per line rather than looped over an array. The loop was
|
|
3028
|
-
-- shorter and \`check-event-contract\` could not read it: its registration parser
|
|
3029
|
-
-- matches literal arguments, so a FOREACH registering fourteen subscriptions
|
|
3030
|
-
-- looked like zero. Same lesson as the manifest side \u2014 the gate reads source,
|
|
3031
|
-
-- so the source has to say it.
|
|
3032
|
-
SELECT public.register_event_subscription('automations', 'crm.lead_created', 'plg_automations_on_entry_event',
|
|
3033
|
-
'Enrol into flows whose entry event is crm.lead_created', 5);
|
|
3034
|
-
SELECT public.register_event_subscription('automations', 'crm.lead_created', 'plg_automations_on_exit_event',
|
|
3035
|
-
'Leave flows that exit on crm.lead_created', 5);
|
|
3036
|
-
SELECT public.register_event_subscription('automations', 'crm.stage_changed', 'plg_automations_on_entry_event',
|
|
3037
|
-
'Enrol into flows whose entry event is crm.stage_changed', 5);
|
|
3038
|
-
SELECT public.register_event_subscription('automations', 'crm.stage_changed', 'plg_automations_on_exit_event',
|
|
3039
|
-
'Leave flows that exit on crm.stage_changed', 5);
|
|
3040
|
-
SELECT public.register_event_subscription('automations', 'crm.quote_sent', 'plg_automations_on_entry_event',
|
|
3041
|
-
'Enrol into flows whose entry event is crm.quote_sent', 5);
|
|
3042
|
-
SELECT public.register_event_subscription('automations', 'crm.quote_sent', 'plg_automations_on_exit_event',
|
|
3043
|
-
'Leave flows that exit on crm.quote_sent', 5);
|
|
3044
|
-
SELECT public.register_event_subscription('automations', 'crm.quote_approved', 'plg_automations_on_entry_event',
|
|
3045
|
-
'Enrol into flows whose entry event is crm.quote_approved', 5);
|
|
3046
|
-
SELECT public.register_event_subscription('automations', 'crm.quote_approved', 'plg_automations_on_exit_event',
|
|
3047
|
-
'Leave flows that exit on crm.quote_approved', 5);
|
|
3048
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_won', 'plg_automations_on_entry_event',
|
|
3049
|
-
'Enrol into flows whose entry event is crm.deal_won', 5);
|
|
3050
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_won', 'plg_automations_on_exit_event',
|
|
3051
|
-
'Leave flows that exit on crm.deal_won', 5);
|
|
3052
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_lost', 'plg_automations_on_entry_event',
|
|
3053
|
-
'Enrol into flows whose entry event is crm.deal_lost', 5);
|
|
3054
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_lost', 'plg_automations_on_exit_event',
|
|
3055
|
-
'Leave flows that exit on crm.deal_lost', 5);
|
|
3056
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_idle', 'plg_automations_on_entry_event',
|
|
3057
|
-
'Enrol into flows whose entry event is crm.deal_idle', 5);
|
|
3058
|
-
SELECT public.register_event_subscription('automations', 'crm.deal_idle', 'plg_automations_on_exit_event',
|
|
3059
|
-
'Leave flows that exit on crm.deal_idle', 5);
|
|
3060
|
-
|
|
3061
|
-
-- \u2500\u2500 view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
3062
|
-
|
|
3063
|
-
-- Per-step numbers, which is the question a cadence is judged by: where do
|
|
3064
|
-
-- people stop. Aggregating per FLOW would hide that the third message is the
|
|
3065
|
-
-- one nobody answers.
|
|
3066
|
-
CREATE OR REPLACE VIEW public.v_automations_flow_steps WITH (security_invoker='true') AS
|
|
3067
|
-
SELECT
|
|
3068
|
-
s.tenant_id, s.flow_id, s.id AS step_id, s.position, s.kind,
|
|
3069
|
-
s.template_key, s.channel, s.delay_minutes, s.task_title,
|
|
3070
|
-
count(q.id) FILTER (WHERE q.id IS NOT NULL) AS queued,
|
|
3071
|
-
count(q.id) FILTER (WHERE q.status = 'sent') AS sent,
|
|
3072
|
-
count(q.id) FILTER (WHERE q.status = 'blocked') AS blocked,
|
|
3073
|
-
count(q.id) FILTER (WHERE q.status = 'failed') AS failed,
|
|
3074
|
-
count(q.id) FILTER (WHERE q.status = 'cancelled') AS cancelled
|
|
3075
|
-
FROM public.plg_automations_flow_steps s
|
|
3076
|
-
LEFT JOIN public.plg_automations_enrollments e ON e.flow_id = s.flow_id
|
|
3077
|
-
LEFT JOIN public.plg_notifications_queue q
|
|
3078
|
-
ON q.dedupe_key = 'flow:' || e.id::text || ':' || s.position::text
|
|
3079
|
-
GROUP BY s.tenant_id, s.flow_id, s.id, s.position, s.kind,
|
|
3080
|
-
s.template_key, s.channel, s.delay_minutes, s.task_title;
|
|
3081
|
-
|
|
3082
|
-
GRANT SELECT ON public.v_automations_flow_steps TO authenticated;
|
|
3083
|
-
GRANT SELECT ON public.v_automations_flow_steps TO service_role;
|
|
3084
|
-
`;
|
|
3085
|
-
var MIGRATION_002_THE_ENGINE_IS_SERVER_ONLY = `-- 002_the_engine_is_server_only.sql
|
|
3086
|
-
--
|
|
3087
|
-
-- 001 meant the cadence engine to be service_role only, and wrote
|
|
3088
|
-
-- \`REVOKE ALL ... FROM PUBLIC\`. That does not undo the pool's default
|
|
3089
|
-
-- privileges, which grant EXECUTE to \`authenticated\` on every new function in
|
|
3090
|
-
-- public \u2014 so on the live pool any logged-in user of any tenant could enrol a
|
|
3091
|
-
-- person into another tenant's flow, exit them, or advance every tenant's
|
|
3092
|
-
-- cadences at once, all SECURITY DEFINER with no caller check.
|
|
3093
|
-
--
|
|
3094
|
-
-- Callers are all server-side: \`event_runner_tick\` (pg_cron, as postgres)
|
|
3095
|
-
-- calls \`automations_flows_run_due\`, the event log calls the two handlers, and
|
|
3096
|
-
-- the handlers call enrol/exit. No screen, edge function or agent tool does.
|
|
3097
|
-
-- \`automations_flow_exit\` was granted to \`authenticated\` for a manual
|
|
3098
|
-
-- "take this person out" that was never built; it goes too, and comes back
|
|
3099
|
-
-- behind a tenant + permission check when a screen needs it.
|
|
3100
|
-
|
|
3101
|
-
REVOKE ALL ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) FROM PUBLIC, anon, authenticated;
|
|
3102
|
-
GRANT EXECUTE ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) TO service_role;
|
|
3103
|
-
|
|
3104
|
-
REVOKE ALL ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) FROM PUBLIC, anon, authenticated;
|
|
3105
|
-
GRANT EXECUTE ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) TO service_role;
|
|
3106
|
-
|
|
3107
|
-
REVOKE ALL ON FUNCTION public.automations_flows_run_due(integer) FROM PUBLIC, anon, authenticated;
|
|
3108
|
-
GRANT EXECUTE ON FUNCTION public.automations_flows_run_due(integer) TO service_role;
|
|
3109
|
-
|
|
3110
|
-
REVOKE ALL ON FUNCTION public.plg_automations_on_entry_event(jsonb) FROM PUBLIC, anon, authenticated;
|
|
3111
|
-
GRANT EXECUTE ON FUNCTION public.plg_automations_on_entry_event(jsonb) TO service_role;
|
|
3112
|
-
|
|
3113
|
-
REVOKE ALL ON FUNCTION public.plg_automations_on_exit_event(jsonb) FROM PUBLIC, anon, authenticated;
|
|
3114
|
-
GRANT EXECUTE ON FUNCTION public.plg_automations_on_exit_event(jsonb) TO service_role;
|
|
3115
|
-
`;
|
|
3116
|
-
var MIGRATIONS = [
|
|
3117
|
-
{ id: "000_baseline", sql: MIGRATION_000_BASELINE },
|
|
3118
|
-
{ id: "001_the_flow_has_steps", sql: MIGRATION_001_THE_FLOW_HAS_STEPS },
|
|
3119
|
-
{ id: "002_the_engine_is_server_only", sql: MIGRATION_002_THE_ENGINE_IS_SERVER_ONLY }
|
|
3120
|
-
];
|
|
3121
|
-
|
|
3122
|
-
// src/index.ts
|
|
161
|
+
var AutomationsList = lazyComponent(() => import('./AutomationsList-3UTTQSIX.js').then((m) => m.AutomationsList));
|
|
162
|
+
var AutomationDetailPage = React.lazy(() => import('./AutomationDetailPage-UHY7KHQK.js').then((m) => ({ default: m.AutomationDetailPage })));
|
|
163
|
+
var FlowsPage = React.lazy(() => import('./FlowsPage-6SUXT2LP.js').then((m) => ({ default: m.FlowsPage })));
|
|
3123
164
|
function createAutomationsPlugin(options) {
|
|
3124
165
|
const connection = resolveFayzAgentConnection();
|
|
3125
|
-
const
|
|
166
|
+
const store = options?.store ?? (connection ? createFayzTemplateStore(connection) : createSupabaseTemplateStore());
|
|
3126
167
|
startEventLog();
|
|
3127
168
|
const inSettings = options?.placement !== "nav";
|
|
3128
|
-
const ListPage = () =>
|
|
169
|
+
const ListPage = () => React.createElement(AutomationsList, { store });
|
|
3129
170
|
ListPage.displayName = "AutomationsList";
|
|
3130
|
-
const SettingsListPage = () =>
|
|
171
|
+
const SettingsListPage = () => React.createElement(AutomationsList, { store, variant: "panel", basePath: "/settings/automations" });
|
|
3131
172
|
SettingsListPage.displayName = "AutomationsSettings";
|
|
3132
|
-
const RailDetail = ({ params, onClose }) =>
|
|
173
|
+
const RailDetail = ({ params, onClose }) => React.createElement(AutomationDetailPage, {
|
|
3133
174
|
eventKey: params.eventKey,
|
|
3134
175
|
channel: params.channel,
|
|
3135
|
-
store
|
|
176
|
+
store,
|
|
3136
177
|
backTo: inSettings ? "/settings/automations" : "/automations",
|
|
3137
178
|
embedded: true,
|
|
3138
179
|
onDone: onClose
|
|
@@ -3235,7 +276,8 @@ function createAutomationsPlugin(options) {
|
|
|
3235
276
|
widgets: []
|
|
3236
277
|
};
|
|
3237
278
|
}
|
|
279
|
+
var CadenceFlowsSurface = lazyComponent(() => import('./FlowsPage-6SUXT2LP.js').then((m) => m.FlowsPage));
|
|
3238
280
|
|
|
3239
|
-
export {
|
|
281
|
+
export { CadenceFlowsSurface, createAutomationsPlugin, createSupabaseTemplateStore };
|
|
3240
282
|
//# sourceMappingURL=index.js.map
|
|
3241
283
|
//# sourceMappingURL=index.js.map
|