@fayz-ai/plugin-automations 0.15.29 → 0.15.31
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
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
|
|
2
|
+
import { Plus, ChevronRight, ListChecks, MessageSquare, Clock, Trash2, Workflow } from 'lucide-react';
|
|
3
|
+
import { toast, Card, PageHeaderActions, Button, Switch, DataTable, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter } from '@fayz-ai/ui';
|
|
4
|
+
import { useTranslation, errorMessage, usePluginRuntimeOptional, getActiveTenantId, getSupabaseClientOptional } from '@fayz-ai/core';
|
|
5
|
+
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
6
|
+
import { PageActions } from '@fayz-ai/admin';
|
|
7
|
+
|
|
8
|
+
// src/views/FlowsPage.tsx
|
|
9
|
+
function CadenceComposer({ open, onClose, onCreate }) {
|
|
10
|
+
const t = useTranslation();
|
|
11
|
+
const runtime = usePluginRuntimeOptional();
|
|
12
|
+
const events = runtime?.events ?? [];
|
|
13
|
+
const [name, setName] = React.useState("");
|
|
14
|
+
const [entryEvent, setEntryEvent] = React.useState("");
|
|
15
|
+
const [exitEvent, setExitEvent] = React.useState("");
|
|
16
|
+
const [saving, setSaving] = React.useState(false);
|
|
17
|
+
React.useEffect(() => {
|
|
18
|
+
if (!open) return;
|
|
19
|
+
setName("");
|
|
20
|
+
setExitEvent("");
|
|
21
|
+
setEntryEvent(events.find((e) => e.name === "crm.lead_created")?.name ?? events[0]?.name ?? "");
|
|
22
|
+
}, [open]);
|
|
23
|
+
const entry = events.find((e) => e.name === entryEvent);
|
|
24
|
+
async function submit() {
|
|
25
|
+
if (!name.trim() || !entryEvent || saving) return;
|
|
26
|
+
setSaving(true);
|
|
27
|
+
try {
|
|
28
|
+
await onCreate({
|
|
29
|
+
name: name.trim(),
|
|
30
|
+
entryEvent,
|
|
31
|
+
exitEvents: exitEvent ? [exitEvent] : []
|
|
32
|
+
});
|
|
33
|
+
onClose();
|
|
34
|
+
} catch (e) {
|
|
35
|
+
toast.error(errorMessage(e));
|
|
36
|
+
} finally {
|
|
37
|
+
setSaving(false);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
|
|
41
|
+
if (!o) onClose();
|
|
42
|
+
}, children: /* @__PURE__ */ jsxs(ModalContent, { size: "md", children: [
|
|
43
|
+
/* @__PURE__ */ jsx(ModalHeader, { children: /* @__PURE__ */ jsx(ModalTitle, { children: t("automations.flow.newTitle") }) }),
|
|
44
|
+
/* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
|
|
45
|
+
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
46
|
+
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.nameLabel") }),
|
|
47
|
+
/* @__PURE__ */ jsx(Input, { value: name, onChange: (e) => setName(e.target.value), placeholder: t("automations.flow.namePlaceholder") })
|
|
48
|
+
] }),
|
|
49
|
+
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
50
|
+
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.entryLabel") }),
|
|
51
|
+
events.length > 0 ? /* @__PURE__ */ jsxs(Select, { value: entryEvent, onValueChange: setEntryEvent, children: [
|
|
52
|
+
/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("automations.flow.entryPlaceholder") }) }),
|
|
53
|
+
/* @__PURE__ */ jsx(SelectContent, { children: events.map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name)) })
|
|
54
|
+
] }) : /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground", children: t("automations.flow.noEvents") }),
|
|
55
|
+
entry?.trigger && /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: entry.trigger })
|
|
56
|
+
] }),
|
|
57
|
+
/* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
|
|
58
|
+
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.exitLabel") }),
|
|
59
|
+
/* @__PURE__ */ jsxs(Select, { value: exitEvent || "__none__", onValueChange: (v) => setExitEvent(v === "__none__" ? "" : v), children: [
|
|
60
|
+
/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
61
|
+
/* @__PURE__ */ jsxs(SelectContent, { children: [
|
|
62
|
+
/* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t("automations.flow.exitNone") }),
|
|
63
|
+
events.filter((e) => e.name !== entryEvent).map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name))
|
|
64
|
+
] })
|
|
65
|
+
] }),
|
|
66
|
+
/* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: t("automations.flow.exitHint") })
|
|
67
|
+
] }),
|
|
68
|
+
/* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2 rounded-lg bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground", children: [
|
|
69
|
+
/* @__PURE__ */ jsx(Workflow, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }),
|
|
70
|
+
t("automations.flow.bornOffHint")
|
|
71
|
+
] })
|
|
72
|
+
] }),
|
|
73
|
+
/* @__PURE__ */ jsxs(ModalFooter, { children: [
|
|
74
|
+
/* @__PURE__ */ jsx(Button, { variant: "outline", onClick: onClose, children: t("common.cancel") }),
|
|
75
|
+
/* @__PURE__ */ jsx(Button, { onClick: () => {
|
|
76
|
+
void submit();
|
|
77
|
+
}, disabled: saving || !name.trim() || !entryEvent, children: t("automations.flow.create") })
|
|
78
|
+
] })
|
|
79
|
+
] }) });
|
|
80
|
+
}
|
|
81
|
+
var FLOWS = "plg_automations_flows";
|
|
82
|
+
var STEPS = "plg_automations_flow_steps";
|
|
83
|
+
var ENROLLMENTS = "plg_automations_enrollments";
|
|
84
|
+
var STEP_STATS = "v_automations_flow_steps";
|
|
85
|
+
function rowToFlow(r) {
|
|
86
|
+
return {
|
|
87
|
+
id: r.id,
|
|
88
|
+
tenantId: r.tenant_id,
|
|
89
|
+
name: r.name,
|
|
90
|
+
description: r.description ?? null,
|
|
91
|
+
entryEvent: r.entry_event,
|
|
92
|
+
exitEvents: Array.isArray(r.exit_events) ? r.exit_events : [],
|
|
93
|
+
isActive: r.is_active === true,
|
|
94
|
+
createdAt: r.created_at,
|
|
95
|
+
updatedAt: r.updated_at ?? r.created_at
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function rowToStepStats(r) {
|
|
99
|
+
return {
|
|
100
|
+
id: r.step_id ?? r.id,
|
|
101
|
+
flowId: r.flow_id,
|
|
102
|
+
position: r.position,
|
|
103
|
+
delayMinutes: r.delay_minutes ?? 0,
|
|
104
|
+
kind: r.kind === "task" ? "task" : "message",
|
|
105
|
+
templateKey: r.template_key ?? null,
|
|
106
|
+
channel: r.channel ?? null,
|
|
107
|
+
taskTitle: r.task_title ?? null,
|
|
108
|
+
taskDueDays: r.task_due_days ?? null,
|
|
109
|
+
queued: Number(r.queued ?? 0),
|
|
110
|
+
sent: Number(r.sent ?? 0),
|
|
111
|
+
blocked: Number(r.blocked ?? 0),
|
|
112
|
+
failed: Number(r.failed ?? 0),
|
|
113
|
+
cancelled: Number(r.cancelled ?? 0)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function nextPosition(steps) {
|
|
117
|
+
if (steps.length === 0) return 10;
|
|
118
|
+
return Math.max(...steps.map((s) => s.position)) + 10;
|
|
119
|
+
}
|
|
120
|
+
function describeDelay(minutes, t) {
|
|
121
|
+
if (minutes <= 0) return t("automations.flow.delayNow");
|
|
122
|
+
if (minutes % 1440 === 0) return t("automations.flow.delayDays", { count: String(minutes / 1440) });
|
|
123
|
+
if (minutes % 60 === 0) return t("automations.flow.delayHours", { count: String(minutes / 60) });
|
|
124
|
+
return t("automations.flow.delayMinutes", { count: String(minutes) });
|
|
125
|
+
}
|
|
126
|
+
function createSupabaseFlowStore() {
|
|
127
|
+
function client() {
|
|
128
|
+
const supabase = getSupabaseClientOptional();
|
|
129
|
+
if (!supabase) throw new Error("Supabase not initialized");
|
|
130
|
+
return supabase;
|
|
131
|
+
}
|
|
132
|
+
const store2 = {
|
|
133
|
+
async listFlows() {
|
|
134
|
+
const { data, error } = await client().from(FLOWS).select("*").order("name");
|
|
135
|
+
if (error) throw new Error(error.message);
|
|
136
|
+
return (data ?? []).map(rowToFlow);
|
|
137
|
+
},
|
|
138
|
+
async saveFlow(input) {
|
|
139
|
+
const row = {
|
|
140
|
+
name: input.name,
|
|
141
|
+
description: input.description ?? null,
|
|
142
|
+
entry_event: input.entryEvent,
|
|
143
|
+
exit_events: input.exitEvents ?? []
|
|
144
|
+
};
|
|
145
|
+
if (input.id) {
|
|
146
|
+
const { data: data2, error: error2 } = await client().from(FLOWS).update(row).eq("id", input.id).select().single();
|
|
147
|
+
if (error2) throw new Error(error2.message);
|
|
148
|
+
return rowToFlow(data2);
|
|
149
|
+
}
|
|
150
|
+
row.tenant_id = getActiveTenantId();
|
|
151
|
+
const { data, error } = await client().from(FLOWS).insert(row).select().single();
|
|
152
|
+
if (error) throw new Error(error.message);
|
|
153
|
+
return rowToFlow(data);
|
|
154
|
+
},
|
|
155
|
+
async setFlowActive(id, isActive) {
|
|
156
|
+
const { error } = await client().from(FLOWS).update({ is_active: isActive, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id);
|
|
157
|
+
if (error) throw new Error(error.message);
|
|
158
|
+
},
|
|
159
|
+
async deleteFlow(id) {
|
|
160
|
+
const { error } = await client().from(FLOWS).delete().eq("id", id);
|
|
161
|
+
if (error) throw new Error(error.message);
|
|
162
|
+
},
|
|
163
|
+
async listSteps(flowId) {
|
|
164
|
+
const { data, error } = await client().from(STEP_STATS).select("*").eq("flow_id", flowId).order("position");
|
|
165
|
+
if (error) throw new Error(error.message);
|
|
166
|
+
return (data ?? []).map(rowToStepStats);
|
|
167
|
+
},
|
|
168
|
+
async saveStep(flowId, input) {
|
|
169
|
+
const row = {
|
|
170
|
+
flow_id: flowId,
|
|
171
|
+
position: input.position,
|
|
172
|
+
delay_minutes: input.delayMinutes ?? 0,
|
|
173
|
+
kind: input.kind ?? "message",
|
|
174
|
+
template_key: input.kind === "task" ? null : input.templateKey ?? null,
|
|
175
|
+
channel: input.kind === "task" ? null : input.channel ?? null,
|
|
176
|
+
task_title: input.kind === "task" ? input.taskTitle ?? null : null,
|
|
177
|
+
task_due_days: input.kind === "task" ? input.taskDueDays ?? null : null
|
|
178
|
+
};
|
|
179
|
+
if (input.id) {
|
|
180
|
+
const { error: error2 } = await client().from(STEPS).update(row).eq("id", input.id);
|
|
181
|
+
if (error2) throw new Error(error2.message);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
row.tenant_id = getActiveTenantId();
|
|
185
|
+
const { error } = await client().from(STEPS).insert(row);
|
|
186
|
+
if (error) throw new Error(error.message);
|
|
187
|
+
},
|
|
188
|
+
async deleteStep(id) {
|
|
189
|
+
const { error } = await client().from(STEPS).delete().eq("id", id);
|
|
190
|
+
if (error) throw new Error(error.message);
|
|
191
|
+
},
|
|
192
|
+
async countsFor(flowId) {
|
|
193
|
+
const { data, error } = await client().from(ENROLLMENTS).select("status").eq("flow_id", flowId);
|
|
194
|
+
if (error) throw new Error(error.message);
|
|
195
|
+
const rows = data ?? [];
|
|
196
|
+
return {
|
|
197
|
+
active: rows.filter((r) => r.status === "active").length,
|
|
198
|
+
completed: rows.filter((r) => r.status === "completed").length,
|
|
199
|
+
exited: rows.filter((r) => r.status === "exited").length
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
return store2;
|
|
204
|
+
}
|
|
205
|
+
var store = createSupabaseFlowStore();
|
|
206
|
+
var DELAY_CHOICES = [0, 60, 1440, 2880, 4320, 10080];
|
|
207
|
+
function useStepColumns(onDelete) {
|
|
208
|
+
const t = useTranslation();
|
|
209
|
+
return useMemo(() => [
|
|
210
|
+
{
|
|
211
|
+
accessorKey: "position",
|
|
212
|
+
header: "#",
|
|
213
|
+
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-muted-foreground", children: getValue() })
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
id: "step",
|
|
217
|
+
header: t("automations.flow.colStep"),
|
|
218
|
+
cell: ({ row }) => {
|
|
219
|
+
const s = row.original;
|
|
220
|
+
const isTask = s.kind === "task";
|
|
221
|
+
return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [
|
|
222
|
+
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" }),
|
|
223
|
+
isTask ? s.taskTitle : s.templateKey,
|
|
224
|
+
!isTask && s.channel && /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: s.channel })
|
|
225
|
+
] });
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
accessorKey: "delayMinutes",
|
|
230
|
+
header: t("automations.flow.colWait"),
|
|
231
|
+
cell: ({ getValue }) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs text-muted-foreground", children: [
|
|
232
|
+
/* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
|
|
233
|
+
describeDelay(getValue(), t)
|
|
234
|
+
] })
|
|
235
|
+
},
|
|
236
|
+
// The scoreboard. Zeroes are shown rather than hidden: a step that has never
|
|
237
|
+
// sent is the finding, not an empty cell.
|
|
238
|
+
{
|
|
239
|
+
accessorKey: "queued",
|
|
240
|
+
header: t("automations.flow.colQueued"),
|
|
241
|
+
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
accessorKey: "sent",
|
|
245
|
+
header: t("automations.flow.colSent"),
|
|
246
|
+
cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
accessorKey: "blocked",
|
|
250
|
+
header: t("automations.flow.colBlocked"),
|
|
251
|
+
cell: ({ getValue }) => {
|
|
252
|
+
const n = getValue();
|
|
253
|
+
return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-warning" : ""}`, children: n });
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
accessorKey: "failed",
|
|
258
|
+
header: t("automations.flow.colFailed"),
|
|
259
|
+
cell: ({ getValue }) => {
|
|
260
|
+
const n = getValue();
|
|
261
|
+
return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-destructive" : ""}`, children: n });
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
id: "actions",
|
|
266
|
+
header: "",
|
|
267
|
+
cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
|
|
268
|
+
Button,
|
|
269
|
+
{
|
|
270
|
+
variant: "bare",
|
|
271
|
+
size: "bare",
|
|
272
|
+
onClick: (e) => {
|
|
273
|
+
e.stopPropagation();
|
|
274
|
+
onDelete(row.original.id);
|
|
275
|
+
},
|
|
276
|
+
title: t("automations.flow.deleteStep"),
|
|
277
|
+
className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-destructive",
|
|
278
|
+
children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
|
|
279
|
+
}
|
|
280
|
+
) })
|
|
281
|
+
}
|
|
282
|
+
], [t, onDelete]);
|
|
283
|
+
}
|
|
284
|
+
var COMPOSER_TRIGGER = "h-auto w-auto gap-2 rounded-md border-border px-2 py-1.5 shadow-none";
|
|
285
|
+
function StepComposer({ steps, onAdd }) {
|
|
286
|
+
const t = useTranslation();
|
|
287
|
+
const [kind, setKind] = useState("message");
|
|
288
|
+
const [delay, setDelay] = useState(1440);
|
|
289
|
+
const [value, setValue] = useState("");
|
|
290
|
+
const submit = () => {
|
|
291
|
+
if (!value.trim()) {
|
|
292
|
+
toast.error(t(kind === "task" ? "automations.flow.needTitle" : "automations.flow.needTemplate"));
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
onAdd({
|
|
296
|
+
kind,
|
|
297
|
+
delayMinutes: delay,
|
|
298
|
+
position: nextPosition(steps),
|
|
299
|
+
...kind === "task" ? { taskTitle: value.trim() } : { templateKey: value.trim() }
|
|
300
|
+
});
|
|
301
|
+
setValue("");
|
|
302
|
+
};
|
|
303
|
+
return /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-dashed p-3", children: [
|
|
304
|
+
/* @__PURE__ */ jsxs(Select, { value: kind, onValueChange: (v) => {
|
|
305
|
+
setKind(v);
|
|
306
|
+
setValue("");
|
|
307
|
+
}, children: [
|
|
308
|
+
/* @__PURE__ */ jsx(SelectTrigger, { className: COMPOSER_TRIGGER, children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
309
|
+
/* @__PURE__ */ jsxs(SelectContent, { children: [
|
|
310
|
+
/* @__PURE__ */ jsx(SelectItem, { value: "message", children: t("automations.flow.kindMessage") }),
|
|
311
|
+
/* @__PURE__ */ jsx(SelectItem, { value: "task", children: t("automations.flow.kindTask") })
|
|
312
|
+
] })
|
|
313
|
+
] }),
|
|
314
|
+
/* @__PURE__ */ jsxs(Select, { value: String(delay), onValueChange: (v) => setDelay(Number(v)), children: [
|
|
315
|
+
/* @__PURE__ */ jsx(SelectTrigger, { className: COMPOSER_TRIGGER, children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
316
|
+
/* @__PURE__ */ jsx(SelectContent, { children: DELAY_CHOICES.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: String(m), children: describeDelay(m, t) }, m)) })
|
|
317
|
+
] }),
|
|
318
|
+
/* @__PURE__ */ jsx("div", { className: "min-w-[200px] flex-1", children: /* @__PURE__ */ jsx(
|
|
319
|
+
Input,
|
|
320
|
+
{
|
|
321
|
+
value,
|
|
322
|
+
onChange: (e) => setValue(e.target.value),
|
|
323
|
+
onKeyDown: (e) => {
|
|
324
|
+
if (e.key === "Enter") submit();
|
|
325
|
+
},
|
|
326
|
+
placeholder: t(kind === "task" ? "automations.flow.titlePlaceholder" : "automations.flow.templatePlaceholder"),
|
|
327
|
+
className: "h-auto rounded-md border-border bg-background px-2 py-1.5 shadow-none"
|
|
328
|
+
}
|
|
329
|
+
) }),
|
|
330
|
+
/* @__PURE__ */ jsxs(Button, { onClick: submit, className: "gap-1", children: [
|
|
331
|
+
/* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
|
|
332
|
+
t("automations.flow.addStep")
|
|
333
|
+
] })
|
|
334
|
+
] });
|
|
335
|
+
}
|
|
336
|
+
function FlowsPage() {
|
|
337
|
+
const t = useTranslation();
|
|
338
|
+
const [flows, setFlows] = useState([]);
|
|
339
|
+
const [loading, setLoading] = useState(true);
|
|
340
|
+
const [selectedId, setSelectedId] = useState(null);
|
|
341
|
+
const [steps, setSteps] = useState([]);
|
|
342
|
+
const [counts, setCounts] = useState(null);
|
|
343
|
+
const [composerOpen, setComposerOpen] = useState(false);
|
|
344
|
+
const load = useCallback(async () => {
|
|
345
|
+
setLoading(true);
|
|
346
|
+
try {
|
|
347
|
+
setFlows(await store.listFlows());
|
|
348
|
+
} catch (e) {
|
|
349
|
+
toast.error(errorMessage(e));
|
|
350
|
+
} finally {
|
|
351
|
+
setLoading(false);
|
|
352
|
+
}
|
|
353
|
+
}, []);
|
|
354
|
+
const selectedRef = useRef(null);
|
|
355
|
+
selectedRef.current = selectedId;
|
|
356
|
+
const loadDetail = useCallback(async (flowId) => {
|
|
357
|
+
try {
|
|
358
|
+
const [s, c] = await Promise.all([store.listSteps(flowId), store.countsFor(flowId)]);
|
|
359
|
+
if (selectedRef.current !== flowId) return;
|
|
360
|
+
setSteps(s);
|
|
361
|
+
setCounts(c);
|
|
362
|
+
} catch (e) {
|
|
363
|
+
toast.error(errorMessage(e));
|
|
364
|
+
}
|
|
365
|
+
}, []);
|
|
366
|
+
const deleteStep = useCallback((id) => {
|
|
367
|
+
void (async () => {
|
|
368
|
+
try {
|
|
369
|
+
await store.deleteStep(id);
|
|
370
|
+
if (selectedId) await loadDetail(selectedId);
|
|
371
|
+
} catch (e) {
|
|
372
|
+
toast.error(errorMessage(e));
|
|
373
|
+
}
|
|
374
|
+
})();
|
|
375
|
+
}, [selectedId, loadDetail]);
|
|
376
|
+
const stepColumns = useStepColumns(deleteStep);
|
|
377
|
+
useEffect(() => {
|
|
378
|
+
void load();
|
|
379
|
+
}, [load]);
|
|
380
|
+
useEffect(() => {
|
|
381
|
+
setSteps([]);
|
|
382
|
+
setCounts(null);
|
|
383
|
+
if (selectedId) void loadDetail(selectedId);
|
|
384
|
+
}, [selectedId, loadDetail]);
|
|
385
|
+
flows.find((f) => f.id === selectedId) ?? null;
|
|
386
|
+
async function createFlow(input) {
|
|
387
|
+
const flow = await store.saveFlow(input);
|
|
388
|
+
await load();
|
|
389
|
+
setSelectedId(flow.id);
|
|
390
|
+
toast.success(t("automations.flow.created"));
|
|
391
|
+
}
|
|
392
|
+
async function toggleActive(flow) {
|
|
393
|
+
if (!flow.isActive) {
|
|
394
|
+
const s = await store.listSteps(flow.id);
|
|
395
|
+
if (s.length === 0) {
|
|
396
|
+
toast.error(t("automations.flow.needStepsToActivate"));
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
try {
|
|
401
|
+
await store.setFlowActive(flow.id, !flow.isActive);
|
|
402
|
+
await load();
|
|
403
|
+
} catch (e) {
|
|
404
|
+
toast.error(errorMessage(e));
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (loading) {
|
|
408
|
+
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: [
|
|
409
|
+
/* @__PURE__ */ jsx("div", { className: "h-4 w-4 shrink-0 animate-pulse rounded bg-muted/40" }),
|
|
410
|
+
/* @__PURE__ */ jsx("div", { className: "h-3.5 animate-pulse rounded bg-muted/40", style: { width: `${34 - i * 6}%` } }),
|
|
411
|
+
/* @__PURE__ */ jsx("div", { className: "h-4 w-28 animate-pulse rounded-full bg-muted/30" }),
|
|
412
|
+
/* @__PURE__ */ jsx("div", { className: "ml-auto h-5 w-9 animate-pulse rounded-full bg-muted/30" })
|
|
413
|
+
] }) }, i)) });
|
|
414
|
+
}
|
|
415
|
+
return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
|
|
416
|
+
/* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
|
|
417
|
+
PageActions,
|
|
418
|
+
{
|
|
419
|
+
actions: [{
|
|
420
|
+
id: "new-flow",
|
|
421
|
+
label: t("automations.flow.new"),
|
|
422
|
+
icon: Plus,
|
|
423
|
+
intent: "primary",
|
|
424
|
+
creates: true,
|
|
425
|
+
onSelect: () => setComposerOpen(true)
|
|
426
|
+
}]
|
|
427
|
+
}
|
|
428
|
+
) }),
|
|
429
|
+
/* @__PURE__ */ jsx(
|
|
430
|
+
CadenceComposer,
|
|
431
|
+
{
|
|
432
|
+
open: composerOpen,
|
|
433
|
+
onClose: () => setComposerOpen(false),
|
|
434
|
+
onCreate: createFlow
|
|
435
|
+
}
|
|
436
|
+
),
|
|
437
|
+
flows.length === 0 ? /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-1 border-dashed py-12 text-center", children: [
|
|
438
|
+
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("automations.flow.emptyTitle") }),
|
|
439
|
+
/* @__PURE__ */ jsx("p", { className: "max-w-md text-xs text-muted-foreground", children: t("automations.flow.emptyHint") })
|
|
440
|
+
] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: flows.map((flow) => /* @__PURE__ */ jsxs(Card, { className: "p-3", children: [
|
|
441
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
442
|
+
/* @__PURE__ */ jsxs(
|
|
443
|
+
Button,
|
|
444
|
+
{
|
|
445
|
+
variant: "bare",
|
|
446
|
+
size: "bare",
|
|
447
|
+
onClick: () => setSelectedId(selectedId === flow.id ? null : flow.id),
|
|
448
|
+
className: "flex flex-1 items-center gap-2 text-left font-normal justify-start",
|
|
449
|
+
children: [
|
|
450
|
+
/* @__PURE__ */ jsx(
|
|
451
|
+
ChevronRight,
|
|
452
|
+
{
|
|
453
|
+
className: `h-4 w-4 text-muted-foreground transition-transform ${selectedId === flow.id ? "rotate-90" : ""}`
|
|
454
|
+
}
|
|
455
|
+
),
|
|
456
|
+
/* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: flow.name }),
|
|
457
|
+
/* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: flow.entryEvent })
|
|
458
|
+
]
|
|
459
|
+
}
|
|
460
|
+
),
|
|
461
|
+
/* @__PURE__ */ jsx(
|
|
462
|
+
Switch,
|
|
463
|
+
{
|
|
464
|
+
checked: flow.isActive,
|
|
465
|
+
onCheckedChange: () => {
|
|
466
|
+
void toggleActive(flow);
|
|
467
|
+
},
|
|
468
|
+
"aria-label": t("automations.flow.toggle")
|
|
469
|
+
}
|
|
470
|
+
)
|
|
471
|
+
] }),
|
|
472
|
+
selectedId === flow.id && /* @__PURE__ */ jsxs("div", { className: "mt-3 border-t pt-3", children: [
|
|
473
|
+
counts && /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs text-muted-foreground", children: t("automations.flow.counts", {
|
|
474
|
+
active: String(counts.active),
|
|
475
|
+
completed: String(counts.completed),
|
|
476
|
+
exited: String(counts.exited)
|
|
477
|
+
}) }),
|
|
478
|
+
/* @__PURE__ */ jsx(
|
|
479
|
+
DataTable,
|
|
480
|
+
{
|
|
481
|
+
columns: stepColumns,
|
|
482
|
+
data: steps,
|
|
483
|
+
emptyMessage: /* @__PURE__ */ jsx("p", { className: "py-4 text-xs text-muted-foreground", children: t("automations.flow.noSteps") })
|
|
484
|
+
}
|
|
485
|
+
),
|
|
486
|
+
/* @__PURE__ */ jsx(
|
|
487
|
+
StepComposer,
|
|
488
|
+
{
|
|
489
|
+
steps,
|
|
490
|
+
onAdd: (input) => {
|
|
491
|
+
void (async () => {
|
|
492
|
+
try {
|
|
493
|
+
await store.saveStep(flow.id, input);
|
|
494
|
+
await loadDetail(flow.id);
|
|
495
|
+
} catch (e) {
|
|
496
|
+
toast.error(errorMessage(e));
|
|
497
|
+
}
|
|
498
|
+
})();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
)
|
|
502
|
+
] })
|
|
503
|
+
] }, flow.id)) })
|
|
504
|
+
] });
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export { FlowsPage };
|
|
508
|
+
//# sourceMappingURL=FlowsPage-6SUXT2LP.js.map
|
|
509
|
+
//# sourceMappingURL=FlowsPage-6SUXT2LP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/views/CadenceComposer.tsx","../src/data/flows.ts","../src/views/FlowsPage.tsx"],"names":["store","data","error","useTranslation","jsx","jsxs","Button","toast","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Input","errorMessage"],"mappings":";;;;;;;;AAiCO,SAAS,eAAA,CAAgB,EAAE,IAAA,EAAM,OAAA,EAAS,UAAS,EAIvD;AACD,EAAA,MAAM,IAAI,cAAA,EAAe;AACzB,EAAA,MAAM,UAAU,wBAAA,EAAyB;AAGzC,EAAA,MAAM,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,EAAC;AAEnC,EAAA,MAAM,CAAC,IAAA,EAAM,OAAO,CAAA,GAAI,KAAA,CAAM,SAAS,EAAE,CAAA;AACzC,EAAA,MAAM,CAAC,UAAA,EAAY,aAAa,CAAA,GAAI,KAAA,CAAM,SAAS,EAAE,CAAA;AACrD,EAAA,MAAM,CAAC,SAAA,EAAW,YAAY,CAAA,GAAI,KAAA,CAAM,SAAS,EAAE,CAAA;AACnD,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAI,KAAA,CAAM,SAAS,KAAK,CAAA;AAEhD,EAAA,KAAA,CAAM,UAAU,MAAM;AACpB,IAAA,IAAI,CAAC,IAAA,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;AAAA;AAAA,SAErF;AAAA,wBAEAA,GAAAA;AAAA,UAAC,YAAA;AAAA,UAAA;AAAA,YACC,KAAA;AAAA,YACA,KAAA,EAAO,CAAC,KAAA,KAAU;AAChB,cAAA,KAAA,CAAM,YAAY;AAChB,gBAAA,IAAI;AACF,kBAAA,MAAM,KAAA,CAAM,QAAA,CAAS,IAAA,CAAK,EAAA,EAAI,KAAK,CAAA;AACnC,kBAAA,MAAM,UAAA,CAAW,KAAK,EAAE,CAAA;AAAA,gBAC1B,SAAS,CAAA,EAAG;AAAE,kBAAAG,KAAAA,CAAM,KAAA,CAAMO,YAAAA,CAAa,CAAC,CAAC,CAAA;AAAA,gBAAE;AAAA,cAC7C,CAAA,GAAG;AAAA,YACL;AAAA;AAAA;AACF,OAAA,EACF;AAAA,KAAA,EAAA,EArDO,IAAA,CAAK,EAuDhB,CACD,CAAA,EACH;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"FlowsPage-6SUXT2LP.js","sourcesContent":["import React from 'react'\nimport { Workflow } from 'lucide-react'\nimport {\n Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, ModalFooter,\n Button, Input,\n Select, SelectTrigger, SelectValue, SelectContent, SelectItem,\n toast,\n} from '@fayz-ai/ui'\nimport { errorMessage, useTranslation, usePluginRuntimeOptional } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// Nova cadência.\n//\n// Era `window.prompt` duas vezes — uma para o nome e outra pedindo que se\n// DIGITASSE `crm.lead_created`. Quem não conhece o catálogo de eventos não tem\n// como acertar, e errar não dá erro: cria um fluxo que espera por um fato que\n// nunca chega, e o ecrã fica mostrando uma cadência ativa com zero pessoas.\n//\n// As três perguntas que definem uma cadência, e nenhuma a mais:\n//\n// QUEM ENTRA um fato do catálogo (só os plugins ativos anunciam fatos),\n// escolhido numa lista — não digitado.\n// QUEM SAI o fato que faz alguém parar de receber. É o campo que\n// separa uma régua de uma perseguição: sem ele, quem já\n// respondeu continua recebendo a mensagem do dia 5.\n// COMO SE CHAMA para o operador achar de novo.\n//\n// Os passos NÃO entram aqui. Uma cadência nasce vazia e desligada, e os passos\n// se montam na tabela do painel, onde se vê o que cada um já enviou. Um\n// formulário que pedisse nome, gatilho, saída e três mensagens de uma vez seria\n// abandonado no terceiro campo.\n// ---------------------------------------------------------------------------\n\nexport function CadenceComposer({ open, onClose, onCreate }: {\n open: boolean\n onClose: () => void\n onCreate: (input: { name: string; entryEvent: string; exitEvents: string[] }) => Promise<void>\n}) {\n const t = useTranslation()\n const runtime = usePluginRuntimeOptional()\n // Só os plugins ATIVOS anunciam fatos: oferecer um gatilho de um módulo que\n // não está montado é prometer uma cadência que nunca dispara.\n const events = runtime?.events ?? []\n\n const [name, setName] = React.useState('')\n const [entryEvent, setEntryEvent] = React.useState('')\n const [exitEvent, setExitEvent] = React.useState('')\n const [saving, setSaving] = React.useState(false)\n\n React.useEffect(() => {\n if (!open) return\n setName(''); setExitEvent('')\n setEntryEvent(events.find((e) => e.name === 'crm.lead_created')?.name ?? events[0]?.name ?? '')\n }, [open])\n\n const entry = events.find((e) => e.name === entryEvent)\n\n async function submit() {\n if (!name.trim() || !entryEvent || saving) return\n setSaving(true)\n try {\n await onCreate({\n name: name.trim(),\n entryEvent,\n exitEvents: exitEvent ? [exitEvent] : [],\n })\n onClose()\n } catch (e) {\n toast.error(errorMessage(e))\n } finally {\n setSaving(false)\n }\n }\n\n return (\n <Modal open={open} onOpenChange={(o) => { if (!o) onClose() }}>\n <ModalContent size=\"md\">\n <ModalHeader>\n <ModalTitle>{t('automations.flow.newTitle')}</ModalTitle>\n </ModalHeader>\n <ModalBody className=\"space-y-4\">\n <label className=\"block space-y-1.5\">\n <span className=\"text-sm font-medium text-foreground\">{t('automations.flow.nameLabel')}</span>\n <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={t('automations.flow.namePlaceholder')} />\n </label>\n\n <label className=\"block space-y-1.5\">\n <span className=\"text-sm font-medium text-foreground\">{t('automations.flow.entryLabel')}</span>\n {events.length > 0 ? (\n <Select value={entryEvent} onValueChange={setEntryEvent}>\n <SelectTrigger><SelectValue placeholder={t('automations.flow.entryPlaceholder')} /></SelectTrigger>\n <SelectContent>\n {events.map((e) => <SelectItem key={e.name} value={e.name}>{e.title ?? e.name}</SelectItem>)}\n </SelectContent>\n </Select>\n ) : (\n <p className=\"rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground\">\n {t('automations.flow.noEvents')}\n </p>\n )}\n {entry?.trigger && <span className=\"text-[11px] text-muted-foreground\">{entry.trigger}</span>}\n </label>\n\n <label className=\"block space-y-1.5\">\n <span className=\"text-sm font-medium text-foreground\">{t('automations.flow.exitLabel')}</span>\n <Select value={exitEvent || '__none__'} onValueChange={(v) => setExitEvent(v === '__none__' ? '' : v)}>\n <SelectTrigger><SelectValue /></SelectTrigger>\n <SelectContent>\n <SelectItem value=\"__none__\">{t('automations.flow.exitNone')}</SelectItem>\n {events.filter((e) => e.name !== entryEvent).map((e) => (\n <SelectItem key={e.name} value={e.name}>{e.title ?? e.name}</SelectItem>\n ))}\n </SelectContent>\n </Select>\n <span className=\"text-[11px] text-muted-foreground\">{t('automations.flow.exitHint')}</span>\n </label>\n\n <p className=\"flex items-start gap-2 rounded-lg bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground\">\n <Workflow className=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\n {t('automations.flow.bornOffHint')}\n </p>\n </ModalBody>\n <ModalFooter>\n <Button variant=\"outline\" onClick={onClose}>{t('common.cancel')}</Button>\n <Button onClick={() => { void submit() }} disabled={saving || !name.trim() || !entryEvent}>\n {t('automations.flow.create')}\n </Button>\n </ModalFooter>\n </ModalContent>\n </Modal>\n )\n}\n","import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// Cadence flows: the rows behind \"day 0 message, day 2 call, day 5 message\".\n//\n// Read and write only. The ENGINE is SQL — `automations_flows_run_due` on the\n// minute tick — and nothing here advances an enrolment. That split is the point:\n// a cadence that depended on a browser being open would stop at 6pm.\n//\n// Enrolments are read-only by policy too (the operator leaves a flow through\n// `automations_flow_exit`, never by editing a pointer), so this module exposes\n// no write for them.\n// ---------------------------------------------------------------------------\n\nconst FLOWS = 'plg_automations_flows'\nconst STEPS = 'plg_automations_flow_steps'\nconst ENROLLMENTS = 'plg_automations_enrollments'\nconst STEP_STATS = 'v_automations_flow_steps'\n\nexport interface CadenceFlow {\n id: string\n tenantId: string\n name: string\n description: string | null\n /** The event that puts somebody in, e.g. `crm.lead_created`. */\n entryEvent: string\n /** Events that take somebody out. Empty means \"only ends by running out\". */\n exitEvents: string[]\n isActive: boolean\n createdAt: string\n updatedAt: string\n}\n\nexport type CadenceStepKind = 'message' | 'task'\n\nexport interface CadenceStep {\n id: string\n flowId: string\n position: number\n /** Minutes to wait AFTER THE PREVIOUS STEP — not since enrolment. */\n delayMinutes: number\n kind: CadenceStepKind\n templateKey: string | null\n /** NULL lets the recipient's own preference choose. */\n channel: string | null\n taskTitle: string | null\n taskDueDays: number | null\n}\n\n/** A step plus what actually happened on it. Per step, never per flow: the\n * question a cadence is judged by is WHERE people stop. */\nexport interface CadenceStepStats extends CadenceStep {\n queued: number\n sent: number\n blocked: number\n failed: number\n cancelled: number\n}\n\nexport interface FlowCounts {\n active: number\n completed: number\n exited: number\n}\n\nexport interface CadenceFlowStore {\n listFlows(): Promise<CadenceFlow[]>\n saveFlow(input: Partial<CadenceFlow> & { name: string; entryEvent: string }): Promise<CadenceFlow>\n setFlowActive(id: string, isActive: boolean): Promise<void>\n deleteFlow(id: string): Promise<void>\n listSteps(flowId: string): Promise<CadenceStepStats[]>\n saveStep(flowId: string, input: Partial<CadenceStep>): Promise<void>\n deleteStep(id: string): Promise<void>\n countsFor(flowId: string): Promise<FlowCounts>\n}\n\nfunction rowToFlow(r: any): CadenceFlow {\n return {\n id: r.id,\n tenantId: r.tenant_id,\n name: r.name,\n description: r.description ?? null,\n entryEvent: r.entry_event,\n exitEvents: Array.isArray(r.exit_events) ? r.exit_events : [],\n isActive: r.is_active === true,\n createdAt: r.created_at,\n updatedAt: r.updated_at ?? r.created_at,\n }\n}\n\nfunction rowToStepStats(r: any): CadenceStepStats {\n return {\n id: r.step_id ?? r.id,\n flowId: r.flow_id,\n position: r.position,\n delayMinutes: r.delay_minutes ?? 0,\n kind: (r.kind === 'task' ? 'task' : 'message'),\n templateKey: r.template_key ?? null,\n channel: r.channel ?? null,\n taskTitle: r.task_title ?? null,\n taskDueDays: r.task_due_days ?? null,\n queued: Number(r.queued ?? 0),\n sent: Number(r.sent ?? 0),\n blocked: Number(r.blocked ?? 0),\n failed: Number(r.failed ?? 0),\n cancelled: Number(r.cancelled ?? 0),\n }\n}\n\n/**\n * Sparse positions (10, 20, 30…) so that inserting a step between two others\n * does not renumber the ones after it — an enrolment's pointer names a\n * position, and renumbering would move people to a step they already had.\n */\nexport function nextPosition(steps: Array<{ position: number }>): number {\n if (steps.length === 0) return 10\n return Math.max(...steps.map((s) => s.position)) + 10\n}\n\n/** Minutes as a salesperson says them. 2880 is \"2 days\", not \"two thousand\". */\nexport function describeDelay(minutes: number, t: (k: string, v?: Record<string, string>) => string): string {\n if (minutes <= 0) return t('automations.flow.delayNow')\n if (minutes % 1440 === 0) return t('automations.flow.delayDays', { count: String(minutes / 1440) })\n if (minutes % 60 === 0) return t('automations.flow.delayHours', { count: String(minutes / 60) })\n return t('automations.flow.delayMinutes', { count: String(minutes) })\n}\n\nexport function createSupabaseFlowStore(): CadenceFlowStore {\n function client() {\n const supabase = getSupabaseClientOptional() as any\n if (!supabase) throw new Error('Supabase not initialized')\n return supabase\n }\n\n const store: CadenceFlowStore = {\n async listFlows() {\n const { data, error } = await client().from(FLOWS).select('*').order('name')\n if (error) throw new Error(error.message)\n return (data ?? []).map(rowToFlow)\n },\n\n async saveFlow(input) {\n const row: any = {\n name: input.name,\n description: input.description ?? null,\n entry_event: input.entryEvent,\n exit_events: input.exitEvents ?? [],\n }\n if (input.id) {\n const { data, error } = await client().from(FLOWS).update(row).eq('id', input.id).select().single()\n if (error) throw new Error(error.message)\n return rowToFlow(data)\n }\n row.tenant_id = getActiveTenantId()\n // A new flow is born INACTIVE. `is_active` defaults false in the table and\n // is not set here on purpose: a cadence that starts sending the moment\n // somebody saves a draft is a cadence that sends a draft.\n const { data, error } = await client().from(FLOWS).insert(row).select().single()\n if (error) throw new Error(error.message)\n return rowToFlow(data)\n },\n\n async setFlowActive(id, isActive) {\n const { error } = await client().from(FLOWS)\n .update({ is_active: isActive, updated_at: new Date().toISOString() }).eq('id', id)\n if (error) throw new Error(error.message)\n },\n\n async deleteFlow(id) {\n const { error } = await client().from(FLOWS).delete().eq('id', id)\n if (error) throw new Error(error.message)\n },\n\n async listSteps(flowId) {\n // The stats view, not the table: the numbers are the reason to look.\n const { data, error } = await client().from(STEP_STATS)\n .select('*').eq('flow_id', flowId).order('position')\n if (error) throw new Error(error.message)\n return (data ?? []).map(rowToStepStats)\n },\n\n async saveStep(flowId, input) {\n const row: any = {\n flow_id: flowId,\n position: input.position,\n delay_minutes: input.delayMinutes ?? 0,\n kind: input.kind ?? 'message',\n template_key: input.kind === 'task' ? null : (input.templateKey ?? null),\n channel: input.kind === 'task' ? null : (input.channel ?? null),\n task_title: input.kind === 'task' ? (input.taskTitle ?? null) : null,\n task_due_days: input.kind === 'task' ? (input.taskDueDays ?? null) : null,\n }\n if (input.id) {\n const { error } = await client().from(STEPS).update(row).eq('id', input.id)\n if (error) throw new Error(error.message)\n return\n }\n row.tenant_id = getActiveTenantId()\n const { error } = await client().from(STEPS).insert(row)\n if (error) throw new Error(error.message)\n },\n\n async deleteStep(id) {\n const { error } = await client().from(STEPS).delete().eq('id', id)\n if (error) throw new Error(error.message)\n },\n\n async countsFor(flowId) {\n const { data, error } = await client().from(ENROLLMENTS).select('status').eq('flow_id', flowId)\n if (error) throw new Error(error.message)\n const rows = (data ?? []) as Array<{ status: string }>\n return {\n active: rows.filter((r) => r.status === 'active').length,\n completed: rows.filter((r) => r.status === 'completed').length,\n exited: rows.filter((r) => r.status === 'exited').length,\n }\n },\n }\n\n return store\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ColumnDef } from '@tanstack/react-table'\nimport { ChevronRight, Clock, ListChecks, Loader2, MessageSquare, Plus, Trash2 } from 'lucide-react'\nimport {\n Button, Card, DataTable, Input, PageHeaderActions, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, toast,\n} from '@fayz-ai/ui'\nimport { CadenceComposer } from './CadenceComposer'\nimport { PageActions } from '@fayz-ai/admin'\nimport { errorMessage, useTranslation } from '@fayz-ai/core'\nimport {\n createSupabaseFlowStore, describeDelay, nextPosition,\n type CadenceFlow, type CadenceStepStats, type FlowCounts,\n} from '../data/flows'\n\n// ---------------------------------------------------------------------------\n// Cadence flows.\n//\n// The list answers \"what is running\"; the panel answers \"where do people stop\".\n// Those are the only two questions a cadence screen has to answer, and the\n// second one is why the step table carries the numbers instead of a chart\n// somewhere else: the third message being the one nobody answers is a fact\n// about a ROW, and it belongs next to the row.\n//\n// Nothing here advances a cadence. The engine is `automations_flows_run_due` on\n// the minute tick — a cadence that needed this page open would stop at 6pm.\n// ---------------------------------------------------------------------------\n\nconst store = createSupabaseFlowStore()\n\n/** The delays a cadence is actually built from, in minutes. */\nconst DELAY_CHOICES = [0, 60, 1440, 2880, 4320, 10080]\n\nfunction useStepColumns(onDelete: (id: string) => void): ColumnDef<CadenceStepStats, any>[] {\n const t = useTranslation()\n return useMemo(() => [\n {\n accessorKey: 'position', header: '#',\n cell: ({ getValue }) => <span className=\"text-xs tabular-nums text-muted-foreground\">{getValue() as number}</span>,\n },\n {\n id: 'step', header: t('automations.flow.colStep'),\n cell: ({ row }) => {\n const s = row.original\n const isTask = s.kind === 'task'\n return (\n <span className=\"inline-flex items-center gap-1.5 text-sm\">\n {isTask ? <ListChecks className=\"h-3.5 w-3.5 text-muted-foreground\" />\n : <MessageSquare className=\"h-3.5 w-3.5 text-muted-foreground\" />}\n {isTask ? s.taskTitle : s.templateKey}\n {!isTask && s.channel && (\n <span className=\"rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground\">{s.channel}</span>\n )}\n </span>\n )\n },\n },\n {\n accessorKey: 'delayMinutes', header: t('automations.flow.colWait'),\n cell: ({ getValue }) => (\n <span className=\"inline-flex items-center gap-1 text-xs text-muted-foreground\">\n <Clock className=\"h-3 w-3\" />{describeDelay(getValue() as number, t)}\n </span>\n ),\n },\n // The scoreboard. Zeroes are shown rather than hidden: a step that has never\n // sent is the finding, not an empty cell.\n {\n accessorKey: 'queued', header: t('automations.flow.colQueued'),\n cell: ({ getValue }) => <span className=\"text-xs tabular-nums\">{getValue() as number}</span>,\n },\n {\n accessorKey: 'sent', header: t('automations.flow.colSent'),\n cell: ({ getValue }) => <span className=\"text-xs tabular-nums\">{getValue() as number}</span>,\n },\n {\n accessorKey: 'blocked', header: t('automations.flow.colBlocked'),\n cell: ({ getValue }) => {\n const n = getValue() as number\n return <span className={`text-xs tabular-nums ${n > 0 ? 'text-warning' : ''}`}>{n}</span>\n },\n },\n {\n accessorKey: 'failed', header: t('automations.flow.colFailed'),\n cell: ({ getValue }) => {\n const n = getValue() as number\n return <span className={`text-xs tabular-nums ${n > 0 ? 'text-destructive' : ''}`}>{n}</span>\n },\n },\n {\n id: 'actions', header: '',\n cell: ({ row }) => (\n <div className=\"flex justify-end\">\n <Button variant=\"bare\" size=\"bare\"\n onClick={(e) => { e.stopPropagation(); onDelete(row.original.id) }}\n title={t('automations.flow.deleteStep')}\n className=\"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-destructive\"\n >\n <Trash2 className=\"h-3.5 w-3.5\" />\n </Button>\n </div>\n ),\n },\n ], [t, onDelete])\n}\n\nconst COMPOSER_TRIGGER = 'h-auto w-auto gap-2 rounded-md border-border px-2 py-1.5 shadow-none'\n\nfunction StepComposer({ steps, onAdd }: {\n steps: CadenceStepStats[]\n onAdd: (input: { kind: 'message' | 'task'; delayMinutes: number; templateKey?: string; channel?: string; taskTitle?: string; position: number }) => void\n}) {\n const t = useTranslation()\n const [kind, setKind] = useState<'message' | 'task'>('message')\n const [delay, setDelay] = useState(1440)\n const [value, setValue] = useState('')\n\n const submit = () => {\n if (!value.trim()) {\n toast.error(t(kind === 'task' ? 'automations.flow.needTitle' : 'automations.flow.needTemplate'))\n return\n }\n onAdd({\n kind, delayMinutes: delay, position: nextPosition(steps),\n ...(kind === 'task' ? { taskTitle: value.trim() } : { templateKey: value.trim() }),\n })\n setValue('')\n }\n\n return (\n <div className=\"mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-dashed p-3\">\n <Select value={kind} onValueChange={(v) => { setKind(v as 'message' | 'task'); setValue('') }}>\n <SelectTrigger className={COMPOSER_TRIGGER}><SelectValue /></SelectTrigger>\n <SelectContent>\n <SelectItem value=\"message\">{t('automations.flow.kindMessage')}</SelectItem>\n <SelectItem value=\"task\">{t('automations.flow.kindTask')}</SelectItem>\n </SelectContent>\n </Select>\n <Select value={String(delay)} onValueChange={(v) => setDelay(Number(v))}>\n <SelectTrigger className={COMPOSER_TRIGGER}><SelectValue /></SelectTrigger>\n <SelectContent>\n {DELAY_CHOICES.map((m) => (\n <SelectItem key={m} value={String(m)}>{describeDelay(m, t)}</SelectItem>\n ))}\n </SelectContent>\n </Select>\n <div className=\"min-w-[200px] flex-1\">\n <Input\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => { if (e.key === 'Enter') submit() }}\n placeholder={t(kind === 'task' ? 'automations.flow.titlePlaceholder' : 'automations.flow.templatePlaceholder')}\n className=\"h-auto rounded-md border-border bg-background px-2 py-1.5 shadow-none\"\n />\n </div>\n <Button onClick={submit} className=\"gap-1\">\n <Plus className=\"h-3.5 w-3.5\" />{t('automations.flow.addStep')}\n </Button>\n </div>\n )\n}\n\nexport function FlowsPage() {\n const t = useTranslation()\n const [flows, setFlows] = useState<CadenceFlow[]>([])\n const [loading, setLoading] = useState(true)\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const [steps, setSteps] = useState<CadenceStepStats[]>([])\n const [counts, setCounts] = useState<FlowCounts | null>(null)\n const [composerOpen, setComposerOpen] = useState(false)\n\n const load = useCallback(async () => {\n setLoading(true)\n try {\n setFlows(await store.listFlows())\n } catch (e) {\n toast.error(errorMessage(e))\n } finally {\n setLoading(false)\n }\n }, [])\n\n // `selectedId` lives in a ref so a late answer can be checked against the\n // selection as it is NOW, without re-creating the callback on every change.\n const selectedRef = useRef<string | null>(null)\n selectedRef.current = selectedId\n\n const loadDetail = useCallback(async (flowId: string) => {\n try {\n const [s, c] = await Promise.all([store.listSteps(flowId), store.countsFor(flowId)])\n // Two selections can resolve out of order, and the panel renders whatever\n // `steps` holds. Applying the wrong flow's rows is not cosmetic: the trash\n // icon deletes `row.original.id`, so a click in that window removes a step\n // from the flow the operator is no longer looking at.\n if (selectedRef.current !== flowId) return\n setSteps(s); setCounts(c)\n } catch (e) {\n toast.error(errorMessage(e))\n }\n }, [])\n\n const deleteStep = useCallback((id: string) => {\n void (async () => {\n try {\n await store.deleteStep(id)\n if (selectedId) await loadDetail(selectedId)\n } catch (e) { toast.error(errorMessage(e)) }\n })()\n }, [selectedId, loadDetail])\n const stepColumns = useStepColumns(deleteStep)\n\n useEffect(() => { void load() }, [load])\n useEffect(() => {\n // Clear FIRST. The panel opens as soon as `selectedId` flips, so without\n // this it shows the previous flow's steps and counts until the fetch lands\n // — and forever if it throws, since `loadDetail` only toasts.\n setSteps([]); setCounts(null)\n if (selectedId) void loadDetail(selectedId)\n }, [selectedId, loadDetail])\n\n const selected = flows.find((f) => f.id === selectedId) ?? null\n\n async function createFlow(input: { name: string; entryEvent: string; exitEvents: string[] }) {\n const flow = await store.saveFlow(input)\n await load()\n // Abre o painel dela na hora: uma cadência sem passos não faz nada, e o\n // próximo ato é sempre adicionar o primeiro.\n setSelectedId(flow.id)\n toast.success(t('automations.flow.created'))\n }\n\n async function toggleActive(flow: CadenceFlow) {\n // Turning a flow ON with no steps would enrol people into nothing: they\n // would sit in `active` forever, and the screen would show a cadence that\n // never sends. Cheaper to refuse than to explain.\n if (!flow.isActive) {\n // Always ask. Reading the shared `steps` when `flow.id === selectedId`\n // meant that during the window above — selection flipped, fetch not back\n // — an empty list let a flow with no steps switch itself on, which is the\n // one thing this guard exists to stop.\n const s = await store.listSteps(flow.id)\n if (s.length === 0) {\n toast.error(t('automations.flow.needStepsToActivate'))\n return\n }\n }\n try {\n await store.setFlowActive(flow.id, !flow.isActive)\n await load()\n } catch (e) {\n toast.error(errorMessage(e))\n }\n }\n\n // Esqueleto com a FORMA da lista, não uma linha de texto centrada: a tela\n // que aparece depois tem cartões empilhados, e um \"Carregando…\" faz o\n // conteúdo saltar quando chega.\n if (loading) {\n return <div className=\"space-y-2\" aria-busy=\"true\" aria-label={t('automations.flow.loading')}>\n {[0, 1, 2].map((i) => (\n <Card key={i} className=\"p-3\">\n <div className=\"flex items-center gap-3\">\n <div className=\"h-4 w-4 shrink-0 animate-pulse rounded bg-muted/40\" />\n <div className=\"h-3.5 animate-pulse rounded bg-muted/40\" style={{ width: `${34 - i * 6}%` }} />\n <div className=\"h-4 w-28 animate-pulse rounded-full bg-muted/30\" />\n <div className=\"ml-auto h-5 w-9 animate-pulse rounded-full bg-muted/30\" />\n </div>\n </Card>\n ))}\n </div>\n }\n\n return (\n <div className=\"space-y-4\">\n <PageHeaderActions>\n <PageActions\n actions={[{\n id: 'new-flow', label: t('automations.flow.new'), icon: Plus,\n intent: 'primary' as const, creates: true, onSelect: () => setComposerOpen(true),\n }]}\n />\n </PageHeaderActions>\n\n <CadenceComposer\n open={composerOpen}\n onClose={() => setComposerOpen(false)}\n onCreate={createFlow}\n />\n\n {flows.length === 0 ? (\n <Card className=\"flex flex-col items-center gap-1 border-dashed py-12 text-center\">\n <p className=\"text-sm font-medium\">{t('automations.flow.emptyTitle')}</p>\n <p className=\"max-w-md text-xs text-muted-foreground\">{t('automations.flow.emptyHint')}</p>\n </Card>\n ) : (\n <div className=\"space-y-2\">\n {flows.map((flow) => (\n <Card key={flow.id} className=\"p-3\">\n <div className=\"flex items-center gap-3\">\n <Button variant=\"bare\" size=\"bare\"\n onClick={() => setSelectedId(selectedId === flow.id ? null : flow.id)}\n className=\"flex flex-1 items-center gap-2 text-left font-normal justify-start\"\n >\n <ChevronRight\n className={`h-4 w-4 text-muted-foreground transition-transform ${selectedId === flow.id ? 'rotate-90' : ''}`}\n />\n <span className=\"text-sm font-medium\">{flow.name}</span>\n <span className=\"rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground\">\n {flow.entryEvent}\n </span>\n </Button>\n {/* The switch says what it will do, not what it is: a flow with\n no steps cannot be turned on, and the refusal explains. */}\n <Switch\n checked={flow.isActive}\n onCheckedChange={() => { void toggleActive(flow) }}\n aria-label={t('automations.flow.toggle')}\n />\n </div>\n\n {selectedId === flow.id && (\n <div className=\"mt-3 border-t pt-3\">\n {counts && (\n <p className=\"mb-2 text-xs text-muted-foreground\">\n {t('automations.flow.counts', {\n active: String(counts.active),\n completed: String(counts.completed),\n exited: String(counts.exited),\n })}\n </p>\n )}\n <DataTable\n columns={stepColumns}\n data={steps}\n emptyMessage={\n <p className=\"py-4 text-xs text-muted-foreground\">{t('automations.flow.noSteps')}</p>\n }\n />\n\n <StepComposer\n steps={steps}\n onAdd={(input) => {\n void (async () => {\n try {\n await store.saveStep(flow.id, input)\n await loadDetail(flow.id)\n } catch (e) { toast.error(errorMessage(e)) }\n })()\n }}\n />\n </div>\n )}\n </Card>\n ))}\n </div>\n )}\n </div>\n )\n}\n"]}
|