@fayz-ai/plugin-automations 0.12.7 → 0.13.1

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/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import * as React4 from 'react';
2
- import React4__default from 'react';
3
- import { getSupabaseClientOptional, startEventLog, getMessageDefaults, normalizeMessageActions, usePluginRuntimeOptional, resolveMessages, errorMessage, resolveMessage, renderMessageTemplate, loadEventRuns, getActiveTenantId } from '@fayz-ai/core';
4
- import { resolveFayzAgentConnection, registerRailPage, getFayzSupabaseClientOptional, useConnectors, useAgentSurface, PageActions, askAI, SettingsTabs, adminNavigateTo, RightRailPage, AskAIButton, useOrganizationStore, connectorRoute, ConnectorMark, ConnectorDeliveries } from '@fayz-ai/admin';
2
+ import React4__default, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
3
+ import { getSupabaseClientOptional, useTranslation, errorMessage, startEventLog, getMessageDefaults, normalizeMessageActions, usePluginRuntimeOptional, resolveMessages, resolveMessage, renderMessageTemplate, loadEventRuns, getActiveTenantId } from '@fayz-ai/core';
4
+ import { PageActions, resolveFayzAgentConnection, registerRailPage, getFayzSupabaseClientOptional, useConnectors, useAgentSurface, askAI, SettingsTabs, adminNavigateTo, RightRailPage, AskAIButton, useOrganizationStore, connectorRoute, ConnectorMark, ConnectorDeliveries } from '@fayz-ai/admin';
5
5
  import * as LucideIcons from 'lucide-react';
6
- import { WandSparkles, Zap, Receipt, Megaphone, MessageSquare, Smartphone, Mail, ChevronRight, RotateCcw, Check, Clock, Monitor, RefreshCw, History, Send, AlertTriangle, CircleCheck, CircleSlash } from 'lucide-react';
7
- import { PageHeaderActions, PageTabs, Card, WhatsAppIcon, Switch, SubpageHeader, Button, Badge, Hint, HeaderTabs, toast, PhoneField } from '@fayz-ai/ui';
6
+ import { Plus, ChevronRight, ListChecks, MessageSquare, Clock, Trash2, Workflow, WandSparkles, Zap, Receipt, Megaphone, Smartphone, Mail, RotateCcw, Check, Monitor, RefreshCw, History, Send, AlertTriangle, CircleCheck, CircleSlash } from 'lucide-react';
7
+ import { toast, Card, PageHeaderActions, Switch, DataTable, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, Button, PageTabs, WhatsAppIcon, SubpageHeader, Badge, Hint, HeaderTabs, PhoneField } from '@fayz-ai/ui';
8
8
  import { createFayzAutomationsClient, FayzAutomationsError } from '@fayz-ai/sdk/automations';
9
- import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
9
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
10
10
 
11
11
  // src/index.ts
12
12
  var PREFLIGHT_FUNCTION = "tyxter-payment-preflight";
@@ -591,7 +591,7 @@ var SAMPLE = {
591
591
  appointment_date: "12/08/2026",
592
592
  appointment_time: "14:30"
593
593
  };
594
- function AutomationDetailPage({ eventKey, channel, store, backTo = "/automations", embedded, onDone }) {
594
+ function AutomationDetailPage({ eventKey, channel, store: store2, backTo = "/automations", embedded, onDone }) {
595
595
  const tenantId = useOrganizationStoreLike();
596
596
  const runtime = usePluginRuntimeOptional();
597
597
  const fayzConnection = React4__default.useMemo(() => resolveFayzAgentConnection(), []);
@@ -652,14 +652,14 @@ function AutomationDetailPage({ eventKey, channel, store, backTo = "/automations
652
652
  }
653
653
  let overrides = [];
654
654
  try {
655
- overrides = await store.list(tenantId);
655
+ overrides = await store2.list(tenantId);
656
656
  } catch (err) {
657
657
  console.warn("[automations] could not load overrides; showing defaults", err);
658
658
  }
659
659
  const found = resolveMessage(decodeURIComponent(eventKey), channel, overrides, runtime?.events ?? []);
660
660
  setMessage(found);
661
661
  if (found) setDraft({ subject: found.subject, body: found.body });
662
- }, [eventKey, channel, store, tenantId, runtime]);
662
+ }, [eventKey, channel, store2, tenantId, runtime]);
663
663
  React4__default.useEffect(() => {
664
664
  void reload();
665
665
  }, [reload]);
@@ -703,7 +703,7 @@ function AutomationDetailPage({ eventKey, channel, store, backTo = "/automations
703
703
  const patch = async (input) => {
704
704
  setSaving(true);
705
705
  try {
706
- await store.upsert(input, tenantId);
706
+ await store2.upsert(input, tenantId);
707
707
  await reload();
708
708
  } catch (err) {
709
709
  console.warn("[automations] save failed", err);
@@ -723,7 +723,7 @@ function AutomationDetailPage({ eventKey, channel, store, backTo = "/automations
723
723
  setDraft({ subject: fallback?.subject ?? "", body: fallback?.body ?? "" });
724
724
  setSaving(true);
725
725
  try {
726
- await store.reset(event.name, message.channel, tenantId);
726
+ await store2.reset(event.name, message.channel, tenantId);
727
727
  await reload();
728
728
  toast.success("Texto restaurado");
729
729
  } catch (err) {
@@ -1207,7 +1207,7 @@ function readSelection(basePath) {
1207
1207
  if (!eventKey || !channel) return null;
1208
1208
  return { eventKey, channel };
1209
1209
  }
1210
- function AutomationsList({ store, variant = "page", basePath = "/automations" }) {
1210
+ function AutomationsList({ store: store2, variant = "page", basePath = "/automations" }) {
1211
1211
  const tenantId = useOrganizationStoreLike();
1212
1212
  const runtime = usePluginRuntimeOptional();
1213
1213
  const [messages, setMessages] = React4__default.useState(null);
@@ -1225,17 +1225,17 @@ function AutomationsList({ store, variant = "page", basePath = "/automations" })
1225
1225
  const reload = React4__default.useCallback(async () => {
1226
1226
  let overrides = [];
1227
1227
  try {
1228
- overrides = await store.list(tenantId);
1228
+ overrides = await store2.list(tenantId);
1229
1229
  } catch (err) {
1230
1230
  console.warn("[automations] could not load template overrides; showing defaults", err);
1231
1231
  }
1232
1232
  setMessages(resolveMessages(overrides, runtime?.events ?? []));
1233
- }, [store, tenantId, runtime]);
1233
+ }, [store2, tenantId, runtime]);
1234
1234
  React4__default.useEffect(() => {
1235
1235
  void reload();
1236
1236
  }, [reload]);
1237
- const surfaceRef = React4__default.useRef({ messages, store, tenantId, reload, basePath });
1238
- surfaceRef.current = { messages, store, tenantId, reload, basePath };
1237
+ const surfaceRef = React4__default.useRef({ messages, store: store2, tenantId, reload, basePath });
1238
+ surfaceRef.current = { messages, store: store2, tenantId, reload, basePath };
1239
1239
  const agentSurface = React4__default.useMemo(() => ({
1240
1240
  id: "automations.list",
1241
1241
  pluginId: "automations",
@@ -1303,7 +1303,7 @@ function AutomationsList({ store, variant = "page", basePath = "/automations" })
1303
1303
  const toggle = async (m, enabled) => {
1304
1304
  setMessages((prev) => prev?.map((x) => x.event.name === m.event.name && x.channel === m.channel ? { ...x, enabled } : x) ?? null);
1305
1305
  try {
1306
- await store.upsert({ eventKey: m.event.name, channel: m.channel, enabled }, tenantId);
1306
+ await store2.upsert({ eventKey: m.event.name, channel: m.channel, enabled }, tenantId);
1307
1307
  await reload();
1308
1308
  } catch (err) {
1309
1309
  console.warn("[automations] toggle failed", err);
@@ -1459,7 +1459,7 @@ function AutomationsList({ store, variant = "page", basePath = "/automations" })
1459
1459
  {
1460
1460
  eventKey: selected.eventKey,
1461
1461
  channel: selected.channel,
1462
- store,
1462
+ store: store2,
1463
1463
  backTo: basePath,
1464
1464
  embedded: true
1465
1465
  }
@@ -1527,21 +1527,1587 @@ function createSupabaseTemplateStore() {
1527
1527
  }
1528
1528
  };
1529
1529
  }
1530
+ function CadenceComposer({ open, onClose, onCreate }) {
1531
+ const t = useTranslation();
1532
+ const runtime = usePluginRuntimeOptional();
1533
+ const events = runtime?.events ?? [];
1534
+ const [name, setName] = React4__default.useState("");
1535
+ const [entryEvent, setEntryEvent] = React4__default.useState("");
1536
+ const [exitEvent, setExitEvent] = React4__default.useState("");
1537
+ const [saving, setSaving] = React4__default.useState(false);
1538
+ React4__default.useEffect(() => {
1539
+ if (!open) return;
1540
+ setName("");
1541
+ setExitEvent("");
1542
+ setEntryEvent(events.find((e) => e.name === "crm.lead_created")?.name ?? events[0]?.name ?? "");
1543
+ }, [open]);
1544
+ const entry = events.find((e) => e.name === entryEvent);
1545
+ async function submit() {
1546
+ if (!name.trim() || !entryEvent || saving) return;
1547
+ setSaving(true);
1548
+ try {
1549
+ await onCreate({
1550
+ name: name.trim(),
1551
+ entryEvent,
1552
+ exitEvents: exitEvent ? [exitEvent] : []
1553
+ });
1554
+ onClose();
1555
+ } catch (e) {
1556
+ toast.error(errorMessage(e));
1557
+ } finally {
1558
+ setSaving(false);
1559
+ }
1560
+ }
1561
+ return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
1562
+ if (!o) onClose();
1563
+ }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "md", children: [
1564
+ /* @__PURE__ */ jsx(ModalHeader, { children: /* @__PURE__ */ jsx(ModalTitle, { children: t("automations.flow.newTitle") }) }),
1565
+ /* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
1566
+ /* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
1567
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.nameLabel") }),
1568
+ /* @__PURE__ */ jsx(Input, { value: name, onChange: (e) => setName(e.target.value), placeholder: t("automations.flow.namePlaceholder") })
1569
+ ] }),
1570
+ /* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
1571
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.entryLabel") }),
1572
+ events.length > 0 ? /* @__PURE__ */ jsxs(Select, { value: entryEvent, onValueChange: setEntryEvent, children: [
1573
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("automations.flow.entryPlaceholder") }) }),
1574
+ /* @__PURE__ */ jsx(SelectContent, { children: events.map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name)) })
1575
+ ] }) : /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground", children: t("automations.flow.noEvents") }),
1576
+ entry?.trigger && /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: entry.trigger })
1577
+ ] }),
1578
+ /* @__PURE__ */ jsxs("label", { className: "block space-y-1.5", children: [
1579
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: t("automations.flow.exitLabel") }),
1580
+ /* @__PURE__ */ jsxs(Select, { value: exitEvent || "__none__", onValueChange: (v) => setExitEvent(v === "__none__" ? "" : v), children: [
1581
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
1582
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
1583
+ /* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t("automations.flow.exitNone") }),
1584
+ events.filter((e) => e.name !== entryEvent).map((e) => /* @__PURE__ */ jsx(SelectItem, { value: e.name, children: e.title ?? e.name }, e.name))
1585
+ ] })
1586
+ ] }),
1587
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: t("automations.flow.exitHint") })
1588
+ ] }),
1589
+ /* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2 rounded-lg bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground", children: [
1590
+ /* @__PURE__ */ jsx(Workflow, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }),
1591
+ t("automations.flow.bornOffHint")
1592
+ ] })
1593
+ ] }),
1594
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
1595
+ /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: onClose, children: t("common.cancel") }),
1596
+ /* @__PURE__ */ jsx(Button, { onClick: () => {
1597
+ void submit();
1598
+ }, disabled: saving || !name.trim() || !entryEvent, children: t("automations.flow.create") })
1599
+ ] })
1600
+ ] }) });
1601
+ }
1602
+ var FLOWS = "plg_automations_flows";
1603
+ var STEPS = "plg_automations_flow_steps";
1604
+ var ENROLLMENTS = "plg_automations_enrollments";
1605
+ var STEP_STATS = "v_automations_flow_steps";
1606
+ function rowToFlow(r) {
1607
+ return {
1608
+ id: r.id,
1609
+ tenantId: r.tenant_id,
1610
+ name: r.name,
1611
+ description: r.description ?? null,
1612
+ entryEvent: r.entry_event,
1613
+ exitEvents: Array.isArray(r.exit_events) ? r.exit_events : [],
1614
+ isActive: r.is_active === true,
1615
+ createdAt: r.created_at,
1616
+ updatedAt: r.updated_at ?? r.created_at
1617
+ };
1618
+ }
1619
+ function rowToStepStats(r) {
1620
+ return {
1621
+ id: r.step_id ?? r.id,
1622
+ flowId: r.flow_id,
1623
+ position: r.position,
1624
+ delayMinutes: r.delay_minutes ?? 0,
1625
+ kind: r.kind === "task" ? "task" : "message",
1626
+ templateKey: r.template_key ?? null,
1627
+ channel: r.channel ?? null,
1628
+ taskTitle: r.task_title ?? null,
1629
+ taskDueDays: r.task_due_days ?? null,
1630
+ queued: Number(r.queued ?? 0),
1631
+ sent: Number(r.sent ?? 0),
1632
+ blocked: Number(r.blocked ?? 0),
1633
+ failed: Number(r.failed ?? 0),
1634
+ cancelled: Number(r.cancelled ?? 0)
1635
+ };
1636
+ }
1637
+ function nextPosition(steps) {
1638
+ if (steps.length === 0) return 10;
1639
+ return Math.max(...steps.map((s) => s.position)) + 10;
1640
+ }
1641
+ function describeDelay(minutes, t) {
1642
+ if (minutes <= 0) return t("automations.flow.delayNow");
1643
+ if (minutes % 1440 === 0) return t("automations.flow.delayDays", { count: String(minutes / 1440) });
1644
+ if (minutes % 60 === 0) return t("automations.flow.delayHours", { count: String(minutes / 60) });
1645
+ return t("automations.flow.delayMinutes", { count: String(minutes) });
1646
+ }
1647
+ function createSupabaseFlowStore() {
1648
+ function client() {
1649
+ const supabase = getSupabaseClientOptional();
1650
+ if (!supabase) throw new Error("Supabase not initialized");
1651
+ return supabase;
1652
+ }
1653
+ const store2 = {
1654
+ async listFlows() {
1655
+ const { data, error } = await client().from(FLOWS).select("*").order("name");
1656
+ if (error) throw new Error(error.message);
1657
+ return (data ?? []).map(rowToFlow);
1658
+ },
1659
+ async saveFlow(input) {
1660
+ const row = {
1661
+ name: input.name,
1662
+ description: input.description ?? null,
1663
+ entry_event: input.entryEvent,
1664
+ exit_events: input.exitEvents ?? []
1665
+ };
1666
+ if (input.id) {
1667
+ const { data: data2, error: error2 } = await client().from(FLOWS).update(row).eq("id", input.id).select().single();
1668
+ if (error2) throw new Error(error2.message);
1669
+ return rowToFlow(data2);
1670
+ }
1671
+ row.tenant_id = getActiveTenantId();
1672
+ const { data, error } = await client().from(FLOWS).insert(row).select().single();
1673
+ if (error) throw new Error(error.message);
1674
+ return rowToFlow(data);
1675
+ },
1676
+ async setFlowActive(id, isActive) {
1677
+ const { error } = await client().from(FLOWS).update({ is_active: isActive, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id);
1678
+ if (error) throw new Error(error.message);
1679
+ },
1680
+ async deleteFlow(id) {
1681
+ const { error } = await client().from(FLOWS).delete().eq("id", id);
1682
+ if (error) throw new Error(error.message);
1683
+ },
1684
+ async listSteps(flowId) {
1685
+ const { data, error } = await client().from(STEP_STATS).select("*").eq("flow_id", flowId).order("position");
1686
+ if (error) throw new Error(error.message);
1687
+ return (data ?? []).map(rowToStepStats);
1688
+ },
1689
+ async saveStep(flowId, input) {
1690
+ const row = {
1691
+ flow_id: flowId,
1692
+ position: input.position,
1693
+ delay_minutes: input.delayMinutes ?? 0,
1694
+ kind: input.kind ?? "message",
1695
+ template_key: input.kind === "task" ? null : input.templateKey ?? null,
1696
+ channel: input.kind === "task" ? null : input.channel ?? null,
1697
+ task_title: input.kind === "task" ? input.taskTitle ?? null : null,
1698
+ task_due_days: input.kind === "task" ? input.taskDueDays ?? null : null
1699
+ };
1700
+ if (input.id) {
1701
+ const { error: error2 } = await client().from(STEPS).update(row).eq("id", input.id);
1702
+ if (error2) throw new Error(error2.message);
1703
+ return;
1704
+ }
1705
+ row.tenant_id = getActiveTenantId();
1706
+ const { error } = await client().from(STEPS).insert(row);
1707
+ if (error) throw new Error(error.message);
1708
+ },
1709
+ async deleteStep(id) {
1710
+ const { error } = await client().from(STEPS).delete().eq("id", id);
1711
+ if (error) throw new Error(error.message);
1712
+ },
1713
+ async countsFor(flowId) {
1714
+ const { data, error } = await client().from(ENROLLMENTS).select("status").eq("flow_id", flowId);
1715
+ if (error) throw new Error(error.message);
1716
+ const rows = data ?? [];
1717
+ return {
1718
+ active: rows.filter((r) => r.status === "active").length,
1719
+ completed: rows.filter((r) => r.status === "completed").length,
1720
+ exited: rows.filter((r) => r.status === "exited").length
1721
+ };
1722
+ }
1723
+ };
1724
+ return store2;
1725
+ }
1726
+ var store = createSupabaseFlowStore();
1727
+ var DELAY_CHOICES = [0, 60, 1440, 2880, 4320, 10080];
1728
+ function useStepColumns(onDelete) {
1729
+ const t = useTranslation();
1730
+ return useMemo(() => [
1731
+ {
1732
+ accessorKey: "position",
1733
+ header: "#",
1734
+ cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-muted-foreground", children: getValue() })
1735
+ },
1736
+ {
1737
+ id: "step",
1738
+ header: t("automations.flow.colStep"),
1739
+ cell: ({ row }) => {
1740
+ const s = row.original;
1741
+ const isTask = s.kind === "task";
1742
+ return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [
1743
+ 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" }),
1744
+ isTask ? s.taskTitle : s.templateKey,
1745
+ !isTask && s.channel && /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: s.channel })
1746
+ ] });
1747
+ }
1748
+ },
1749
+ {
1750
+ accessorKey: "delayMinutes",
1751
+ header: t("automations.flow.colWait"),
1752
+ cell: ({ getValue }) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs text-muted-foreground", children: [
1753
+ /* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
1754
+ describeDelay(getValue(), t)
1755
+ ] })
1756
+ },
1757
+ // The scoreboard. Zeroes are shown rather than hidden: a step that has never
1758
+ // sent is the finding, not an empty cell.
1759
+ {
1760
+ accessorKey: "queued",
1761
+ header: t("automations.flow.colQueued"),
1762
+ cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
1763
+ },
1764
+ {
1765
+ accessorKey: "sent",
1766
+ header: t("automations.flow.colSent"),
1767
+ cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums", children: getValue() })
1768
+ },
1769
+ {
1770
+ accessorKey: "blocked",
1771
+ header: t("automations.flow.colBlocked"),
1772
+ cell: ({ getValue }) => {
1773
+ const n = getValue();
1774
+ return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-warning" : ""}`, children: n });
1775
+ }
1776
+ },
1777
+ {
1778
+ accessorKey: "failed",
1779
+ header: t("automations.flow.colFailed"),
1780
+ cell: ({ getValue }) => {
1781
+ const n = getValue();
1782
+ return /* @__PURE__ */ jsx("span", { className: `text-xs tabular-nums ${n > 0 ? "text-destructive" : ""}`, children: n });
1783
+ }
1784
+ },
1785
+ {
1786
+ id: "actions",
1787
+ header: "",
1788
+ cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(
1789
+ "button",
1790
+ {
1791
+ onClick: (e) => {
1792
+ e.stopPropagation();
1793
+ onDelete(row.original.id);
1794
+ },
1795
+ title: t("automations.flow.deleteStep"),
1796
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-destructive",
1797
+ children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
1798
+ }
1799
+ ) })
1800
+ }
1801
+ ], [t, onDelete]);
1802
+ }
1803
+ function StepComposer({ steps, onAdd }) {
1804
+ const t = useTranslation();
1805
+ const [kind, setKind] = useState("message");
1806
+ const [delay, setDelay] = useState(1440);
1807
+ const [value, setValue] = useState("");
1808
+ const submit = () => {
1809
+ if (!value.trim()) {
1810
+ toast.error(t(kind === "task" ? "automations.flow.needTitle" : "automations.flow.needTemplate"));
1811
+ return;
1812
+ }
1813
+ onAdd({
1814
+ kind,
1815
+ delayMinutes: delay,
1816
+ position: nextPosition(steps),
1817
+ ...kind === "task" ? { taskTitle: value.trim() } : { templateKey: value.trim() }
1818
+ });
1819
+ setValue("");
1820
+ };
1821
+ return /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-dashed p-3", children: [
1822
+ /* @__PURE__ */ jsxs(
1823
+ "select",
1824
+ {
1825
+ value: kind,
1826
+ onChange: (e) => {
1827
+ setKind(e.target.value);
1828
+ setValue("");
1829
+ },
1830
+ className: "rounded-md border bg-background px-2 py-1.5 text-sm",
1831
+ children: [
1832
+ /* @__PURE__ */ jsx("option", { value: "message", children: t("automations.flow.kindMessage") }),
1833
+ /* @__PURE__ */ jsx("option", { value: "task", children: t("automations.flow.kindTask") })
1834
+ ]
1835
+ }
1836
+ ),
1837
+ /* @__PURE__ */ jsx(
1838
+ "select",
1839
+ {
1840
+ value: delay,
1841
+ onChange: (e) => setDelay(Number(e.target.value)),
1842
+ className: "rounded-md border bg-background px-2 py-1.5 text-sm",
1843
+ children: DELAY_CHOICES.map((m) => /* @__PURE__ */ jsx("option", { value: m, children: describeDelay(m, t) }, m))
1844
+ }
1845
+ ),
1846
+ /* @__PURE__ */ jsx(
1847
+ "input",
1848
+ {
1849
+ value,
1850
+ onChange: (e) => setValue(e.target.value),
1851
+ onKeyDown: (e) => {
1852
+ if (e.key === "Enter") submit();
1853
+ },
1854
+ placeholder: t(kind === "task" ? "automations.flow.titlePlaceholder" : "automations.flow.templatePlaceholder"),
1855
+ className: "min-w-[200px] flex-1 rounded-md border bg-background px-2 py-1.5 text-sm"
1856
+ }
1857
+ ),
1858
+ /* @__PURE__ */ jsxs(
1859
+ "button",
1860
+ {
1861
+ onClick: submit,
1862
+ className: "inline-flex items-center gap-1 rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground hover:opacity-90",
1863
+ children: [
1864
+ /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
1865
+ t("automations.flow.addStep")
1866
+ ]
1867
+ }
1868
+ )
1869
+ ] });
1870
+ }
1871
+ function FlowsPage() {
1872
+ const t = useTranslation();
1873
+ const [flows, setFlows] = useState([]);
1874
+ const [loading, setLoading] = useState(true);
1875
+ const [selectedId, setSelectedId] = useState(null);
1876
+ const [steps, setSteps] = useState([]);
1877
+ const [counts, setCounts] = useState(null);
1878
+ const [composerOpen, setComposerOpen] = useState(false);
1879
+ const load = useCallback(async () => {
1880
+ setLoading(true);
1881
+ try {
1882
+ setFlows(await store.listFlows());
1883
+ } catch (e) {
1884
+ toast.error(errorMessage(e));
1885
+ } finally {
1886
+ setLoading(false);
1887
+ }
1888
+ }, []);
1889
+ const selectedRef = useRef(null);
1890
+ selectedRef.current = selectedId;
1891
+ const loadDetail = useCallback(async (flowId) => {
1892
+ try {
1893
+ const [s, c] = await Promise.all([store.listSteps(flowId), store.countsFor(flowId)]);
1894
+ if (selectedRef.current !== flowId) return;
1895
+ setSteps(s);
1896
+ setCounts(c);
1897
+ } catch (e) {
1898
+ toast.error(errorMessage(e));
1899
+ }
1900
+ }, []);
1901
+ const deleteStep = useCallback((id) => {
1902
+ void (async () => {
1903
+ try {
1904
+ await store.deleteStep(id);
1905
+ if (selectedId) await loadDetail(selectedId);
1906
+ } catch (e) {
1907
+ toast.error(errorMessage(e));
1908
+ }
1909
+ })();
1910
+ }, [selectedId, loadDetail]);
1911
+ const stepColumns = useStepColumns(deleteStep);
1912
+ useEffect(() => {
1913
+ void load();
1914
+ }, [load]);
1915
+ useEffect(() => {
1916
+ setSteps([]);
1917
+ setCounts(null);
1918
+ if (selectedId) void loadDetail(selectedId);
1919
+ }, [selectedId, loadDetail]);
1920
+ flows.find((f) => f.id === selectedId) ?? null;
1921
+ async function createFlow(input) {
1922
+ const flow = await store.saveFlow(input);
1923
+ await load();
1924
+ setSelectedId(flow.id);
1925
+ toast.success(t("automations.flow.created"));
1926
+ }
1927
+ async function toggleActive(flow) {
1928
+ if (!flow.isActive) {
1929
+ const s = await store.listSteps(flow.id);
1930
+ if (s.length === 0) {
1931
+ toast.error(t("automations.flow.needStepsToActivate"));
1932
+ return;
1933
+ }
1934
+ }
1935
+ try {
1936
+ await store.setFlowActive(flow.id, !flow.isActive);
1937
+ await load();
1938
+ } catch (e) {
1939
+ toast.error(errorMessage(e));
1940
+ }
1941
+ }
1942
+ if (loading) {
1943
+ 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: [
1944
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-4 shrink-0 animate-pulse rounded bg-muted/40" }),
1945
+ /* @__PURE__ */ jsx("div", { className: "h-3.5 animate-pulse rounded bg-muted/40", style: { width: `${34 - i * 6}%` } }),
1946
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-28 animate-pulse rounded-full bg-muted/30" }),
1947
+ /* @__PURE__ */ jsx("div", { className: "ml-auto h-5 w-9 animate-pulse rounded-full bg-muted/30" })
1948
+ ] }) }, i)) });
1949
+ }
1950
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1951
+ /* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
1952
+ PageActions,
1953
+ {
1954
+ actions: [{
1955
+ id: "new-flow",
1956
+ label: t("automations.flow.new"),
1957
+ icon: Plus,
1958
+ intent: "primary",
1959
+ creates: true,
1960
+ onSelect: () => setComposerOpen(true)
1961
+ }]
1962
+ }
1963
+ ) }),
1964
+ /* @__PURE__ */ jsx(
1965
+ CadenceComposer,
1966
+ {
1967
+ open: composerOpen,
1968
+ onClose: () => setComposerOpen(false),
1969
+ onCreate: createFlow
1970
+ }
1971
+ ),
1972
+ flows.length === 0 ? /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-1 border-dashed py-12 text-center", children: [
1973
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("automations.flow.emptyTitle") }),
1974
+ /* @__PURE__ */ jsx("p", { className: "max-w-md text-xs text-muted-foreground", children: t("automations.flow.emptyHint") })
1975
+ ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: flows.map((flow) => /* @__PURE__ */ jsxs(Card, { className: "p-3", children: [
1976
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
1977
+ /* @__PURE__ */ jsxs(
1978
+ "button",
1979
+ {
1980
+ onClick: () => setSelectedId(selectedId === flow.id ? null : flow.id),
1981
+ className: "flex flex-1 items-center gap-2 text-left",
1982
+ children: [
1983
+ /* @__PURE__ */ jsx(
1984
+ ChevronRight,
1985
+ {
1986
+ className: `h-4 w-4 text-muted-foreground transition-transform ${selectedId === flow.id ? "rotate-90" : ""}`
1987
+ }
1988
+ ),
1989
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: flow.name }),
1990
+ /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground", children: flow.entryEvent })
1991
+ ]
1992
+ }
1993
+ ),
1994
+ /* @__PURE__ */ jsx(
1995
+ Switch,
1996
+ {
1997
+ checked: flow.isActive,
1998
+ onCheckedChange: () => {
1999
+ void toggleActive(flow);
2000
+ },
2001
+ "aria-label": t("automations.flow.toggle")
2002
+ }
2003
+ )
2004
+ ] }),
2005
+ selectedId === flow.id && /* @__PURE__ */ jsxs("div", { className: "mt-3 border-t pt-3", children: [
2006
+ counts && /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs text-muted-foreground", children: t("automations.flow.counts", {
2007
+ active: String(counts.active),
2008
+ completed: String(counts.completed),
2009
+ exited: String(counts.exited)
2010
+ }) }),
2011
+ /* @__PURE__ */ jsx(
2012
+ DataTable,
2013
+ {
2014
+ columns: stepColumns,
2015
+ data: steps,
2016
+ emptyMessage: /* @__PURE__ */ jsx("p", { className: "py-4 text-xs text-muted-foreground", children: t("automations.flow.noSteps") })
2017
+ }
2018
+ ),
2019
+ /* @__PURE__ */ jsx(
2020
+ StepComposer,
2021
+ {
2022
+ steps,
2023
+ onAdd: (input) => {
2024
+ void (async () => {
2025
+ try {
2026
+ await store.saveStep(flow.id, input);
2027
+ await loadDetail(flow.id);
2028
+ } catch (e) {
2029
+ toast.error(errorMessage(e));
2030
+ }
2031
+ })();
2032
+ }
2033
+ }
2034
+ )
2035
+ ] })
2036
+ ] }, flow.id)) })
2037
+ ] });
2038
+ }
2039
+
2040
+ // src/locales/en.ts
2041
+ var en = {
2042
+ "automations.flow.newTitle": "New cadence",
2043
+ "automations.flow.nameLabel": "Name",
2044
+ "automations.flow.namePlaceholder": "e.g. New lead sequence",
2045
+ "automations.flow.entryLabel": "Who enters",
2046
+ "automations.flow.entryPlaceholder": "Pick the fact that puts somebody in",
2047
+ "automations.flow.exitLabel": "Who leaves",
2048
+ "automations.flow.exitNone": "Only leaves when the steps run out",
2049
+ "automations.flow.exitHint": "The fact that stops the sequence. Without it, someone who already replied still gets the day-5 message.",
2050
+ "automations.flow.bornOffHint": "A cadence is born off and empty. Add the steps below and switch it on when it is ready.",
2051
+ "automations.flow.noEvents": "No active module announces facts in this app \u2014 no trigger, no cadence.",
2052
+ "automations.flow.create": "Create cadence",
2053
+ "automations.flow.new": "New flow",
2054
+ "automations.flow.loading": "Loading flows\u2026",
2055
+ "automations.flow.emptyTitle": "No cadence flows yet",
2056
+ "automations.flow.emptyHint": "A flow touches the same lead more than once \u2014 a message today, a call in two days, another message on Friday \u2014 and stops on its own when they answer.",
2057
+ "automations.flow.namePrompt": "Name this flow",
2058
+ "automations.flow.entryPrompt": "Which event puts someone in?",
2059
+ "automations.flow.created": "Flow created. It starts switched off.",
2060
+ "automations.flow.toggle": "Active",
2061
+ "automations.flow.needStepsToActivate": "Add a step first \u2014 an empty flow enrols people into nothing.",
2062
+ "automations.flow.noSteps": "No steps yet.",
2063
+ "automations.flow.counts": "{{active}} in the flow \xB7 {{completed}} finished \xB7 {{exited}} left early",
2064
+ "automations.flow.colStep": "Step",
2065
+ "automations.flow.colWait": "Wait",
2066
+ "automations.flow.colQueued": "Queued",
2067
+ "automations.flow.colSent": "Sent",
2068
+ "automations.flow.colBlocked": "Blocked",
2069
+ "automations.flow.colFailed": "Failed",
2070
+ "automations.flow.addStep": "Add step",
2071
+ "automations.flow.deleteStep": "Remove step",
2072
+ "automations.flow.kindMessage": "Message",
2073
+ "automations.flow.kindTask": "Task",
2074
+ "automations.flow.templatePlaceholder": "Template key, e.g. lead.followup",
2075
+ "automations.flow.titlePlaceholder": "What should somebody do?",
2076
+ "automations.flow.needTemplate": "A message step needs a template.",
2077
+ "automations.flow.needTitle": "A task step needs a title.",
2078
+ "automations.flow.delayNow": "Right away",
2079
+ "automations.flow.delayMinutes": "{{count}} min later",
2080
+ "automations.flow.delayHours": "{{count}}h later",
2081
+ "automations.flow.delayDays": "{{count}} days later"
2082
+ };
2083
+
2084
+ // src/locales/pt-BR.ts
2085
+ var ptBR = {
2086
+ "automations.flow.newTitle": "Nova cad\xEAncia",
2087
+ "automations.flow.nameLabel": "Nome",
2088
+ "automations.flow.namePlaceholder": "ex.: R\xE9gua do lead novo",
2089
+ "automations.flow.entryLabel": "Quem entra",
2090
+ "automations.flow.entryPlaceholder": "Escolha o fato que coloca algu\xE9m na r\xE9gua",
2091
+ "automations.flow.exitLabel": "Quem sai",
2092
+ "automations.flow.exitNone": "S\xF3 sai quando os passos acabam",
2093
+ "automations.flow.exitHint": "O fato que faz a pessoa parar de receber. Sem ele, quem j\xE1 respondeu continua recebendo a mensagem do dia 5.",
2094
+ "automations.flow.bornOffHint": "A cad\xEAncia nasce desligada e sem passos. Monte os passos abaixo e ligue quando estiver pronta.",
2095
+ "automations.flow.noEvents": "Nenhum m\xF3dulo ativo anuncia fatos neste app \u2014 sem gatilho n\xE3o h\xE1 cad\xEAncia.",
2096
+ "automations.flow.create": "Criar cad\xEAncia",
2097
+ "automations.flow.new": "Novo fluxo",
2098
+ "automations.flow.loading": "Carregando fluxos\u2026",
2099
+ "automations.flow.emptyTitle": "Nenhum fluxo de cad\xEAncia ainda",
2100
+ "automations.flow.emptyHint": "Um fluxo toca o mesmo lead mais de uma vez \u2014 uma mensagem hoje, uma liga\xE7\xE3o em dois dias, outra mensagem na sexta \u2014 e para sozinho quando a pessoa responde.",
2101
+ "automations.flow.namePrompt": "Nome do fluxo",
2102
+ "automations.flow.entryPrompt": "Qual evento coloca algu\xE9m aqui?",
2103
+ "automations.flow.created": "Fluxo criado. Ele nasce desligado.",
2104
+ "automations.flow.toggle": "Ativo",
2105
+ "automations.flow.needStepsToActivate": "Adicione um passo antes \u2014 um fluxo vazio inscreve gente em nada.",
2106
+ "automations.flow.noSteps": "Nenhum passo ainda.",
2107
+ "automations.flow.counts": "{{active}} no fluxo \xB7 {{completed}} conclu\xEDram \xB7 {{exited}} sa\xEDram antes",
2108
+ "automations.flow.colStep": "Passo",
2109
+ "automations.flow.colWait": "Espera",
2110
+ "automations.flow.colQueued": "Na fila",
2111
+ "automations.flow.colSent": "Enviados",
2112
+ "automations.flow.colBlocked": "Bloqueados",
2113
+ "automations.flow.colFailed": "Falharam",
2114
+ "automations.flow.addStep": "Adicionar passo",
2115
+ "automations.flow.deleteStep": "Remover passo",
2116
+ "automations.flow.kindMessage": "Mensagem",
2117
+ "automations.flow.kindTask": "Tarefa",
2118
+ "automations.flow.templatePlaceholder": "Chave do modelo, ex.: lead.followup",
2119
+ "automations.flow.titlePlaceholder": "O que algu\xE9m precisa fazer?",
2120
+ "automations.flow.needTemplate": "Um passo de mensagem precisa de um modelo.",
2121
+ "automations.flow.needTitle": "Um passo de tarefa precisa de um t\xEDtulo.",
2122
+ "automations.flow.delayNow": "Na hora",
2123
+ "automations.flow.delayMinutes": "{{count}} min depois",
2124
+ "automations.flow.delayHours": "{{count}}h depois",
2125
+ "automations.flow.delayDays": "{{count}} dias depois"
2126
+ };
2127
+
2128
+ // src/locales/index.ts
2129
+ var automationsLocales = {
2130
+ en,
2131
+ "pt-BR": ptBR
2132
+ };
2133
+
2134
+ // src/migrations/index.ts
2135
+ var MIGRATION_000_BASELINE = `-- ============================================================================
2136
+ -- plugins/plugin-automations/migrations/000_baseline.sql \u2014 what installing this provisions, as one file.
2137
+ --
2138
+ -- GENERATED by scripts/emit-unit-baselines.mjs (#338). Do not edit by hand:
2139
+ -- change the schema, regenerate, and let scripts/check-chain-equivalence.mjs
2140
+ -- prove the result still matches.
2141
+ --
2142
+ -- This replaced 4 migration files. They are kept, unapplied, in
2143
+ -- migrations.archive/ \u2014 a year of decisions is worth reading even when it is no
2144
+ -- longer worth replaying.
2145
+ --
2146
+ -- Object order is fixed rather than dependency-sorted: schemas, types,
2147
+ -- sequences, tables, defaults, functions, constraints, views, indexes, foreign
2148
+ -- keys, triggers, row security, policies, grants. Dependencies BETWEEN units
2149
+ -- are carried by the order packages/db/chain.json declares.
2150
+ -- ============================================================================
2151
+
2152
+ -- A LANGUAGE sql function binds its body at CREATE time, and 570 functions
2153
+ -- sorted by name are not sorted by who calls whom. This is what lets them load
2154
+ -- in any order; every body is still compiled on first call, so a genuinely
2155
+ -- broken reference surfaces then rather than never. Session-scoped.
2156
+ SET check_function_bodies = false;
2157
+
2158
+
2159
+
2160
+ -- \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
2161
+ -- Cleared BEFORE anything is created, so every object below gets the ACL the
2162
+ -- dump describes rather than the image's defaults on top of it. Restored at
2163
+ -- the end of this file.
2164
+
2165
+ DO $dp$ BEGIN
2166
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
2167
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2168
+ 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$;
2169
+ END $dp$;
2170
+
2171
+ DO $dp$ BEGIN
2172
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated, service_role, fayz_connector$stmt$;
2173
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2174
+ 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$;
2175
+ END $dp$;
2176
+
2177
+ DO $dp$ BEGIN
2178
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
2179
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2180
+ 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$;
2181
+ END $dp$;
2182
+
2183
+ DO $dp$ BEGIN
2184
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated, service_role, fayz_connector$stmt$;
2185
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2186
+ 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$;
2187
+ END $dp$;
2188
+
2189
+ DO $dp$ BEGIN
2190
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
2191
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2192
+ 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$;
2193
+ END $dp$;
2194
+
2195
+ DO $dp$ BEGIN
2196
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated, service_role, fayz_connector$stmt$;
2197
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2198
+ 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$;
2199
+ END $dp$;
2200
+
2201
+
2202
+ -- \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
2203
+
2204
+ CREATE TABLE public.plg_automations_provider_templates (
2205
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
2206
+ tenant_id uuid,
2207
+ event_key text NOT NULL,
2208
+ channel text DEFAULT 'whatsapp'::text NOT NULL,
2209
+ provider text DEFAULT 'tyxter'::text NOT NULL,
2210
+ provider_template_id text,
2211
+ template_name text NOT NULL,
2212
+ language text DEFAULT 'pt_BR'::text NOT NULL,
2213
+ variable_map jsonb DEFAULT '[]'::jsonb NOT NULL,
2214
+ actions_map jsonb DEFAULT '[]'::jsonb NOT NULL,
2215
+ status text DEFAULT 'draft'::text NOT NULL,
2216
+ rejection_reason text,
2217
+ body_snapshot text,
2218
+ submitted_at timestamp with time zone,
2219
+ approved_at timestamp with time zone,
2220
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
2221
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
2222
+ CONSTRAINT plg_automations_provider_templates_status_check CHECK ((status = ANY (ARRAY['draft'::text, 'submitted'::text, 'approved'::text, 'rejected'::text, 'paused'::text, 'disabled'::text])))
2223
+ );
2224
+
2225
+ CREATE TABLE public.plg_automations_templates (
2226
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
2227
+ tenant_id uuid NOT NULL,
2228
+ event_key text NOT NULL,
2229
+ channel text DEFAULT 'email'::text NOT NULL,
2230
+ enabled boolean,
2231
+ subject text,
2232
+ body text,
2233
+ name text,
2234
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
2235
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
2236
+ actions jsonb
2237
+ );
2238
+
2239
+
2240
+ -- \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
2241
+
2242
+ CREATE FUNCTION public.automations_set_updated_at() RETURNS trigger
2243
+ LANGUAGE plpgsql
2244
+ AS $$
2245
+ BEGIN
2246
+ NEW.updated_at = now();
2247
+ RETURN NEW;
2248
+ END $$;
2249
+
2250
+
2251
+ -- \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
2252
+
2253
+ ALTER TABLE ONLY public.plg_automations_provider_templates
2254
+ ADD CONSTRAINT plg_automations_provider_templates_pkey PRIMARY KEY (id);
2255
+
2256
+ ALTER TABLE ONLY public.plg_automations_templates
2257
+ ADD CONSTRAINT plg_automations_templates_pkey PRIMARY KEY (id);
2258
+
2259
+
2260
+ -- \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
2261
+
2262
+ CREATE INDEX idx_plg_automations_provider_templates_lookup ON public.plg_automations_provider_templates USING btree (event_key, channel, provider, status);
2263
+
2264
+ CREATE INDEX plg_automations_templates_tenant_idx ON public.plg_automations_templates USING btree (tenant_id);
2265
+
2266
+ CREATE UNIQUE INDEX plg_automations_templates_unique_idx ON public.plg_automations_templates USING btree (tenant_id, event_key, channel);
2267
+
2268
+ 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);
2269
+
2270
+ 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);
2271
+
2272
+
2273
+ -- \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
2274
+
2275
+ ALTER TABLE ONLY public.plg_automations_provider_templates
2276
+ ADD CONSTRAINT plg_automations_provider_templates_tenant_id_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
2277
+
2278
+
2279
+ -- \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
2280
+
2281
+ 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();
2282
+
2283
+ 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();
2284
+
2285
+
2286
+ -- \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
2287
+
2288
+ ALTER TABLE public.plg_automations_provider_templates ENABLE ROW LEVEL SECURITY;
2289
+
2290
+ ALTER TABLE public.plg_automations_templates ENABLE ROW LEVEL SECURITY;
2291
+
2292
+
2293
+ -- \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
2294
+
2295
+ 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))));
2296
+
2297
+ 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)));
2298
+
2299
+
2300
+ -- \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
2301
+
2302
+ GRANT ALL ON FUNCTION public.automations_set_updated_at() TO authenticated;
2303
+ GRANT ALL ON FUNCTION public.automations_set_updated_at() TO service_role;
2304
+
2305
+ GRANT MAINTAIN ON TABLE public.plg_automations_provider_templates TO anon;
2306
+ GRANT ALL ON TABLE public.plg_automations_provider_templates TO authenticated;
2307
+ GRANT ALL ON TABLE public.plg_automations_provider_templates TO service_role;
2308
+
2309
+ GRANT MAINTAIN ON TABLE public.plg_automations_templates TO anon;
2310
+ GRANT ALL ON TABLE public.plg_automations_templates TO authenticated;
2311
+ GRANT ALL ON TABLE public.plg_automations_templates TO service_role;
2312
+
2313
+
2314
+ -- \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
2315
+
2316
+ 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.';
2317
+
2318
+
2319
+ -- \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
2320
+ -- Put back, so the NEXT thing installed inherits what the chain had.
2321
+
2322
+ DO $dp$ BEGIN
2323
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
2324
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2325
+ 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$;
2326
+ END $dp$;
2327
+
2328
+ DO $dp$ BEGIN
2329
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
2330
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2331
+ 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$;
2332
+ END $dp$;
2333
+
2334
+ DO $dp$ BEGIN
2335
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
2336
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2337
+ 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$;
2338
+ END $dp$;
2339
+
2340
+ DO $dp$ BEGIN
2341
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
2342
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2343
+ 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$;
2344
+ END $dp$;
2345
+
2346
+ DO $dp$ BEGIN
2347
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres$stmt$;
2348
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2349
+ 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$;
2350
+ END $dp$;
2351
+
2352
+ DO $dp$ BEGIN
2353
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO anon$stmt$;
2354
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2355
+ 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$;
2356
+ END $dp$;
2357
+
2358
+ DO $dp$ BEGIN
2359
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated$stmt$;
2360
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2361
+ 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$;
2362
+ END $dp$;
2363
+
2364
+ DO $dp$ BEGIN
2365
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON SEQUENCES TO service_role$stmt$;
2366
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2367
+ 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$;
2368
+ END $dp$;
2369
+
2370
+ DO $dp$ BEGIN
2371
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
2372
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2373
+ 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$;
2374
+ END $dp$;
2375
+
2376
+ DO $dp$ BEGIN
2377
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
2378
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2379
+ 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$;
2380
+ END $dp$;
2381
+
2382
+ DO $dp$ BEGIN
2383
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
2384
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2385
+ 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$;
2386
+ END $dp$;
2387
+
2388
+ DO $dp$ BEGIN
2389
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres$stmt$;
2390
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2391
+ 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$;
2392
+ END $dp$;
2393
+
2394
+ DO $dp$ BEGIN
2395
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon$stmt$;
2396
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2397
+ 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$;
2398
+ END $dp$;
2399
+
2400
+ DO $dp$ BEGIN
2401
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO authenticated$stmt$;
2402
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2403
+ 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$;
2404
+ END $dp$;
2405
+
2406
+ DO $dp$ BEGIN
2407
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON FUNCTIONS TO service_role$stmt$;
2408
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2409
+ 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$;
2410
+ END $dp$;
2411
+
2412
+ DO $dp$ BEGIN
2413
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
2414
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2415
+ 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$;
2416
+ END $dp$;
2417
+
2418
+ DO $dp$ BEGIN
2419
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT MAINTAIN ON TABLES TO anon$stmt$;
2420
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2421
+ 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$;
2422
+ END $dp$;
2423
+
2424
+ DO $dp$ BEGIN
2425
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
2426
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2427
+ 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$;
2428
+ END $dp$;
2429
+
2430
+ DO $dp$ BEGIN
2431
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
2432
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2433
+ 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$;
2434
+ END $dp$;
2435
+
2436
+ DO $dp$ BEGIN
2437
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO postgres$stmt$;
2438
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2439
+ 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$;
2440
+ END $dp$;
2441
+
2442
+ DO $dp$ BEGIN
2443
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO anon$stmt$;
2444
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2445
+ 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$;
2446
+ END $dp$;
2447
+
2448
+ DO $dp$ BEGIN
2449
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO authenticated$stmt$;
2450
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2451
+ 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$;
2452
+ END $dp$;
2453
+
2454
+ DO $dp$ BEGIN
2455
+ EXECUTE $stmt$ALTER DEFAULT PRIVILEGES FOR ROLE supabase_admin IN SCHEMA public GRANT ALL ON TABLES TO service_role$stmt$;
2456
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2457
+ 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$;
2458
+ END $dp$;
2459
+
2460
+ DO $dp$ BEGIN
2461
+ EXECUTE $stmt$--
2462
+ -- PostgreSQL database dump complete
2463
+ --$stmt$;
2464
+ EXCEPTION WHEN insufficient_privilege OR undefined_object THEN
2465
+ RAISE NOTICE 'baseline: not ours to set \u2014 %', $stmt$--
2466
+ -- PostgreSQL database dump complete
2467
+ --$stmt$;
2468
+ END $dp$;
2469
+ `;
2470
+ var MIGRATION_001_THE_FLOW_HAS_STEPS = `-- 001_the_flow_has_steps.sql
2471
+ --
2472
+ -- A CADENCE: the same lead touched on day 0, day 2 and day 5, by itself.
2473
+ --
2474
+ -- This plugin's README has promised "multi-step sequences, and enrollment
2475
+ -- stats" since M1, and \`AutomationsList.tsx\` says plainly what shipped instead:
2476
+ -- "um fluxo de um passo \xE9 o texto com o gatilho escrito na frente". One row per
2477
+ -- (event, channel). Nothing waits, nothing remembers where a person got to, and
2478
+ -- nothing stops when they reply.
2479
+ --
2480
+ -- WHAT THIS DOES NOT BUILD, BECAUSE IT ALREADY EXISTS.
2481
+ --
2482
+ -- * The clock. \`fayz_event_runner\` is a pg_cron job that already calls
2483
+ -- \`event_runner_tick(200)\` every minute. This adds a fifth call to it
2484
+ -- (packages/db 046), guarded like the other four.
2485
+ -- * The delay. \`notifications_enqueue(..., p_scheduled_for, p_dedupe_key)\`
2486
+ -- already means "send this at time T, and not twice". A cadence step is a
2487
+ -- row in that queue with a computed \`scheduled_for\`.
2488
+ -- * Consent, channel preference and quiet-channel fallback \u2014 all inside
2489
+ -- \`notifications_resolve_channel\`, which plugin-notifications 002 just
2490
+ -- taught to read the opt-out correctly. A cadence that dodged the queue
2491
+ -- would dodge consent with it, which is the whole reason it does not.
2492
+ -- * The claim-and-retry shape. \`marketing_run_due\` / \`marketing_campaign_run\`
2493
+ -- already solve "advance a set of enrolled people on a tick" with
2494
+ -- \`FOR UPDATE SKIP LOCKED\`. \`automations_flows_run_due\` is that function
2495
+ -- with a step pointer.
2496
+ --
2497
+ -- THE THREE DECISIONS WORTH ARGUING WITH.
2498
+ --
2499
+ -- 1. THE DELAY IS AN OFFSET FROM THE PREVIOUS STEP, NOT FROM ENROLMENT.
2500
+ -- "Two days after the call" is how a salesperson describes a cadence, and it
2501
+ -- survives inserting a step in the middle. Absolute offsets from day 0 mean
2502
+ -- every later step silently shifts when you add one.
2503
+ --
2504
+ -- 2. THE ENROLMENT CARRIES THE STEP POINTER, AND THE DEDUPE KEY CARRIES THE
2505
+ -- POSITION. \`flow:<enrolment>:<position>\` means replaying a tick, or two
2506
+ -- workers taking the same row, cannot send a step twice \u2014
2507
+ -- \`notifications_enqueue\` refuses a repeated \`dedupe_key\` before it writes
2508
+ -- anything. The SKIP LOCKED claim is the first defence; this is the one that
2509
+ -- survives a crash between the enqueue and the pointer update.
2510
+ --
2511
+ -- 3. A FLOW IS BORN INACTIVE. \`is_active\` defaults false. A cadence that starts
2512
+ -- sending the moment somebody saves a draft is a cadence that sends a draft.
2513
+ --
2514
+ -- WHAT IS STILL MISSING AFTER THIS, AND IS NOT PRETENDED OTHERWISE: e-mail and
2515
+ -- SMS still resolve to \`notifications_send_to_log\`, which records and sends
2516
+ -- nothing. A cadence on those channels will enqueue, drain, and deliver to a
2517
+ -- log row. WhatsApp reaches a provider; in-app reaches the bell.
2518
+
2519
+ SET check_function_bodies = false;
2520
+
2521
+ -- \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
2522
+
2523
+ CREATE TABLE IF NOT EXISTS public.plg_automations_flows (
2524
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
2525
+ tenant_id uuid NOT NULL,
2526
+ unit_id uuid,
2527
+ name text NOT NULL,
2528
+ description text,
2529
+ -- The fact that puts somebody in. Names an event from the aggregated plugin
2530
+ -- catalog (\`crm.lead_created\`, \`crm.stage_changed\`, \u2026); it is text and not a
2531
+ -- foreign key because the catalog is assembled at runtime from whichever
2532
+ -- plugins an app mounts.
2533
+ entry_event text NOT NULL,
2534
+ -- The facts that take somebody out. Empty means the flow only ends by
2535
+ -- running out of steps.
2536
+ exit_events text[] DEFAULT '{}'::text[] NOT NULL,
2537
+ is_active boolean DEFAULT false NOT NULL,
2538
+ owner_id uuid,
2539
+ created_at timestamptz DEFAULT now() NOT NULL,
2540
+ updated_at timestamptz DEFAULT now() NOT NULL,
2541
+ CONSTRAINT plg_automations_flows_pkey PRIMARY KEY (id)
2542
+ );
2543
+
2544
+ CREATE TABLE IF NOT EXISTS public.plg_automations_flow_steps (
2545
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
2546
+ tenant_id uuid NOT NULL,
2547
+ flow_id uuid NOT NULL,
2548
+ -- Sparse on purpose (10, 20, 30\u2026): inserting between two steps should not
2549
+ -- renumber the ones after it, and the enrolment's pointer names a position.
2550
+ position integer NOT NULL,
2551
+ -- Minutes to wait AFTER THE PREVIOUS STEP. The first step's delay is measured
2552
+ -- from enrolment, so 0 means "right away".
2553
+ delay_minutes integer DEFAULT 0 NOT NULL,
2554
+ kind text DEFAULT 'message' NOT NULL,
2555
+ -- kind='message': which template, and optionally force a channel. NULL
2556
+ -- channel lets notifications_resolve_channel pick, which is what honours the
2557
+ -- recipient's preference.
2558
+ template_key text,
2559
+ channel text,
2560
+ -- kind='task': what the human is asked to do, and by when.
2561
+ task_title text,
2562
+ task_due_days integer,
2563
+ created_at timestamptz DEFAULT now() NOT NULL,
2564
+ updated_at timestamptz DEFAULT now() NOT NULL,
2565
+ CONSTRAINT plg_automations_flow_steps_pkey PRIMARY KEY (id),
2566
+ CONSTRAINT plg_automations_flow_steps_kind_check
2567
+ CHECK (kind = ANY (ARRAY['message'::text, 'task'::text])),
2568
+ CONSTRAINT plg_automations_flow_steps_delay_check CHECK (delay_minutes >= 0),
2569
+ -- A message step with no template has nothing to send; a task step with no
2570
+ -- title gives the human nothing to read. Either is a step that would fail at
2571
+ -- 3am rather than at save time.
2572
+ CONSTRAINT plg_automations_flow_steps_payload_check CHECK (
2573
+ (kind = 'message' AND template_key IS NOT NULL)
2574
+ OR (kind = 'task' AND task_title IS NOT NULL)
2575
+ )
2576
+ );
2577
+
2578
+ CREATE TABLE IF NOT EXISTS public.plg_automations_enrollments (
2579
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
2580
+ tenant_id uuid NOT NULL,
2581
+ flow_id uuid NOT NULL,
2582
+ person_id uuid NOT NULL,
2583
+ -- What put them here, for the timeline: ('lead', <id>) or ('deal', <id>).
2584
+ subject_type text,
2585
+ subject_id uuid,
2586
+ status text DEFAULT 'active' NOT NULL,
2587
+ -- The position of the step that runs NEXT. NULL once nothing is left.
2588
+ current_position integer,
2589
+ next_run_at timestamptz DEFAULT now() NOT NULL,
2590
+ entered_at timestamptz DEFAULT now() NOT NULL,
2591
+ exited_at timestamptz,
2592
+ exit_reason text,
2593
+ created_at timestamptz DEFAULT now() NOT NULL,
2594
+ updated_at timestamptz DEFAULT now() NOT NULL,
2595
+ CONSTRAINT plg_automations_enrollments_pkey PRIMARY KEY (id),
2596
+ CONSTRAINT plg_automations_enrollments_status_check
2597
+ CHECK (status = ANY (ARRAY['active'::text, 'completed'::text, 'exited'::text]))
2598
+ );
2599
+
2600
+ -- \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
2601
+
2602
+ ALTER TABLE public.plg_automations_flows
2603
+ DROP CONSTRAINT IF EXISTS plg_automations_flows_tenant_fkey;
2604
+ ALTER TABLE public.plg_automations_flows
2605
+ ADD CONSTRAINT plg_automations_flows_tenant_fkey
2606
+ FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
2607
+
2608
+ ALTER TABLE public.plg_automations_flow_steps
2609
+ DROP CONSTRAINT IF EXISTS plg_automations_flow_steps_flow_fkey;
2610
+ ALTER TABLE public.plg_automations_flow_steps
2611
+ ADD CONSTRAINT plg_automations_flow_steps_flow_fkey
2612
+ FOREIGN KEY (flow_id) REFERENCES public.plg_automations_flows(id) ON DELETE CASCADE;
2613
+
2614
+ ALTER TABLE public.plg_automations_enrollments
2615
+ DROP CONSTRAINT IF EXISTS plg_automations_enrollments_flow_fkey;
2616
+ ALTER TABLE public.plg_automations_enrollments
2617
+ ADD CONSTRAINT plg_automations_enrollments_flow_fkey
2618
+ FOREIGN KEY (flow_id) REFERENCES public.plg_automations_flows(id) ON DELETE CASCADE;
2619
+
2620
+ -- \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
2621
+
2622
+ CREATE UNIQUE INDEX IF NOT EXISTS plg_automations_flow_steps_position_uq
2623
+ ON public.plg_automations_flow_steps (flow_id, position);
2624
+ CREATE INDEX IF NOT EXISTS plg_automations_flows_tenant_idx
2625
+ ON public.plg_automations_flows (tenant_id);
2626
+ CREATE INDEX IF NOT EXISTS plg_automations_flows_entry_idx
2627
+ ON public.plg_automations_flows (tenant_id, entry_event) WHERE is_active;
2628
+
2629
+ -- One live enrolment per person per flow. Re-entering a cadence somebody is
2630
+ -- already in would double every remaining message.
2631
+ CREATE UNIQUE INDEX IF NOT EXISTS plg_automations_enrollments_live_uq
2632
+ ON public.plg_automations_enrollments (flow_id, person_id) WHERE status = 'active';
2633
+ -- The claim index: the runner only ever asks for due, active rows.
2634
+ CREATE INDEX IF NOT EXISTS plg_automations_enrollments_due_idx
2635
+ ON public.plg_automations_enrollments (next_run_at) WHERE status = 'active';
2636
+ CREATE INDEX IF NOT EXISTS plg_automations_enrollments_person_idx
2637
+ ON public.plg_automations_enrollments (tenant_id, person_id);
2638
+
2639
+ -- \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
2640
+
2641
+ -- ENABLE **and** FORCE. Without FORCE the table owner \u2014 which is the role that
2642
+ -- runs migrations and every SECURITY DEFINER function here \u2014 bypasses these
2643
+ -- policies entirely, and \`packages/db/test/pgtap/900_verification/001_posture.sql\`
2644
+ -- (N14b) fails the whole pool for it.
2645
+ ALTER TABLE public.plg_automations_flows ENABLE ROW LEVEL SECURITY;
2646
+ ALTER TABLE public.plg_automations_flows FORCE ROW LEVEL SECURITY;
2647
+ ALTER TABLE public.plg_automations_flow_steps ENABLE ROW LEVEL SECURITY;
2648
+ ALTER TABLE public.plg_automations_flow_steps FORCE ROW LEVEL SECURITY;
2649
+ ALTER TABLE public.plg_automations_enrollments ENABLE ROW LEVEL SECURITY;
2650
+ ALTER TABLE public.plg_automations_enrollments FORCE ROW LEVEL SECURITY;
2651
+
2652
+ DROP POLICY IF EXISTS plg_automations_flows_authz_select ON public.plg_automations_flows;
2653
+ CREATE POLICY plg_automations_flows_authz_select ON public.plg_automations_flows
2654
+ FOR SELECT TO authenticated USING (
2655
+ tenant_id = (SELECT app.current_tenant_id())
2656
+ AND (SELECT app.has_permission('automations.read', NULL::uuid)));
2657
+
2658
+ DROP POLICY IF EXISTS plg_automations_flows_authz_insert ON public.plg_automations_flows;
2659
+ CREATE POLICY plg_automations_flows_authz_insert ON public.plg_automations_flows
2660
+ FOR INSERT TO authenticated WITH CHECK (
2661
+ tenant_id = (SELECT app.current_tenant_id())
2662
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
2663
+
2664
+ DROP POLICY IF EXISTS plg_automations_flows_authz_update ON public.plg_automations_flows;
2665
+ CREATE POLICY plg_automations_flows_authz_update ON public.plg_automations_flows
2666
+ FOR UPDATE TO authenticated USING (
2667
+ tenant_id = (SELECT app.current_tenant_id())
2668
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)))
2669
+ WITH CHECK (
2670
+ tenant_id = (SELECT app.current_tenant_id())
2671
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
2672
+
2673
+ DROP POLICY IF EXISTS plg_automations_flows_authz_delete ON public.plg_automations_flows;
2674
+ CREATE POLICY plg_automations_flows_authz_delete ON public.plg_automations_flows
2675
+ FOR DELETE TO authenticated USING (
2676
+ tenant_id = (SELECT app.current_tenant_id())
2677
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
2678
+
2679
+ DROP POLICY IF EXISTS plg_automations_flow_steps_authz_select ON public.plg_automations_flow_steps;
2680
+ CREATE POLICY plg_automations_flow_steps_authz_select ON public.plg_automations_flow_steps
2681
+ FOR SELECT TO authenticated USING (
2682
+ tenant_id = (SELECT app.current_tenant_id())
2683
+ AND (SELECT app.has_permission('automations.read', NULL::uuid)));
2684
+
2685
+ DROP POLICY IF EXISTS plg_automations_flow_steps_authz_insert ON public.plg_automations_flow_steps;
2686
+ -- The parent flow is checked, not just the stamped tenant. A tenant-only
2687
+ -- WITH CHECK lets a caller stamp their OWN tenant_id on a step and hang it off
2688
+ -- somebody else's flow \u2014 and the engine looks steps up by flow_id alone, so the
2689
+ -- injected step runs in that tenant's cadence.
2690
+ CREATE POLICY plg_automations_flow_steps_authz_insert ON public.plg_automations_flow_steps
2691
+ FOR INSERT TO authenticated WITH CHECK (
2692
+ tenant_id = (SELECT app.current_tenant_id())
2693
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid))
2694
+ AND EXISTS (SELECT 1 FROM public.plg_automations_flows f
2695
+ WHERE f.id = flow_id AND f.tenant_id = (SELECT app.current_tenant_id())));
2696
+
2697
+ DROP POLICY IF EXISTS plg_automations_flow_steps_authz_update ON public.plg_automations_flow_steps;
2698
+ CREATE POLICY plg_automations_flow_steps_authz_update ON public.plg_automations_flow_steps
2699
+ FOR UPDATE TO authenticated USING (
2700
+ tenant_id = (SELECT app.current_tenant_id())
2701
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)))
2702
+ WITH CHECK (
2703
+ tenant_id = (SELECT app.current_tenant_id())
2704
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
2705
+
2706
+ DROP POLICY IF EXISTS plg_automations_flow_steps_authz_delete ON public.plg_automations_flow_steps;
2707
+ CREATE POLICY plg_automations_flow_steps_authz_delete ON public.plg_automations_flow_steps
2708
+ FOR DELETE TO authenticated USING (
2709
+ tenant_id = (SELECT app.current_tenant_id())
2710
+ AND (SELECT app.has_permission('automations.edit', NULL::uuid)));
2711
+
2712
+ -- Enrolments are READ-ONLY to the operator. They are written by the engine, and
2713
+ -- a hand-edited step pointer is a cadence nobody can explain afterwards.
2714
+ -- Leaving a flow is \`automations_flow_exit\`, not an UPDATE.
2715
+ DROP POLICY IF EXISTS plg_automations_enrollments_authz_select ON public.plg_automations_enrollments;
2716
+ CREATE POLICY plg_automations_enrollments_authz_select ON public.plg_automations_enrollments
2717
+ FOR SELECT TO authenticated USING (
2718
+ tenant_id = (SELECT app.current_tenant_id())
2719
+ AND (SELECT app.has_permission('automations.read', NULL::uuid)));
2720
+
2721
+ GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_automations_flows TO authenticated;
2722
+ GRANT ALL ON public.plg_automations_flows TO service_role;
2723
+ GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_automations_flow_steps TO authenticated;
2724
+ GRANT ALL ON public.plg_automations_flow_steps TO service_role;
2725
+ GRANT SELECT ON public.plg_automations_enrollments TO authenticated;
2726
+ GRANT ALL ON public.plg_automations_enrollments TO service_role;
2727
+
2728
+ INSERT INTO app.scaffold_registry
2729
+ (table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)
2730
+ VALUES
2731
+ ('public', 'plg_automations_flows', 'automations.flow', 'automations', false, 'enforce', ARRAY[]::text[], false, 'unit_optional', false),
2732
+ ('public', 'plg_automations_flow_steps', 'automations.flow_step', 'automations', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),
2733
+ ('public', 'plg_automations_enrollments', 'automations.enrollment', 'automations', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)
2734
+ ON CONFLICT DO NOTHING;
2735
+
2736
+ -- \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
2737
+
2738
+ -- Put somebody into a flow. Returns the enrolment, or NULL when the flow is
2739
+ -- inactive, has no steps, or the person is already in it.
2740
+ CREATE OR REPLACE FUNCTION public.automations_flow_enroll(
2741
+ p_tenant_id uuid, p_flow_id uuid, p_person_id uuid,
2742
+ p_subject_type text DEFAULT NULL, p_subject_id uuid DEFAULT NULL
2743
+ ) RETURNS uuid
2744
+ LANGUAGE plpgsql SECURITY DEFINER
2745
+ SET search_path TO ''
2746
+ AS $$
2747
+ DECLARE v_first record; v_id uuid;
2748
+ BEGIN
2749
+ SELECT s.position, s.delay_minutes INTO v_first
2750
+ FROM public.plg_automations_flow_steps s
2751
+ JOIN public.plg_automations_flows f ON f.id = s.flow_id
2752
+ WHERE s.flow_id = p_flow_id AND f.tenant_id = p_tenant_id AND f.is_active
2753
+ ORDER BY s.position
2754
+ LIMIT 1;
2755
+
2756
+ -- An inactive flow, or one with no steps, enrols nobody. Silently: this is
2757
+ -- called from an event handler, and raising would fail the whole delivery.
2758
+ IF v_first.position IS NULL THEN RETURN NULL; END IF;
2759
+
2760
+ INSERT INTO public.plg_automations_enrollments
2761
+ (tenant_id, flow_id, person_id, subject_type, subject_id, current_position, next_run_at)
2762
+ VALUES
2763
+ (p_tenant_id, p_flow_id, p_person_id, p_subject_type, p_subject_id,
2764
+ v_first.position, now() + make_interval(mins => v_first.delay_minutes))
2765
+ ON CONFLICT DO NOTHING
2766
+ RETURNING id INTO v_id;
2767
+
2768
+ RETURN v_id;
2769
+ END $$;
2770
+
2771
+ -- Take somebody out of every flow they are in. The reason is kept, because
2772
+ -- "left because they replied" and "left because the deal was lost" are the two
2773
+ -- halves of whether a cadence works.
2774
+ CREATE OR REPLACE FUNCTION public.automations_flow_exit(
2775
+ p_tenant_id uuid, p_person_id uuid, p_reason text, p_flow_ids uuid[] DEFAULT NULL
2776
+ ) RETURNS integer
2777
+ LANGUAGE plpgsql SECURITY DEFINER
2778
+ SET search_path TO ''
2779
+ AS $$
2780
+ DECLARE v_n integer; v_gone uuid[];
2781
+ BEGIN
2782
+ -- SCOPED TO THE FLOWS THAT ASKED. \`p_flow_ids\` NULL still means "every flow",
2783
+ -- which is what a manual "take this person out" wants; the event handler
2784
+ -- passes the flows whose own \`exit_events\` name the fact.
2785
+ --
2786
+ -- Without the scope, one flow declaring \`crm.deal_won\` pulled the person out
2787
+ -- of EVERY flow they were in and cancelled every queued step \u2014 including a
2788
+ -- flow that declared no exits at all, whose comment says it "only ends by
2789
+ -- running out of steps". Flow-level exit_events were meaningless the moment a
2790
+ -- second flow existed.
2791
+ WITH gone AS (
2792
+ UPDATE public.plg_automations_enrollments
2793
+ SET status = 'exited', exited_at = now(), exit_reason = p_reason,
2794
+ current_position = NULL, updated_at = now()
2795
+ WHERE tenant_id = p_tenant_id AND person_id = p_person_id AND status = 'active'
2796
+ AND (p_flow_ids IS NULL OR flow_id = ANY (p_flow_ids))
2797
+ RETURNING id
2798
+ )
2799
+ SELECT count(*)::integer, array_agg(id) INTO v_n, v_gone FROM gone;
2800
+
2801
+ -- A step already in the queue but not yet sent must not go out after the
2802
+ -- person left. \`cancelled\` was in the status CHECK from the beginning and
2803
+ -- nothing ever wrote it; this is what it was for.
2804
+ --
2805
+ -- Keyed by the ENROLMENTS that just left, not by \`flow:%\` \u2014 the wide pattern
2806
+ -- cancelled the pending steps of flows the person is still in.
2807
+ IF v_n > 0 AND to_regclass('public.plg_notifications_queue') IS NOT NULL THEN
2808
+ UPDATE public.plg_notifications_queue q
2809
+ SET status = 'cancelled', last_error = 'left the flow: ' || p_reason
2810
+ WHERE q.tenant_id = p_tenant_id
2811
+ AND q.person_id = p_person_id
2812
+ AND q.status = 'pending'
2813
+ AND split_part(q.dedupe_key, ':', 1) = 'flow'
2814
+ AND split_part(q.dedupe_key, ':', 2) = ANY (SELECT unnest(v_gone)::text);
2815
+ END IF;
2816
+
2817
+ RETURN v_n;
2818
+ END $$;
2819
+
2820
+ -- The tick. Claims due enrolments, runs ONE step each, moves the pointer.
2821
+ CREATE OR REPLACE FUNCTION public.automations_flows_run_due(p_limit integer DEFAULT 50)
2822
+ RETURNS jsonb
2823
+ LANGUAGE plpgsql SECURITY DEFINER
2824
+ SET search_path TO ''
2825
+ AS $$
2826
+ DECLARE
2827
+ e record; v_step record; v_next record; v_error text;
2828
+ v_ran integer := 0; v_done integer := 0; v_failed integer := 0;
2829
+ BEGIN
2830
+ -- JOINED to the flow, and \`f.is_active\` checked here rather than only in
2831
+ -- \`automations_flow_enroll\`. Switching a flow off used to stop new entrants
2832
+ -- and nothing else: everybody already mid-cadence kept receiving messages
2833
+ -- from a flow the operator had just turned off, which is the opposite of what
2834
+ -- the switch promises.
2835
+ FOR e IN
2836
+ SELECT en.* FROM public.plg_automations_enrollments en
2837
+ JOIN public.plg_automations_flows f ON f.id = en.flow_id AND f.is_active
2838
+ WHERE en.status = 'active' AND en.next_run_at <= now()
2839
+ ORDER BY en.next_run_at
2840
+ LIMIT greatest(p_limit, 0)
2841
+ FOR UPDATE OF en SKIP LOCKED
2842
+ LOOP
2843
+ SELECT * INTO v_step FROM public.plg_automations_flow_steps s
2844
+ WHERE s.flow_id = e.flow_id AND s.position = e.current_position;
2845
+
2846
+ -- The step was deleted while somebody stood on it. Move on rather than
2847
+ -- spinning on a pointer that will never resolve.
2848
+ IF v_step.id IS NULL THEN
2849
+ SELECT * INTO v_next FROM public.plg_automations_flow_steps s
2850
+ WHERE s.flow_id = e.flow_id AND s.position > coalesce(e.current_position, -1)
2851
+ ORDER BY s.position LIMIT 1;
2852
+ ELSE
2853
+ BEGIN
2854
+ IF v_step.kind = 'message' THEN
2855
+ PERFORM public.notifications_enqueue(
2856
+ e.tenant_id, v_step.template_key, e.person_id,
2857
+ jsonb_build_object('flow_id', e.flow_id, 'enrollment_id', e.id, 'step', v_step.position),
2858
+ 'flow:' || e.id::text || ':' || v_step.position::text,
2859
+ now(),
2860
+ v_step.channel
2861
+ );
2862
+ ELSIF v_step.kind = 'task' AND to_regclass('public.tasks') IS NOT NULL THEN
2863
+ -- \`tasks_source_uniq (tenant_id, source, source_key)\` makes this
2864
+ -- idempotent for free \u2014 the same step cannot raise two tasks.
2865
+ INSERT INTO public.tasks
2866
+ (tenant_id, title, description, status, due_date, source, source_key)
2867
+ VALUES
2868
+ (e.tenant_id, v_step.task_title,
2869
+ 'Automation flow step ' || v_step.position::text,
2870
+ 'todo',
2871
+ CASE WHEN v_step.task_due_days IS NOT NULL
2872
+ THEN (now() + make_interval(days => v_step.task_due_days))::date END,
2873
+ 'automation:flow', e.id::text || ':' || v_step.position::text)
2874
+ ON CONFLICT DO NOTHING;
2875
+ END IF;
2876
+ v_ran := v_ran + 1;
2877
+ EXCEPTION WHEN OTHERS THEN
2878
+ -- One bad step must not stop the tick for everybody else, so the
2879
+ -- enrolment still leaves this step: a template that no longer exists
2880
+ -- would otherwise wedge the person forever.
2881
+ --
2882
+ -- But it does NOT read as a finished cadence. The first cut let the
2883
+ -- loop fall through to \`completed\`, and because a failed step never
2884
+ -- produces a queue row, \`v_automations_flow_steps\` \u2014 which counts queue
2885
+ -- statuses \u2014 could not show it either. The screen built to answer
2886
+ -- "where do people stop" reported the person as having finished.
2887
+ v_failed := v_failed + 1;
2888
+ v_error := SQLERRM;
2889
+ RAISE NOTICE 'automations_flows_run_due: step % of enrolment % failed (%)',
2890
+ v_step.position, e.id, SQLERRM;
2891
+ END;
2892
+
2893
+ SELECT * INTO v_next FROM public.plg_automations_flow_steps s
2894
+ WHERE s.flow_id = e.flow_id AND s.position > v_step.position
2895
+ ORDER BY s.position LIMIT 1;
2896
+ END IF;
2897
+
2898
+ IF v_next.id IS NULL THEN
2899
+ UPDATE public.plg_automations_enrollments
2900
+ SET status = 'completed', current_position = NULL,
2901
+ exited_at = now(), updated_at = now(),
2902
+ -- A cadence that ended on a step that could not run did not
2903
+ -- finish; saying so is the difference between "nobody answers the
2904
+ -- third message" and "the third message never left".
2905
+ exit_reason = CASE WHEN v_error IS NOT NULL
2906
+ THEN 'last step failed: ' || v_error END
2907
+ WHERE id = e.id;
2908
+ v_done := v_done + 1;
2909
+ ELSE
2910
+ UPDATE public.plg_automations_enrollments
2911
+ SET current_position = v_next.position,
2912
+ next_run_at = now() + make_interval(mins => v_next.delay_minutes),
2913
+ updated_at = now()
2914
+ WHERE id = e.id;
2915
+ END IF;
2916
+
2917
+ v_next := NULL; v_step := NULL; v_error := NULL;
2918
+ END LOOP;
2919
+
2920
+ RETURN jsonb_build_object('steps_ran', v_ran, 'completed', v_done, 'failed', v_failed);
2921
+ END $$;
2922
+
2923
+ REVOKE ALL ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) FROM PUBLIC;
2924
+ GRANT EXECUTE ON FUNCTION public.automations_flow_enroll(uuid, uuid, uuid, text, uuid) TO service_role;
2925
+ REVOKE ALL ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) FROM PUBLIC;
2926
+ GRANT EXECUTE ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) TO authenticated;
2927
+ GRANT EXECUTE ON FUNCTION public.automations_flow_exit(uuid, uuid, text, uuid[]) TO service_role;
2928
+ REVOKE ALL ON FUNCTION public.automations_flows_run_due(integer) FROM PUBLIC;
2929
+ GRANT EXECUTE ON FUNCTION public.automations_flows_run_due(integer) TO service_role;
2930
+
2931
+ -- \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
2932
+
2933
+ -- Who the event is about.
2934
+ --
2935
+ -- \`consume_event_log\` calls a handler with \`to_jsonb(v_event)\` \u2014 the whole
2936
+ -- \`event_log\` ROW. So \`tenant_id\`, \`event_key\`, \`subject_type\` and \`subject_id\`
2937
+ -- are at the top level and everything the emitter chose to send is nested under
2938
+ -- \`payload\`. The first cut read \`person_id\` at the top level, where it never is:
2939
+ -- every delivery answered "payload carries no tenant, person or event", was
2940
+ -- marked DELIVERED, and the cadence enrolled nobody, ever, with nothing
2941
+ -- reporting it.
2942
+ --
2943
+ -- \`subject_id\` first, because that is the convention the shipped handlers use
2944
+ -- (\`plg_notifications_on_fulfillment_completed\` reads exactly that), and it is
2945
+ -- \`text\` on the row. The payload fallbacks are for emitters that name the person
2946
+ -- there instead.
2947
+ CREATE OR REPLACE FUNCTION public.automations_event_person(p_event jsonb)
2948
+ RETURNS uuid
2949
+ LANGUAGE sql IMMUTABLE
2950
+ SET search_path TO ''
2951
+ AS $$
2952
+ SELECT nullif(coalesce(
2953
+ CASE WHEN p_event ->> 'subject_type' IN ('lead', 'person', 'contact')
2954
+ THEN p_event ->> 'subject_id' END,
2955
+ p_event -> 'payload' ->> 'person_id',
2956
+ p_event -> 'payload' ->> 'lead_id',
2957
+ p_event -> 'payload' ->> 'contact_id',
2958
+ p_event ->> 'person_id',
2959
+ p_event ->> 'lead_id'
2960
+ ), '')::uuid
2961
+ $$;
2962
+
2963
+ REVOKE ALL ON FUNCTION public.automations_event_person(jsonb) FROM PUBLIC;
2964
+ GRANT EXECUTE ON FUNCTION public.automations_event_person(jsonb) TO service_role;
2965
+
2966
+ -- Enrol on the flow's entry event. The payload names the person; a fact that
2967
+ -- does not carry one cannot start a cadence.
2968
+ CREATE OR REPLACE FUNCTION public.plg_automations_on_entry_event(p_event jsonb)
2969
+ RETURNS jsonb
2970
+ LANGUAGE plpgsql SECURITY DEFINER
2971
+ SET search_path TO ''
2972
+ AS $$
2973
+ DECLARE
2974
+ v_tenant uuid := nullif(p_event ->> 'tenant_id', '')::uuid;
2975
+ v_event text := p_event ->> 'event_key';
2976
+ v_person uuid := public.automations_event_person(p_event);
2977
+ f record; v_n integer := 0;
2978
+ BEGIN
2979
+ IF v_tenant IS NULL OR v_person IS NULL OR v_event IS NULL THEN
2980
+ RETURN jsonb_build_object('enrolled', 0, 'reason', 'event carries no tenant, person or key');
2981
+ END IF;
2982
+
2983
+ FOR f IN SELECT id FROM public.plg_automations_flows
2984
+ WHERE tenant_id = v_tenant AND entry_event = v_event AND is_active
2985
+ LOOP
2986
+ IF public.automations_flow_enroll(
2987
+ v_tenant, f.id, v_person,
2988
+ p_event ->> 'subject_type', nullif(p_event ->> 'subject_id', '')::uuid) IS NOT NULL THEN
2989
+ v_n := v_n + 1;
2990
+ END IF;
2991
+ END LOOP;
2992
+
2993
+ RETURN jsonb_build_object('enrolled', v_n);
2994
+ END $$;
2995
+
2996
+ -- Leave the flows whose own \`exit_events\` name this fact.
2997
+ CREATE OR REPLACE FUNCTION public.plg_automations_on_exit_event(p_event jsonb)
2998
+ RETURNS jsonb
2999
+ LANGUAGE plpgsql SECURITY DEFINER
3000
+ SET search_path TO ''
3001
+ AS $$
3002
+ DECLARE
3003
+ v_tenant uuid := nullif(p_event ->> 'tenant_id', '')::uuid;
3004
+ v_event text := p_event ->> 'event_key';
3005
+ v_person uuid := public.automations_event_person(p_event);
3006
+ v_flows uuid[]; v_n integer := 0;
3007
+ BEGIN
3008
+ IF v_tenant IS NULL OR v_person IS NULL OR v_event IS NULL THEN
3009
+ RETURN jsonb_build_object('exited', 0, 'reason', 'event carries no tenant, person or key');
3010
+ END IF;
3011
+
3012
+ SELECT array_agg(id) INTO v_flows
3013
+ FROM public.plg_automations_flows
3014
+ WHERE tenant_id = v_tenant AND is_active AND v_event = ANY (exit_events);
3015
+
3016
+ IF v_flows IS NOT NULL THEN
3017
+ v_n := public.automations_flow_exit(v_tenant, v_person, v_event, v_flows);
3018
+ END IF;
3019
+
3020
+ RETURN jsonb_build_object('exited', v_n);
3021
+ END $$;
3022
+
3023
+ REVOKE ALL ON FUNCTION public.plg_automations_on_entry_event(jsonb) FROM PUBLIC;
3024
+ GRANT EXECUTE ON FUNCTION public.plg_automations_on_entry_event(jsonb) TO service_role;
3025
+ REVOKE ALL ON FUNCTION public.plg_automations_on_exit_event(jsonb) FROM PUBLIC;
3026
+ GRANT EXECUTE ON FUNCTION public.plg_automations_on_exit_event(jsonb) TO service_role;
3027
+
3028
+ -- \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
3029
+
3030
+ -- The manifest DECLARES the reaction; this is what makes the event log call it.
3031
+ -- Both handlers on every CRM fact, because which fact opens a cadence and which
3032
+ -- closes it is the operator's choice: the handler looks the flow up and returns
3033
+ -- immediately when no flow in that tenant names the event.
3034
+ -- Written out one call per line rather than looped over an array. The loop was
3035
+ -- shorter and \`check-event-contract\` could not read it: its registration parser
3036
+ -- matches literal arguments, so a FOREACH registering fourteen subscriptions
3037
+ -- looked like zero. Same lesson as the manifest side \u2014 the gate reads source,
3038
+ -- so the source has to say it.
3039
+ SELECT public.register_event_subscription('automations', 'crm.lead_created', 'plg_automations_on_entry_event',
3040
+ 'Enrol into flows whose entry event is crm.lead_created', 5);
3041
+ SELECT public.register_event_subscription('automations', 'crm.lead_created', 'plg_automations_on_exit_event',
3042
+ 'Leave flows that exit on crm.lead_created', 5);
3043
+ SELECT public.register_event_subscription('automations', 'crm.stage_changed', 'plg_automations_on_entry_event',
3044
+ 'Enrol into flows whose entry event is crm.stage_changed', 5);
3045
+ SELECT public.register_event_subscription('automations', 'crm.stage_changed', 'plg_automations_on_exit_event',
3046
+ 'Leave flows that exit on crm.stage_changed', 5);
3047
+ SELECT public.register_event_subscription('automations', 'crm.quote_sent', 'plg_automations_on_entry_event',
3048
+ 'Enrol into flows whose entry event is crm.quote_sent', 5);
3049
+ SELECT public.register_event_subscription('automations', 'crm.quote_sent', 'plg_automations_on_exit_event',
3050
+ 'Leave flows that exit on crm.quote_sent', 5);
3051
+ SELECT public.register_event_subscription('automations', 'crm.quote_approved', 'plg_automations_on_entry_event',
3052
+ 'Enrol into flows whose entry event is crm.quote_approved', 5);
3053
+ SELECT public.register_event_subscription('automations', 'crm.quote_approved', 'plg_automations_on_exit_event',
3054
+ 'Leave flows that exit on crm.quote_approved', 5);
3055
+ SELECT public.register_event_subscription('automations', 'crm.deal_won', 'plg_automations_on_entry_event',
3056
+ 'Enrol into flows whose entry event is crm.deal_won', 5);
3057
+ SELECT public.register_event_subscription('automations', 'crm.deal_won', 'plg_automations_on_exit_event',
3058
+ 'Leave flows that exit on crm.deal_won', 5);
3059
+ SELECT public.register_event_subscription('automations', 'crm.deal_lost', 'plg_automations_on_entry_event',
3060
+ 'Enrol into flows whose entry event is crm.deal_lost', 5);
3061
+ SELECT public.register_event_subscription('automations', 'crm.deal_lost', 'plg_automations_on_exit_event',
3062
+ 'Leave flows that exit on crm.deal_lost', 5);
3063
+ SELECT public.register_event_subscription('automations', 'crm.deal_idle', 'plg_automations_on_entry_event',
3064
+ 'Enrol into flows whose entry event is crm.deal_idle', 5);
3065
+ SELECT public.register_event_subscription('automations', 'crm.deal_idle', 'plg_automations_on_exit_event',
3066
+ 'Leave flows that exit on crm.deal_idle', 5);
3067
+
3068
+ -- \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
3069
+
3070
+ -- Per-step numbers, which is the question a cadence is judged by: where do
3071
+ -- people stop. Aggregating per FLOW would hide that the third message is the
3072
+ -- one nobody answers.
3073
+ CREATE OR REPLACE VIEW public.v_automations_flow_steps WITH (security_invoker='true') AS
3074
+ SELECT
3075
+ s.tenant_id, s.flow_id, s.id AS step_id, s.position, s.kind,
3076
+ s.template_key, s.channel, s.delay_minutes, s.task_title,
3077
+ count(q.id) FILTER (WHERE q.id IS NOT NULL) AS queued,
3078
+ count(q.id) FILTER (WHERE q.status = 'sent') AS sent,
3079
+ count(q.id) FILTER (WHERE q.status = 'blocked') AS blocked,
3080
+ count(q.id) FILTER (WHERE q.status = 'failed') AS failed,
3081
+ count(q.id) FILTER (WHERE q.status = 'cancelled') AS cancelled
3082
+ FROM public.plg_automations_flow_steps s
3083
+ LEFT JOIN public.plg_automations_enrollments e ON e.flow_id = s.flow_id
3084
+ LEFT JOIN public.plg_notifications_queue q
3085
+ ON q.dedupe_key = 'flow:' || e.id::text || ':' || s.position::text
3086
+ GROUP BY s.tenant_id, s.flow_id, s.id, s.position, s.kind,
3087
+ s.template_key, s.channel, s.delay_minutes, s.task_title;
3088
+
3089
+ GRANT SELECT ON public.v_automations_flow_steps TO authenticated;
3090
+ GRANT SELECT ON public.v_automations_flow_steps TO service_role;
3091
+ `;
3092
+ var MIGRATIONS = [
3093
+ { id: "000_baseline", sql: MIGRATION_000_BASELINE },
3094
+ { id: "001_the_flow_has_steps", sql: MIGRATION_001_THE_FLOW_HAS_STEPS }
3095
+ ];
1530
3096
 
1531
3097
  // src/index.ts
1532
3098
  function createAutomationsPlugin(options) {
1533
3099
  const connection = resolveFayzAgentConnection();
1534
- const store = options?.store ?? (connection ? createFayzTemplateStore(connection) : createSupabaseTemplateStore());
3100
+ const store2 = options?.store ?? (connection ? createFayzTemplateStore(connection) : createSupabaseTemplateStore());
1535
3101
  startEventLog();
1536
3102
  const inSettings = options?.placement === "settings";
1537
- const ListPage = () => React4__default.createElement(AutomationsList, { store });
3103
+ const ListPage = () => React4__default.createElement(AutomationsList, { store: store2 });
1538
3104
  ListPage.displayName = "AutomationsList";
1539
- const SettingsListPage = () => React4__default.createElement(AutomationsList, { store, variant: "panel", basePath: "/settings/automations" });
3105
+ const SettingsListPage = () => React4__default.createElement(AutomationsList, { store: store2, variant: "panel", basePath: "/settings/automations" });
1540
3106
  SettingsListPage.displayName = "AutomationsSettings";
1541
3107
  const RailDetail = ({ params, onClose }) => React4__default.createElement(AutomationDetailPage, {
1542
3108
  eventKey: params.eventKey,
1543
3109
  channel: params.channel,
1544
- store,
3110
+ store: store2,
1545
3111
  backTo: inSettings ? "/settings/automations" : "/automations",
1546
3112
  embedded: true,
1547
3113
  onDone: onClose
@@ -1569,7 +3135,19 @@ function createAutomationsPlugin(options) {
1569
3135
  icon: "Zap",
1570
3136
  permission: READ,
1571
3137
  indexChild: false
1572
- }
3138
+ },
3139
+ // The flows screen had a route and nothing pointing at it — no nav entry,
3140
+ // no link, no tab. `git grep automations/flows` found the registration
3141
+ // and the changeset, and nothing else.
3142
+ ...inSettings ? [] : [{
3143
+ section: options?.navSection ?? "main",
3144
+ position: (options?.navPosition ?? 6) + 0.1,
3145
+ label: "Cad\xEAncias",
3146
+ route: "/automations/flows",
3147
+ icon: "Repeat",
3148
+ permission: READ,
3149
+ indexChild: false
3150
+ }]
1573
3151
  ],
1574
3152
  // The SAME list, served inside settings — not a second screen.
1575
3153
  settings: inSettings ? [
@@ -1582,12 +3160,61 @@ function createAutomationsPlugin(options) {
1582
3160
  // mesmo componente: a shell colapsa '/x' e '/x/*' na mesma chave, então a
1583
3161
  // página não remonta ao abrir o painel (ver AdminShell.routeKey). Um
1584
3162
  // segundo componente aqui traria de volta a troca de tela.
3163
+ // Flows are their OWN route, not a tab of the list. A one-step automation
3164
+ // and a cadence answer different questions — "does the order confirmation
3165
+ // go out" versus "where do people stop" — and the wildcard above already
3166
+ // owns the right rail, so a tab here would fight it for the same URL.
3167
+ { path: "/automations/flows", component: FlowsPage, permission: READ },
1585
3168
  { path: "/automations/*", component: ListPage, permission: READ }
1586
3169
  ],
3170
+ // A flow names its own entry and exit events, but a SUBSCRIPTION is a row:
3171
+ // static, written at install time. So both handlers listen to the whole CRM
3172
+ // fact catalogue and each one decides whether any flow cares — the handler
3173
+ // is a lookup against `plg_automations_flows`, and a tenant with no flow on
3174
+ // that event does one indexed read and returns.
3175
+ //
3176
+ // Both handlers on every event on purpose: which facts open a cadence and
3177
+ // which close it is the operator's choice, not ours. A house may well start
3178
+ // a win-back flow on `crm.deal_lost`.
3179
+ //
3180
+ // Written out one by one rather than generated from CADENCE_FACTS. The
3181
+ // generated form read better and was invisible to `check-event-contract`,
3182
+ // whose regex needs a literal `subscribesTo: [ … ]` with literal event and
3183
+ // handler strings — so fourteen subscriptions that nothing registered
3184
+ // passed the gate in silence. A contract a checker cannot read is not a
3185
+ // contract.
3186
+ subscribesTo: [
3187
+ { event: "crm.lead_created", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by a new lead", maxAttempts: 5 },
3188
+ { event: "crm.lead_created", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on a new lead", maxAttempts: 5 },
3189
+ { event: "crm.stage_changed", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by a stage change", maxAttempts: 5 },
3190
+ { event: "crm.stage_changed", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on a stage change", maxAttempts: 5 },
3191
+ { event: "crm.quote_sent", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by a sent quote", maxAttempts: 5 },
3192
+ { event: "crm.quote_sent", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on a sent quote", maxAttempts: 5 },
3193
+ { event: "crm.quote_approved", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by an approved quote", maxAttempts: 5 },
3194
+ { event: "crm.quote_approved", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on an approved quote", maxAttempts: 5 },
3195
+ { event: "crm.deal_won", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by a won deal", maxAttempts: 5 },
3196
+ { event: "crm.deal_won", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on a won deal", maxAttempts: 5 },
3197
+ { event: "crm.deal_lost", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by a lost deal", maxAttempts: 5 },
3198
+ { event: "crm.deal_lost", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on a lost deal", maxAttempts: 5 },
3199
+ { event: "crm.deal_idle", handler: "plg_automations_on_entry_event", description: "Enrol into flows entered by an idle deal", maxAttempts: 5 },
3200
+ { event: "crm.deal_idle", handler: "plg_automations_on_exit_event", description: "Leave flows that exit on an idle deal", maxAttempts: 5 }
3201
+ ],
3202
+ // The barrel an app installing this plugin applies. Without it the tables
3203
+ // and functions below simply do not exist there: `chain.json` provisions a
3204
+ // CLUSTER, and the manifest is what provisions an app — this plugin had
3205
+ // neither a `migrations` key nor a barrel to point it at, so fourteen
3206
+ // subscriptions and a whole screen shipped over nothing.
3207
+ migrations: MIGRATIONS.map((m) => ({
3208
+ id: `automations-${m.id}`,
3209
+ version: "1.0.0",
3210
+ sql: m.sql,
3211
+ description: m.id
3212
+ })),
3213
+ locales: automationsLocales,
1587
3214
  widgets: []
1588
3215
  };
1589
3216
  }
1590
3217
 
1591
- export { PROVIDER_TEMPLATES_TABLE, createAutomationsPlugin, createFayzTemplateStore, createSupabaseTemplateStore, loadProviderTemplates, providerApprovalFor, providerTemplateFor };
3218
+ export { FlowsPage as CadenceFlowsSurface, PROVIDER_TEMPLATES_TABLE, createAutomationsPlugin, createFayzTemplateStore, createSupabaseTemplateStore, loadProviderTemplates, providerApprovalFor, providerTemplateFor };
1592
3219
  //# sourceMappingURL=index.js.map
1593
3220
  //# sourceMappingURL=index.js.map