@fayz-ai/plugin-automations 0.15.28 → 0.15.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AutomationDetailPage-UHY7KHQK.js +4 -0
- package/dist/AutomationDetailPage-UHY7KHQK.js.map +1 -0
- package/dist/AutomationsList-3UTTQSIX.js +478 -0
- package/dist/AutomationsList-3UTTQSIX.js.map +1 -0
- package/dist/FlowsPage-6SUXT2LP.js +509 -0
- package/dist/FlowsPage-6SUXT2LP.js.map +1 -0
- package/dist/chunk-63YAGMWV.js +258 -0
- package/dist/chunk-63YAGMWV.js.map +1 -0
- package/dist/chunk-TCSHZ3VF.js +764 -0
- package/dist/chunk-TCSHZ3VF.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -2974
- package/dist/index.js.map +1 -1
- package/dist/migrations/main.browser.js +9 -0
- package/dist/migrations/main.browser.js.map +1 -0
- package/dist/migrations/main.js +998 -0
- package/dist/migrations/main.js.map +1 -0
- package/dist/views/AutomationsList.d.ts.map +1 -1
- package/package.json +10 -4
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { getFayzSupabaseClientOptional } from '@fayz-ai/admin';
|
|
2
|
+
import { getSupabaseClientOptional, getMessageDefaults } from '@fayz-ai/core';
|
|
3
|
+
import { createFayzAutomationsClient, FayzAutomationsError } from '@fayz-ai/sdk/automations';
|
|
4
|
+
import React from 'react';
|
|
5
|
+
import { Badge } from '@fayz-ai/ui';
|
|
6
|
+
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
7
|
+
|
|
8
|
+
// src/data/fayz.ts
|
|
9
|
+
function toTemplate(automation) {
|
|
10
|
+
const eventKey = automation.triggerConfig?.eventKey;
|
|
11
|
+
if (!eventKey) return null;
|
|
12
|
+
const action = automation.actions?.[0];
|
|
13
|
+
return {
|
|
14
|
+
id: automation.id,
|
|
15
|
+
tenantId: automation.tenantId ?? "",
|
|
16
|
+
eventKey,
|
|
17
|
+
channel: automation.triggerConfig.sourceChannel ?? "email",
|
|
18
|
+
enabled: automation.enabled,
|
|
19
|
+
// Empty and absent mean the same — "no customisation", the catalogue default.
|
|
20
|
+
subject: action?.config?.subject || null,
|
|
21
|
+
body: action?.config?.body || null,
|
|
22
|
+
// The automation name belongs to the platform, not a user rename: the
|
|
23
|
+
// catalogue title still owns the screen.
|
|
24
|
+
name: null,
|
|
25
|
+
// The platform's automation action carries a subject and a body and nothing
|
|
26
|
+
// else, so there is nowhere for a customised button to live yet. NULL, not
|
|
27
|
+
// [], because the catalogue default is what still applies — an empty list
|
|
28
|
+
// would read as "this tenant removed the buttons".
|
|
29
|
+
actions: null,
|
|
30
|
+
updatedAt: automation.updatedAt
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function catalogDefaultEnabled(eventKey, channel) {
|
|
34
|
+
const def = getMessageDefaults().find((d) => d.eventKey === eventKey);
|
|
35
|
+
return def?.defaultEnabled?.[channel] ?? false;
|
|
36
|
+
}
|
|
37
|
+
async function defaultSessionToken() {
|
|
38
|
+
const session = (await getFayzSupabaseClientOptional()?.auth.getSession())?.data.session;
|
|
39
|
+
return session?.access_token ?? null;
|
|
40
|
+
}
|
|
41
|
+
function createFayzTemplateStore(connection, deps = {}) {
|
|
42
|
+
const client = deps.client ?? createFayzAutomationsClient({
|
|
43
|
+
baseUrl: connection.apiBaseUrl,
|
|
44
|
+
projectId: connection.projectId,
|
|
45
|
+
publishableKey: connection.publishableKey
|
|
46
|
+
});
|
|
47
|
+
const getSessionToken = deps.getSessionToken ?? defaultSessionToken;
|
|
48
|
+
const ids = /* @__PURE__ */ new Map();
|
|
49
|
+
const keyOf = (eventKey, channel) => `${eventKey}:${channel}`;
|
|
50
|
+
async function refresh(tenantId) {
|
|
51
|
+
const automations = await client.list({ tenantId });
|
|
52
|
+
ids.clear();
|
|
53
|
+
const rows = [];
|
|
54
|
+
for (const automation of automations) {
|
|
55
|
+
const row = toTemplate(automation);
|
|
56
|
+
if (!row) continue;
|
|
57
|
+
ids.set(keyOf(row.eventKey, row.channel), automation.id);
|
|
58
|
+
rows.push(row);
|
|
59
|
+
}
|
|
60
|
+
return rows;
|
|
61
|
+
}
|
|
62
|
+
const LIST_TTL_MS = 3e4;
|
|
63
|
+
let cache = null;
|
|
64
|
+
function invalidate() {
|
|
65
|
+
cache = null;
|
|
66
|
+
}
|
|
67
|
+
function load(tenantId) {
|
|
68
|
+
if (cache && cache.tenantId === tenantId && Date.now() - cache.at < LIST_TTL_MS) return cache.promise;
|
|
69
|
+
const promise = refresh(tenantId);
|
|
70
|
+
promise.catch(() => {
|
|
71
|
+
if (cache?.promise === promise) cache = null;
|
|
72
|
+
});
|
|
73
|
+
cache = { tenantId, at: Date.now(), promise };
|
|
74
|
+
return promise;
|
|
75
|
+
}
|
|
76
|
+
async function requireToken() {
|
|
77
|
+
const token = await getSessionToken();
|
|
78
|
+
if (!token) throw new Error("Sess\xE3o expirada \u2014 entre de novo.");
|
|
79
|
+
return token;
|
|
80
|
+
}
|
|
81
|
+
async function resolveId(eventKey, channel, tenantId) {
|
|
82
|
+
const key = keyOf(eventKey, channel);
|
|
83
|
+
if (!ids.has(key)) await load(tenantId);
|
|
84
|
+
return ids.get(key);
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
async list(tenantId) {
|
|
88
|
+
if (!tenantId) return [];
|
|
89
|
+
return load(tenantId);
|
|
90
|
+
},
|
|
91
|
+
async upsert(input, tenantId) {
|
|
92
|
+
if (!tenantId) throw new Error("@fayz-ai/plugin-automations: tenantId is required");
|
|
93
|
+
const appSessionToken = await requireToken();
|
|
94
|
+
const key = keyOf(input.eventKey, input.channel);
|
|
95
|
+
let id = await resolveId(input.eventKey, input.channel, tenantId);
|
|
96
|
+
if (!id) {
|
|
97
|
+
const action = {};
|
|
98
|
+
if (input.subject != null) action.subject = input.subject;
|
|
99
|
+
if (input.body != null) action.body = input.body;
|
|
100
|
+
try {
|
|
101
|
+
const created = await client.create({
|
|
102
|
+
tenantId,
|
|
103
|
+
appSessionToken,
|
|
104
|
+
eventKey: input.eventKey,
|
|
105
|
+
sourceChannel: input.channel,
|
|
106
|
+
// The platform has no "inherit from catalogue": materialise the default.
|
|
107
|
+
enabled: input.enabled ?? catalogDefaultEnabled(input.eventKey, input.channel),
|
|
108
|
+
...Object.keys(action).length ? { action } : {}
|
|
109
|
+
});
|
|
110
|
+
ids.set(key, created.id);
|
|
111
|
+
invalidate();
|
|
112
|
+
const row2 = toTemplate(created);
|
|
113
|
+
if (!row2) throw new Error("@fayz-ai/plugin-automations: platform did not round-trip eventKey");
|
|
114
|
+
return row2;
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (!(err instanceof FayzAutomationsError) || err.status !== 409) throw err;
|
|
117
|
+
invalidate();
|
|
118
|
+
await refresh(tenantId);
|
|
119
|
+
id = ids.get(key);
|
|
120
|
+
if (!id) throw err;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const updated = await client.update({
|
|
124
|
+
id,
|
|
125
|
+
tenantId,
|
|
126
|
+
appSessionToken,
|
|
127
|
+
// Only what was sent: omitting has to mean "leave it alone", as in the local store.
|
|
128
|
+
...typeof input.enabled === "boolean" ? { enabled: input.enabled } : {},
|
|
129
|
+
...input.subject !== void 0 || input.body !== void 0 ? {
|
|
130
|
+
action: {
|
|
131
|
+
...input.subject !== void 0 ? { subject: input.subject } : {},
|
|
132
|
+
...input.body !== void 0 ? { body: input.body } : {}
|
|
133
|
+
}
|
|
134
|
+
} : {}
|
|
135
|
+
});
|
|
136
|
+
invalidate();
|
|
137
|
+
const row = toTemplate(updated);
|
|
138
|
+
if (!row) throw new Error("@fayz-ai/plugin-automations: platform did not round-trip eventKey");
|
|
139
|
+
return row;
|
|
140
|
+
},
|
|
141
|
+
async reset(eventKey, channel, tenantId) {
|
|
142
|
+
if (!tenantId) return;
|
|
143
|
+
const id = await resolveId(eventKey, channel, tenantId);
|
|
144
|
+
if (!id) return;
|
|
145
|
+
const appSessionToken = await requireToken();
|
|
146
|
+
await client.update({ id, tenantId, appSessionToken, action: { subject: null, body: null } });
|
|
147
|
+
invalidate();
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
var cachedClient = null;
|
|
152
|
+
function getFayzAutomationsClient(connection) {
|
|
153
|
+
const key = `${connection.apiBaseUrl}|${connection.projectId}|${connection.publishableKey}`;
|
|
154
|
+
if (cachedClient?.key === key) return cachedClient.client;
|
|
155
|
+
const client = createFayzAutomationsClient({
|
|
156
|
+
baseUrl: connection.apiBaseUrl,
|
|
157
|
+
projectId: connection.projectId,
|
|
158
|
+
publishableKey: connection.publishableKey
|
|
159
|
+
});
|
|
160
|
+
cachedClient = { key, client };
|
|
161
|
+
return client;
|
|
162
|
+
}
|
|
163
|
+
var PROVIDER_TEMPLATES_TABLE = "plg_automations_provider_templates";
|
|
164
|
+
function rowToProviderTemplate(row) {
|
|
165
|
+
return {
|
|
166
|
+
id: row.id,
|
|
167
|
+
tenantId: row.tenant_id ?? null,
|
|
168
|
+
eventKey: row.event_key,
|
|
169
|
+
channel: row.channel ?? "whatsapp",
|
|
170
|
+
provider: row.provider ?? "tyxter",
|
|
171
|
+
templateName: row.template_name ?? "",
|
|
172
|
+
status: row.status ?? "draft",
|
|
173
|
+
rejectionReason: row.rejection_reason || null,
|
|
174
|
+
updatedAt: row.updated_at ?? row.created_at ?? null
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
async function loadProviderTemplates() {
|
|
178
|
+
const client = getSupabaseClientOptional();
|
|
179
|
+
if (!client) return [];
|
|
180
|
+
try {
|
|
181
|
+
const { data, error } = await client.from(PROVIDER_TEMPLATES_TABLE).select("*");
|
|
182
|
+
if (error) throw error;
|
|
183
|
+
return (data ?? []).map(rowToProviderTemplate);
|
|
184
|
+
} catch (err) {
|
|
185
|
+
console.warn("[automations] could not load provider template status", err);
|
|
186
|
+
return [];
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function providerTemplateFor(rows, eventKey, channel) {
|
|
190
|
+
const matching = rows.filter((r) => r.eventKey === eventKey && r.channel === channel);
|
|
191
|
+
return {
|
|
192
|
+
own: matching.find((r) => r.tenantId !== null) ?? null,
|
|
193
|
+
fallback: matching.find((r) => r.tenantId === null) ?? null
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function providerApprovalFor(rows, eventKey, channel) {
|
|
197
|
+
if (channel !== "whatsapp") return null;
|
|
198
|
+
const { own, fallback } = providerTemplateFor(rows, eventKey, channel);
|
|
199
|
+
const row = own ?? fallback;
|
|
200
|
+
if (!row) return null;
|
|
201
|
+
const fallbackApproved = fallback?.status === "approved";
|
|
202
|
+
switch (row.status) {
|
|
203
|
+
case "approved":
|
|
204
|
+
return { tone: "ok", label: "Aprovado pela Meta" };
|
|
205
|
+
case "rejected":
|
|
206
|
+
return {
|
|
207
|
+
tone: fallbackApproved && own ? "waiting" : "error",
|
|
208
|
+
label: fallbackApproved && own ? "Seu texto foi recusado" : "Recusado pela Meta",
|
|
209
|
+
detail: row.rejectionReason ? `Motivo: ${row.rejectionReason}` : "A Meta n\xE3o disse o motivo."
|
|
210
|
+
};
|
|
211
|
+
case "paused":
|
|
212
|
+
return {
|
|
213
|
+
tone: "error",
|
|
214
|
+
label: "Pausado pela Meta",
|
|
215
|
+
detail: row.rejectionReason ?? "Costuma ser excesso de marca\xE7\xF5es de spam pelos clientes."
|
|
216
|
+
};
|
|
217
|
+
case "disabled":
|
|
218
|
+
return { tone: "error", label: "Desativado pela Meta", detail: row.rejectionReason ?? void 0 };
|
|
219
|
+
case "submitted":
|
|
220
|
+
return {
|
|
221
|
+
tone: "waiting",
|
|
222
|
+
label: "Aguardando aprova\xE7\xE3o da Meta",
|
|
223
|
+
detail: fallbackApproved && own ? "At\xE9 l\xE1 a mensagem sai com o texto padr\xE3o." : "A revis\xE3o costuma levar algumas horas."
|
|
224
|
+
};
|
|
225
|
+
default:
|
|
226
|
+
return { tone: "waiting", label: "Ainda n\xE3o enviado para aprova\xE7\xE3o" };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
var TONE_VARIANT = {
|
|
230
|
+
ok: "success",
|
|
231
|
+
waiting: "warning",
|
|
232
|
+
error: "destructive"
|
|
233
|
+
};
|
|
234
|
+
function ProviderTemplateBadge({ approval, showDetail }) {
|
|
235
|
+
if (!approval) return null;
|
|
236
|
+
if (approval.tone === "ok" && !showDetail) return null;
|
|
237
|
+
return /* @__PURE__ */ jsxs("span", { className: "inline-flex flex-wrap items-center gap-1.5", children: [
|
|
238
|
+
/* @__PURE__ */ jsx(Badge, { variant: TONE_VARIANT[approval.tone], children: approval.label }),
|
|
239
|
+
showDetail && approval.detail && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: approval.detail })
|
|
240
|
+
] });
|
|
241
|
+
}
|
|
242
|
+
function useProviderTemplates() {
|
|
243
|
+
const [rows, setRows] = React.useState([]);
|
|
244
|
+
React.useEffect(() => {
|
|
245
|
+
let cancelled = false;
|
|
246
|
+
void loadProviderTemplates().then((data) => {
|
|
247
|
+
if (!cancelled) setRows(data);
|
|
248
|
+
});
|
|
249
|
+
return () => {
|
|
250
|
+
cancelled = true;
|
|
251
|
+
};
|
|
252
|
+
}, []);
|
|
253
|
+
return rows;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export { PROVIDER_TEMPLATES_TABLE, ProviderTemplateBadge, createFayzTemplateStore, getFayzAutomationsClient, loadProviderTemplates, providerApprovalFor, providerTemplateFor, useProviderTemplates };
|
|
257
|
+
//# sourceMappingURL=chunk-63YAGMWV.js.map
|
|
258
|
+
//# sourceMappingURL=chunk-63YAGMWV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/data/fayz.ts","../src/data/provider-templates.ts","../src/views/ProviderTemplateStatus.tsx"],"names":["row"],"mappings":";;;;;;;;AAkBA,SAAS,WAAW,UAAA,EAAoD;AACtE,EAAA,MAAM,QAA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IAC5D,UAAA,IAAc,SAAS,MAAA,oBACtB,GAAA,CAAC,UAAK,SAAA,EAAU,+BAAA,EAAiC,mBAAS,MAAA,EAAO;AAAA,GAAA,EAErE,CAAA;AAEJ;AAGO,SAAS,oBAAA,GAA8C;AAC5D,EAAA,MAAM,CAAC,IAAA,EAAM,OAAO,IAAI,KAAA,CAAM,QAAA,CAAgC,EAAE,CAAA;AAChE,EAAA,KAAA,CAAM,UAAU,MAAM;AACpB,IAAA,IAAI,SAAA,GAAY,KAAA;AAChB,IAAA,KAAK,qBAAA,EAAsB,CAAE,IAAA,CAAK,CAAC,IAAA,KAAS;AAAE,MAAA,IAAI,CAAC,SAAA,EAAW,OAAA,CAAQ,IAAI,CAAA;AAAA,IAAE,CAAC,CAAA;AAC7E,IAAA,OAAO,MAAM;AAAE,MAAA,SAAA,GAAY,IAAA;AAAA,IAAK,CAAA;AAAA,EAClC,CAAA,EAAG,EAAE,CAAA;AACL,EAAA,OAAO,IAAA;AACT","file":"chunk-63YAGMWV.js","sourcesContent":["import { getFayzSupabaseClientOptional } from '@fayz-ai/admin'\nimport type { ResolvedFayzAgentConnection } from '@fayz-ai/admin'\nimport { getMessageDefaults } from '@fayz-ai/core'\nimport type { MessageChannel, MessageTemplate } from '@fayz-ai/core'\nimport {\n createFayzAutomationsClient,\n FayzAutomationsError,\n type FayzAutomation,\n type FayzAutomationsClient,\n} from '@fayz-ai/sdk/automations'\nimport type { MessageTemplateStore } from './templates'\n\n// ---------------------------------------------------------------------------\n// The SAME contract as `templates.ts`, served by the platform: behind a Fayz\n// project the platform is what runs the automations, so the customisation has\n// to live there — a local row the platform never reads is a fake switch.\n// ---------------------------------------------------------------------------\n\nfunction toTemplate(automation: FayzAutomation): MessageTemplate | null {\n const eventKey = automation.triggerConfig?.eventKey\n // No eventKey means it isn't a catalogue automation — standalone platform\n // flows have no row on this screen.\n if (!eventKey) return null\n const action = automation.actions?.[0]\n return {\n id: automation.id,\n tenantId: automation.tenantId ?? '',\n eventKey,\n channel: (automation.triggerConfig.sourceChannel ?? 'email') as MessageChannel,\n enabled: automation.enabled,\n // Empty and absent mean the same — \"no customisation\", the catalogue default.\n subject: action?.config?.subject || null,\n body: action?.config?.body || null,\n // The automation name belongs to the platform, not a user rename: the\n // catalogue title still owns the screen.\n name: null,\n // The platform's automation action carries a subject and a body and nothing\n // else, so there is nowhere for a customised button to live yet. NULL, not\n // [], because the catalogue default is what still applies — an empty list\n // would read as \"this tenant removed the buttons\".\n actions: null,\n updatedAt: automation.updatedAt,\n }\n}\n\nfunction catalogDefaultEnabled(eventKey: string, channel: MessageChannel): boolean {\n const def = getMessageDefaults().find((d) => d.eventKey === eventKey)\n return def?.defaultEnabled?.[channel] ?? false\n}\n\nasync function defaultSessionToken(): Promise<string | null> {\n const session = (await getFayzSupabaseClientOptional()?.auth.getSession())?.data.session\n return session?.access_token ?? null\n}\n\nexport interface FayzTemplateStoreDeps {\n client?: FayzAutomationsClient\n getSessionToken?: () => Promise<string | null>\n}\n\nexport function createFayzTemplateStore(\n connection: ResolvedFayzAgentConnection,\n deps: FayzTemplateStoreDeps = {},\n): MessageTemplateStore {\n const client = deps.client ?? createFayzAutomationsClient({\n baseUrl: connection.apiBaseUrl,\n projectId: connection.projectId,\n publishableKey: connection.publishableKey,\n })\n const getSessionToken = deps.getSessionToken ?? defaultSessionToken\n\n // (event_key, channel) → platform automation id, repopulated on every list.\n const ids = new Map<string, string>()\n const keyOf = (eventKey: string, channel: string) => `${eventKey}:${channel}`\n\n async function refresh(tenantId: string): Promise<MessageTemplate[]> {\n const automations = await client.list({ tenantId })\n ids.clear()\n const rows: MessageTemplate[] = []\n for (const automation of automations) {\n const row = toTemplate(automation)\n if (!row) continue\n ids.set(keyOf(row.eventKey, row.channel), automation.id)\n rows.push(row)\n }\n return rows\n }\n\n // One screen mounts several views of the same catalogue (list, detail, CRM ⚡)\n // and StrictMode doubles effects in dev — unshared, opening it costs 8+ identical\n // GETs. One flight per tenant, short-lived; writes invalidate.\n const LIST_TTL_MS = 30_000\n let cache: { tenantId: string; at: number; promise: Promise<MessageTemplate[]> } | null = null\n\n function invalidate(): void {\n cache = null\n }\n\n function load(tenantId: string): Promise<MessageTemplate[]> {\n if (cache && cache.tenantId === tenantId && Date.now() - cache.at < LIST_TTL_MS) return cache.promise\n const promise = refresh(tenantId)\n promise.catch(() => {\n if (cache?.promise === promise) cache = null // a failure must not stay cached for 30s\n })\n cache = { tenantId, at: Date.now(), promise }\n return promise\n }\n\n async function requireToken(): Promise<string> {\n const token = await getSessionToken()\n // Writing needs the app session — same message as the rest of the admin.\n if (!token) throw new Error('Sessão expirada — entre de novo.')\n return token\n }\n\n async function resolveId(eventKey: string, channel: string, tenantId: string): Promise<string | undefined> {\n const key = keyOf(eventKey, channel)\n if (!ids.has(key)) await load(tenantId)\n return ids.get(key)\n }\n\n return {\n async list(tenantId) {\n // No account yet, nothing to ask — the catalogue at its defaults is a\n // complete state, same as the local store when the read fails.\n if (!tenantId) return []\n return load(tenantId)\n },\n\n async upsert(input, tenantId) {\n if (!tenantId) throw new Error('@fayz-ai/plugin-automations: tenantId is required')\n const appSessionToken = await requireToken()\n const key = keyOf(input.eventKey, input.channel)\n let id = await resolveId(input.eventKey, input.channel, tenantId)\n\n if (!id) {\n const action: { subject?: string; body?: string } = {}\n if (input.subject != null) action.subject = input.subject\n if (input.body != null) action.body = input.body\n try {\n const created = await client.create({\n tenantId,\n appSessionToken,\n eventKey: input.eventKey,\n sourceChannel: input.channel,\n // The platform has no \"inherit from catalogue\": materialise the default.\n enabled: input.enabled ?? catalogDefaultEnabled(input.eventKey, input.channel),\n ...(Object.keys(action).length ? { action } : {}),\n })\n ids.set(key, created.id)\n invalidate()\n const row = toTemplate(created)\n if (!row) throw new Error('@fayz-ai/plugin-automations: platform did not round-trip eventKey')\n return row\n } catch (err) {\n // 409: someone created it first — turn it into an update.\n if (!(err instanceof FayzAutomationsError) || err.status !== 409) throw err\n invalidate()\n await refresh(tenantId)\n id = ids.get(key)\n if (!id) throw err\n }\n }\n\n const updated = await client.update({\n id,\n tenantId,\n appSessionToken,\n // Only what was sent: omitting has to mean \"leave it alone\", as in the local store.\n ...(typeof input.enabled === 'boolean' ? { enabled: input.enabled } : {}),\n ...(input.subject !== undefined || input.body !== undefined\n ? {\n action: {\n ...(input.subject !== undefined ? { subject: input.subject } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n },\n }\n : {}),\n })\n invalidate()\n const row = toTemplate(updated)\n if (!row) throw new Error('@fayz-ai/plugin-automations: platform did not round-trip eventKey')\n return row\n },\n\n async reset(eventKey, channel, tenantId) {\n if (!tenantId) return\n const id = await resolveId(eventKey, channel, tenantId)\n // Never customised: the default already applies, nothing to clear.\n if (!id) return\n const appSessionToken = await requireToken()\n // The automation stays (the on/off belongs to it); only the text goes back\n // to the catalogue — null clears the field on the server.\n await client.update({ id, tenantId, appSessionToken, action: { subject: null, body: null } })\n invalidate()\n },\n }\n}\n\nlet cachedClient: { key: string; client: FayzAutomationsClient } | null = null\n\n/** One client per connection — RunLog and the store read the same surface. */\nexport function getFayzAutomationsClient(connection: ResolvedFayzAgentConnection): FayzAutomationsClient {\n const key = `${connection.apiBaseUrl}|${connection.projectId}|${connection.publishableKey}`\n if (cachedClient?.key === key) return cachedClient.client\n const client = createFayzAutomationsClient({\n baseUrl: connection.apiBaseUrl,\n projectId: connection.projectId,\n publishableKey: connection.publishableKey,\n })\n cachedClient = { key, client }\n return client\n}\n","import { getSupabaseClientOptional } from '@fayz-ai/core'\nimport type { MessageChannel } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// O que a Meta respondeu sobre cada modelo.\n//\n// Só LEITURA. A tabela é escrita pelo webhook e pela função de sincronização,\n// com service role: quem pudesse marcar `approved` daqui faria o envio tentar um\n// modelo que a Meta nunca liberou, e a recusa chegaria como uma confirmação de\n// horário que não saiu.\n//\n// A leitura traz as linhas do tenant E as do produto (tenant_id NULL). São as\n// duas que importam na tela: a mensagem sai pela do produto até a do tenant ser\n// aprovada, então \"aguardando aprovação\" só é verdade quando NENHUMA das duas\n// está aprovada.\n// ---------------------------------------------------------------------------\n\nexport const PROVIDER_TEMPLATES_TABLE = 'plg_automations_provider_templates'\n\nexport type ProviderTemplateStatus =\n | 'draft' | 'submitted' | 'approved' | 'rejected' | 'paused' | 'disabled'\n\nexport interface ProviderTemplateRow {\n id: string\n /** NULL = o modelo padrão do produto, que serve todos os tenants. */\n tenantId: string | null\n eventKey: string\n channel: MessageChannel\n provider: string\n templateName: string\n status: ProviderTemplateStatus\n rejectionReason: string | null\n updatedAt: string | null\n}\n\nfunction rowToProviderTemplate(row: any): ProviderTemplateRow {\n return {\n id: row.id,\n tenantId: row.tenant_id ?? null,\n eventKey: row.event_key,\n channel: (row.channel ?? 'whatsapp') as MessageChannel,\n provider: row.provider ?? 'tyxter',\n templateName: row.template_name ?? '',\n status: (row.status ?? 'draft') as ProviderTemplateStatus,\n rejectionReason: row.rejection_reason || null,\n updatedAt: row.updated_at ?? row.created_at ?? null,\n }\n}\n\n/**\n * Nunca lança: sem cliente, sem tabela ou sem permissão a lista de automações\n * continua inteira, só sem a pastilha de aprovação. Um erro aqui não pode\n * esconder as automações de e-mail, que não dependem da Meta para nada.\n */\nexport async function loadProviderTemplates(): Promise<ProviderTemplateRow[]> {\n const client = getSupabaseClientOptional() as unknown as { from: (t: string) => any } | null\n if (!client) return []\n try {\n // Sem filtro de tenant: a RLS já entrega as linhas deste tenant mais as do\n // produto, e filtrar por tenant aqui esconderia justamente o modelo padrão\n // pelo qual a mensagem sai hoje.\n const { data, error } = await client.from(PROVIDER_TEMPLATES_TABLE).select('*')\n if (error) throw error\n return (data ?? []).map(rowToProviderTemplate)\n } catch (err) {\n console.warn('[automations] could not load provider template status', err)\n return []\n }\n}\n\n/**\n * A linha que decide o que a tela mostra para um (evento × canal).\n *\n * A do tenant ganha quando existe — é a que ele está esperando. Se ela não\n * existe, vale a do produto. E se a do tenant foi recusada mas a do produto está\n * aprovada, a mensagem AINDA SAI (pela do produto): quem escolhe aqui é a linha\n * do tenant, e o texto da pastilha é que diz isso.\n */\nexport function providerTemplateFor(\n rows: ProviderTemplateRow[],\n eventKey: string,\n channel: MessageChannel,\n): { own: ProviderTemplateRow | null; fallback: ProviderTemplateRow | null } {\n const matching = rows.filter((r) => r.eventKey === eventKey && r.channel === channel)\n return {\n own: matching.find((r) => r.tenantId !== null) ?? null,\n fallback: matching.find((r) => r.tenantId === null) ?? null,\n }\n}\n","import React from 'react'\nimport { Badge } from '@fayz-ai/ui'\nimport type { MessageChannel } from '@fayz-ai/core'\nimport {\n loadProviderTemplates, providerTemplateFor,\n type ProviderTemplateRow,\n} from '../data/provider-templates'\n\n// ---------------------------------------------------------------------------\n// \"Ligado\" não quer dizer \"vai sair\".\n//\n// No WhatsApp a mensagem só existe depois que a Meta aprova o modelo, e a\n// aprovação é assíncrona: pode levar horas e pode voltar recusada. Sem esta\n// pastilha a tela mostra um interruptor verde para uma automação que a Meta\n// ainda não liberou — e o negócio só descobre quando a cliente não recebe.\n//\n// Só o WhatsApp tem isso. E-mail não passa por aprovação de ninguém, então a\n// pastilha some nos outros canais em vez de dizer \"aprovado\" sobre algo que\n// nunca precisou ser.\n// ---------------------------------------------------------------------------\n\nexport type ProviderApproval =\n | { tone: 'ok'; label: string; detail?: string }\n | { tone: 'waiting'; label: string; detail?: string }\n | { tone: 'error'; label: string; detail?: string }\n\n/**\n * O que a linha mostra para um (evento × canal).\n *\n * `null` = nada a dizer, e é o caso comum: canal sem aprovação, ou WhatsApp\n * ainda não conectado (sem nenhuma linha, o assunto não existe para este\n * negócio e uma pastilha vermelha seria um alarme sobre algo que ninguém pediu).\n *\n * A regra que decide o texto é a mesma do envio: sai pelo modelo do produto até\n * o do tenant ser aprovado. Por isso um modelo do tenant recusado, com o do\n * produto aprovado, é um AVISO e não uma falha — a mensagem continua saindo.\n */\nexport function providerApprovalFor(\n rows: ProviderTemplateRow[],\n eventKey: string,\n channel: MessageChannel,\n): ProviderApproval | null {\n if (channel !== 'whatsapp') return null\n const { own, fallback } = providerTemplateFor(rows, eventKey, channel)\n const row = own ?? fallback\n if (!row) return null\n\n const fallbackApproved = fallback?.status === 'approved'\n\n switch (row.status) {\n case 'approved':\n return { tone: 'ok', label: 'Aprovado pela Meta' }\n case 'rejected':\n return {\n tone: fallbackApproved && own ? 'waiting' : 'error',\n label: fallbackApproved && own ? 'Seu texto foi recusado' : 'Recusado pela Meta',\n detail: row.rejectionReason\n ? `Motivo: ${row.rejectionReason}`\n : 'A Meta não disse o motivo.',\n }\n case 'paused':\n return {\n tone: 'error',\n label: 'Pausado pela Meta',\n detail: row.rejectionReason ?? 'Costuma ser excesso de marcações de spam pelos clientes.',\n }\n case 'disabled':\n return { tone: 'error', label: 'Desativado pela Meta', detail: row.rejectionReason ?? undefined }\n case 'submitted':\n return {\n tone: 'waiting',\n label: 'Aguardando aprovação da Meta',\n detail: fallbackApproved && own\n ? 'Até lá a mensagem sai com o texto padrão.'\n : 'A revisão costuma levar algumas horas.',\n }\n default:\n return { tone: 'waiting', label: 'Ainda não enviado para aprovação' }\n }\n}\n\nconst TONE_VARIANT: Record<ProviderApproval['tone'], 'success' | 'warning' | 'destructive'> = {\n ok: 'success',\n waiting: 'warning',\n error: 'destructive',\n}\n\nexport function ProviderTemplateBadge({ approval, showDetail }: {\n approval: ProviderApproval | null\n showDetail?: boolean\n}) {\n if (!approval) return null\n // Aprovado não ganha pastilha na lista: é o estado normal, e uma linha em que\n // tudo está certo não precisa de enfeite. O que precisa aparecer é o que\n // impede a mensagem de sair.\n if (approval.tone === 'ok' && !showDetail) return null\n return (\n <span className=\"inline-flex flex-wrap items-center gap-1.5\">\n <Badge variant={TONE_VARIANT[approval.tone]}>{approval.label}</Badge>\n {showDetail && approval.detail && (\n <span className=\"text-xs text-muted-foreground\">{approval.detail}</span>\n )}\n </span>\n )\n}\n\n/** Uma leitura por tela. Nunca lança: sem a tabela, a lista continua inteira. */\nexport function useProviderTemplates(): ProviderTemplateRow[] {\n const [rows, setRows] = React.useState<ProviderTemplateRow[]>([])\n React.useEffect(() => {\n let cancelled = false\n void loadProviderTemplates().then((data) => { if (!cancelled) setRows(data) })\n return () => { cancelled = true }\n }, [])\n return rows\n}\n"]}
|