opscms-meta-plugin 0.0.0-stage → 0.4.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +180 -0
  2. package/LICENSE +21 -0
  3. package/README.md +338 -2
  4. package/dist/chunk-HCQSD757.mjs +142 -0
  5. package/dist/chunk-QEVRQKSQ.mjs +26 -0
  6. package/dist/components/MetaCatalogSync/index.d.mts +10 -0
  7. package/dist/components/MetaCatalogSync/index.d.ts +10 -0
  8. package/dist/components/MetaCatalogSync/index.js +195 -0
  9. package/dist/components/MetaCatalogSync/index.mjs +108 -0
  10. package/dist/components/MetaConnectPanel/index.d.mts +20 -0
  11. package/dist/components/MetaConnectPanel/index.d.ts +20 -0
  12. package/dist/components/MetaConnectPanel/index.js +723 -0
  13. package/dist/components/MetaConnectPanel/index.mjs +554 -0
  14. package/dist/components/MetaLoginButton/index.d.mts +5 -0
  15. package/dist/components/MetaLoginButton/index.d.ts +5 -0
  16. package/dist/components/MetaLoginButton/index.js +82 -0
  17. package/dist/components/MetaLoginButton/index.mjs +58 -0
  18. package/dist/components/MetaPixelSelect/index.d.mts +11 -0
  19. package/dist/components/MetaPixelSelect/index.d.ts +11 -0
  20. package/dist/components/MetaPixelSelect/index.js +202 -0
  21. package/dist/components/MetaPixelSelect/index.mjs +115 -0
  22. package/dist/components/ThreadsConnectPanel/index.d.mts +10 -0
  23. package/dist/components/ThreadsConnectPanel/index.d.ts +10 -0
  24. package/dist/components/ThreadsConnectPanel/index.js +163 -0
  25. package/dist/components/ThreadsConnectPanel/index.mjs +56 -0
  26. package/dist/index.d.mts +376 -0
  27. package/dist/index.d.ts +376 -0
  28. package/dist/index.js +3561 -0
  29. package/dist/index.mjs +3501 -0
  30. package/icon.svg +1 -0
  31. package/package.json +109 -4
@@ -0,0 +1,723 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/components/MetaConnectPanel/index.tsx
32
+ var MetaConnectPanel_exports = {};
33
+ __export(MetaConnectPanel_exports, {
34
+ MetaConnectPanelField: () => MetaConnectPanelField,
35
+ MetaTenantDefaults: () => MetaTenantDefaults
36
+ });
37
+ module.exports = __toCommonJS(MetaConnectPanel_exports);
38
+ var import_react3 = require("react");
39
+ var import_ui3 = require("@payloadcms/ui");
40
+
41
+ // src/components/shared.tsx
42
+ var import_react = __toESM(require("react"));
43
+ var import_ui = require("@payloadcms/ui");
44
+ var import_jsx_runtime = require("react/jsx-runtime");
45
+ var fieldWrapperStyle = {
46
+ marginBottom: "1.5rem"
47
+ };
48
+ var descriptionStyle = {
49
+ fontSize: "0.8125rem",
50
+ color: "var(--theme-elevation-500, #6b7280)",
51
+ marginTop: "0.25rem",
52
+ lineHeight: 1.4
53
+ };
54
+ var messageBoxStyle = (variant) => ({
55
+ padding: "0.75rem 1rem",
56
+ borderRadius: "var(--style-radius, 0.25rem)",
57
+ border: "1px solid",
58
+ borderColor: variant === "error" ? "var(--theme-error-250, #fecaca)" : variant === "warning" ? "var(--theme-warning-250, #fde68a)" : variant === "success" ? "var(--theme-success-250, #bbf7d0)" : "var(--theme-elevation-150, #e5e7eb)",
59
+ backgroundColor: variant === "error" ? "var(--theme-error-100, #fef2f2)" : variant === "warning" ? "var(--theme-warning-100, #fffbeb)" : variant === "success" ? "var(--theme-success-100, #f0fdf4)" : "var(--theme-elevation-50, #f9fafb)",
60
+ color: variant === "error" ? "var(--theme-error-700, #b91c1c)" : variant === "warning" ? "var(--theme-warning-700, #b45309)" : variant === "success" ? "var(--theme-success-700, #15803d)" : "var(--theme-elevation-500, #6b7280)",
61
+ fontSize: "0.875rem",
62
+ lineHeight: 1.4,
63
+ marginBottom: "0.75rem"
64
+ });
65
+ var FieldWrapper = ({ path, label, description, children }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: fieldWrapperStyle, children: [
66
+ label && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui.FieldLabel, { label, path }),
67
+ children,
68
+ description && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: descriptionStyle, children: description })
69
+ ] });
70
+ var LoadingState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: messageBoxStyle("info"), children: [
71
+ "\u23F3 ",
72
+ message
73
+ ] });
74
+ var EmptyState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: messageBoxStyle("info"), children: message });
75
+ var ErrorState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: messageBoxStyle("error"), children: [
76
+ "\u26A0\uFE0F ",
77
+ message
78
+ ] });
79
+ var SuccessState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: messageBoxStyle("success"), children: [
80
+ "\u2705 ",
81
+ message
82
+ ] });
83
+ var ConnectButton = ({ onClick, disabled, children }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui.Button, { type: "button", buttonStyle: "primary", size: "medium", disabled, onClick, children });
84
+ var StyledSelect = ({
85
+ path,
86
+ value,
87
+ options,
88
+ placeholder = "Select an option",
89
+ onChange
90
+ }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
91
+ import_ui.SelectInput,
92
+ {
93
+ path,
94
+ name: path,
95
+ value,
96
+ onChange: (option) => {
97
+ const selected = Array.isArray(option) ? option[0] : option;
98
+ onChange(selected?.value != null ? String(selected.value) : "");
99
+ },
100
+ options: [{ label: `\u2014 ${placeholder} \u2014`, value: "" }, ...options]
101
+ }
102
+ );
103
+ function useMetaAppInfo() {
104
+ const [state, setState] = import_react.default.useState({ configured: false, maskedAppId: null, loading: true });
105
+ import_react.default.useEffect(() => {
106
+ fetch("/api/meta-oauth/app-info").then((res) => res.json()).then((data) => setState({ configured: Boolean(data.configured), maskedAppId: data.maskedAppId ?? null, loading: false })).catch(() => setState({ configured: false, maskedAppId: null, loading: false }));
107
+ }, []);
108
+ return state;
109
+ }
110
+ var MetaAppInfoBadge = ({ appInfo }) => {
111
+ if (appInfo.loading) return null;
112
+ if (!appInfo.configured) {
113
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 an admin needs to set META_APP_ID and META_APP_SECRET." });
114
+ }
115
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
116
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
117
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: appInfo.maskedAppId })
118
+ ] });
119
+ };
120
+ var DetailList = ({ items }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { display: "grid", gridTemplateColumns: "auto 1fr", columnGap: "1rem", rowGap: "0.375rem", fontSize: "0.875rem", margin: "0.5rem 0 0.75rem" }, children: items.map((item) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react.default.Fragment, { children: [
121
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: { color: "var(--theme-elevation-500, #6b7280)" }, children: item.label }),
122
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: item.value })
123
+ ] }, item.label)) });
124
+ var META_OAUTH_MESSAGE_SOURCE = "payload-meta-oauth";
125
+ function openMetaOAuthPopup(url, onResult) {
126
+ const popup = window.open(url, "payload-meta-oauth", "popup=yes,width=520,height=720");
127
+ if (!popup) {
128
+ window.location.assign(url.replace(/([?&])popup=1\b/, "$1popup=0"));
129
+ return;
130
+ }
131
+ let settled = false;
132
+ const finish = (result) => {
133
+ if (settled) return;
134
+ settled = true;
135
+ window.removeEventListener("message", onMessage);
136
+ window.clearInterval(timer);
137
+ onResult(result);
138
+ };
139
+ const onMessage = (event) => {
140
+ if (event.origin !== window.location.origin) return;
141
+ const data = event.data;
142
+ if (!data || data.source !== META_OAUTH_MESSAGE_SOURCE) return;
143
+ finish({ ok: Boolean(data.ok), error: data.error ? String(data.error) : null });
144
+ };
145
+ window.addEventListener("message", onMessage);
146
+ const timer = window.setInterval(() => {
147
+ if (popup.closed) finish({ ok: false, error: null });
148
+ }, 400);
149
+ }
150
+ function useOAuthRedirectMessage(successParam, errorParam) {
151
+ const [state, setState] = import_react.default.useState({ success: false, error: null });
152
+ import_react.default.useEffect(() => {
153
+ if (typeof window === "undefined") return;
154
+ const params = new URLSearchParams(window.location.search);
155
+ const success = params.get(successParam) === "1";
156
+ const error = params.get(errorParam);
157
+ if (success || error) {
158
+ setState({ success, error });
159
+ params.delete(successParam);
160
+ params.delete(errorParam);
161
+ const newSearch = params.toString();
162
+ const newUrl = `${window.location.pathname}${newSearch ? `?${newSearch}` : ""}`;
163
+ window.history.replaceState({}, "", newUrl);
164
+ }
165
+ }, []);
166
+ return state;
167
+ }
168
+
169
+ // src/oauth/clearedConnection.ts
170
+ function clearedMetaUserConnection() {
171
+ return {
172
+ accessToken: null,
173
+ oauthUserAccessToken: null,
174
+ oauthExpiresAt: null,
175
+ facebookPageId: null,
176
+ facebookPageName: null,
177
+ instagramBusinessAccountId: null,
178
+ instagramUsername: null,
179
+ businessManagerId: null,
180
+ pixelId: null,
181
+ pixelEnabled: false,
182
+ catalogId: null,
183
+ catalogEnabled: false,
184
+ whatsappPhoneNumberId: null,
185
+ whatsappBusinessAccountId: null,
186
+ whatsappEnabled: false,
187
+ authMethod: "manual",
188
+ connectionStatus: "disconnected"
189
+ };
190
+ }
191
+
192
+ // src/components/MetaConnectPanel/TenantDefaults.tsx
193
+ var import_react2 = require("react");
194
+ var import_ui2 = require("@payloadcms/ui");
195
+ function relationId(value) {
196
+ if (value == null || value === "") return null;
197
+ if (typeof value === "object") {
198
+ const id = value.id;
199
+ if (typeof id === "string" || typeof id === "number") return id;
200
+ return null;
201
+ }
202
+ if (typeof value === "string" || typeof value === "number") return value;
203
+ return null;
204
+ }
205
+ var MetaTenantDefaults = () => {
206
+ const { user } = (0, import_ui2.useAuth)();
207
+ const { id } = (0, import_ui2.useDocumentInfo)();
208
+ const { dispatchFields } = (0, import_ui2.useForm)();
209
+ const siteValue = (0, import_ui2.useFormFields)(([fields]) => fields?.site?.value);
210
+ const organizationValue = (0, import_ui2.useFormFields)(([fields]) => fields?.organization?.value);
211
+ const seeded = (0, import_react2.useRef)(false);
212
+ const lastSite = (0, import_react2.useRef)(null);
213
+ const lastOrg = (0, import_react2.useRef)(null);
214
+ const setSite = (0, import_react2.useCallback)((value) => {
215
+ dispatchFields({ type: "UPDATE", path: "site", value });
216
+ }, [dispatchFields]);
217
+ const setOrganization = (0, import_react2.useCallback)((value) => {
218
+ dispatchFields({ type: "UPDATE", path: "organization", value });
219
+ }, [dispatchFields]);
220
+ (0, import_react2.useEffect)(() => {
221
+ if (id || seeded.current) return;
222
+ const account = user;
223
+ if (!account) return;
224
+ const ownSite = relationId(account.site);
225
+ const ownOrg = relationId(account.organization);
226
+ if (relationId(organizationValue) == null && ownOrg != null) setOrganization(ownOrg);
227
+ if (relationId(siteValue) == null && ownSite != null) {
228
+ setSite(ownSite);
229
+ seeded.current = true;
230
+ return;
231
+ }
232
+ if (relationId(siteValue) != null || ownOrg == null || account.role === "super-admin") {
233
+ seeded.current = true;
234
+ return;
235
+ }
236
+ let cancelled = false;
237
+ fetch(`/api/sites?where[organization][equals]=${encodeURIComponent(String(ownOrg))}&limit=2&depth=0`).then((res) => res.json()).then((body) => {
238
+ if (cancelled) return;
239
+ const docs = body?.docs ?? [];
240
+ if (docs.length === 1 && docs[0]?.id != null) {
241
+ setSite(docs[0].id);
242
+ const siteOrg = relationId(docs[0].organization) ?? ownOrg;
243
+ setOrganization(siteOrg);
244
+ }
245
+ }).catch(() => {
246
+ }).finally(() => {
247
+ seeded.current = true;
248
+ });
249
+ return () => {
250
+ cancelled = true;
251
+ };
252
+ }, [id, user, siteValue, organizationValue, setSite, setOrganization]);
253
+ (0, import_react2.useEffect)(() => {
254
+ const siteId = relationId(siteValue);
255
+ if (siteId == null || lastSite.current === siteId) return;
256
+ lastSite.current = siteId;
257
+ let cancelled = false;
258
+ fetch(`/api/sites/${encodeURIComponent(String(siteId))}?depth=0`).then((res) => res.json()).then((doc) => {
259
+ const orgId = relationId(doc?.organization);
260
+ if (!cancelled && orgId != null) setOrganization(orgId);
261
+ }).catch(() => {
262
+ });
263
+ return () => {
264
+ cancelled = true;
265
+ };
266
+ }, [siteValue, setOrganization]);
267
+ (0, import_react2.useEffect)(() => {
268
+ const orgId = relationId(organizationValue);
269
+ if (orgId == null) return;
270
+ if (lastOrg.current == null) {
271
+ lastOrg.current = orgId;
272
+ return;
273
+ }
274
+ if (String(lastOrg.current) === String(orgId)) return;
275
+ lastOrg.current = orgId;
276
+ const siteId = relationId(siteValue);
277
+ if (siteId == null) return;
278
+ let cancelled = false;
279
+ fetch(`/api/sites/${encodeURIComponent(String(siteId))}?depth=0`).then((res) => res.json()).then((doc) => {
280
+ const siteOrg = relationId(doc?.organization);
281
+ if (cancelled || siteOrg == null || String(siteOrg) === String(orgId)) return;
282
+ lastSite.current = null;
283
+ dispatchFields({ type: "UPDATE", path: "site", value: null });
284
+ }).catch(() => {
285
+ });
286
+ return () => {
287
+ cancelled = true;
288
+ };
289
+ }, [organizationValue, siteValue, dispatchFields]);
290
+ return null;
291
+ };
292
+
293
+ // src/components/MetaConnectPanel/index.tsx
294
+ var import_jsx_runtime2 = require("react/jsx-runtime");
295
+ var stepStyle = { marginTop: "1.25rem" };
296
+ var stepTitle = { fontWeight: 600, marginBottom: "0.35rem" };
297
+ var hintStyle = { fontSize: "0.8125rem", lineHeight: 1.45, margin: "0 0 0.5rem" };
298
+ var rowStyle = { display: "flex", gap: "0.75rem", alignItems: "flex-end" };
299
+ var nameInputStyle = { width: "100%", padding: "0.5rem 0.6rem" };
300
+ var MetaConnectPanelField = () => {
301
+ const { id } = (0, import_ui3.useDocumentInfo)();
302
+ const { dispatchFields } = (0, import_ui3.useForm)();
303
+ const redirectMsg = useOAuthRedirectMessage("meta_oauth_success", "meta_oauth_error");
304
+ const appInfo = useMetaAppInfo();
305
+ const [doc, setDoc] = (0, import_react3.useState)(null);
306
+ const [loadingDoc, setLoadingDoc] = (0, import_react3.useState)(false);
307
+ const [pages, setPages] = (0, import_react3.useState)(null);
308
+ const [loadingPages, setLoadingPages] = (0, import_react3.useState)(false);
309
+ const [selectedPageId, setSelectedPageId] = (0, import_react3.useState)("");
310
+ const [saving, setSaving] = (0, import_react3.useState)(false);
311
+ const [actionError, setActionError] = (0, import_react3.useState)(null);
312
+ const [facebookName, setFacebookName] = (0, import_react3.useState)(null);
313
+ const [catalogs, setCatalogs] = (0, import_react3.useState)(null);
314
+ const [businesses, setBusinesses] = (0, import_react3.useState)([]);
315
+ const [pixels, setPixels] = (0, import_react3.useState)(null);
316
+ const [numbers, setNumbers] = (0, import_react3.useState)(null);
317
+ const [assetsError, setAssetsError] = (0, import_react3.useState)(null);
318
+ const [selectedCatalogId, setSelectedCatalogId] = (0, import_react3.useState)("");
319
+ const [selectedPixelId, setSelectedPixelId] = (0, import_react3.useState)("");
320
+ const [selectedNumberId, setSelectedNumberId] = (0, import_react3.useState)("");
321
+ const [newCatalogName, setNewCatalogName] = (0, import_react3.useState)("");
322
+ const [newPixelName, setNewPixelName] = (0, import_react3.useState)("");
323
+ const [createBusinessId, setCreateBusinessId] = (0, import_react3.useState)("");
324
+ const [stepMessage, setStepMessage] = (0, import_react3.useState)(null);
325
+ const [autoPageFailed, setAutoPageFailed] = (0, import_react3.useState)(false);
326
+ const autoOnce = (0, import_react3.useRef)({ page: false, catalog: false, pixel: false, number: false });
327
+ const loadDoc = (0, import_react3.useCallback)(() => {
328
+ if (!id) return;
329
+ setLoadingDoc(true);
330
+ fetch(`/api/meta-config/${id}?depth=0`).then((res) => res.json()).then((data) => setDoc(data)).catch(() => {
331
+ }).finally(() => setLoadingDoc(false));
332
+ }, [id]);
333
+ const isConnected = doc?.authMethod === "oauth";
334
+ const hasPage = Boolean(doc?.facebookPageId);
335
+ (0, import_react3.useEffect)(() => {
336
+ loadDoc();
337
+ }, [loadDoc, redirectMsg.success]);
338
+ (0, import_react3.useEffect)(() => {
339
+ if (!id || !isConnected) return;
340
+ fetch(`/api/meta-oauth/me?configId=${id}`).then((res) => res.json()).then((data) => {
341
+ if (data.name) setFacebookName(data.name);
342
+ }).catch(() => {
343
+ });
344
+ }, [id, isConnected]);
345
+ const loadPages = (0, import_react3.useCallback)(() => {
346
+ if (!id) return;
347
+ setLoadingPages(true);
348
+ setActionError(null);
349
+ fetch(`/api/meta-oauth/pages?configId=${id}`).then((res) => res.json()).then((data) => {
350
+ if (data.error) {
351
+ setActionError(data.error);
352
+ return;
353
+ }
354
+ setPages(data.pages ?? []);
355
+ }).catch(() => setActionError("Failed to load Pages")).finally(() => setLoadingPages(false));
356
+ }, [id]);
357
+ (0, import_react3.useEffect)(() => {
358
+ if (!id || !isConnected || hasPage || pages !== null || loadingPages) return;
359
+ loadPages();
360
+ }, [id, isConnected, hasPage, pages, loadingPages, loadPages]);
361
+ const loadAssets = (0, import_react3.useCallback)(() => {
362
+ if (!id) return;
363
+ setAssetsError(null);
364
+ Promise.all([
365
+ fetch(`/api/meta-catalog/catalogs?configId=${id}`).then((res) => res.json()),
366
+ fetch(`/api/meta-oauth/pixels?configId=${id}`).then((res) => res.json()),
367
+ fetch(`/api/meta-whatsapp/numbers?configId=${id}`).then((res) => res.json())
368
+ ]).then(([catalogData, pixelData, numberData]) => {
369
+ if (catalogData.error) setAssetsError(catalogData.error);
370
+ setCatalogs(catalogData.catalogs ?? []);
371
+ setBusinesses(catalogData.businesses ?? pixelData.businesses ?? []);
372
+ setPixels(pixelData.pixels ?? []);
373
+ setNumbers(numberData.numbers ?? []);
374
+ if (!catalogData.error && (pixelData.error || numberData.error)) {
375
+ setAssetsError(pixelData.error || numberData.error);
376
+ }
377
+ }).catch(() => setAssetsError("Could not load catalogs, Pixels, and WhatsApp numbers from this Facebook login."));
378
+ }, [id]);
379
+ (0, import_react3.useEffect)(() => {
380
+ if (!id || !hasPage) return;
381
+ loadAssets();
382
+ }, [id, hasPage, doc?.facebookPageId, loadAssets]);
383
+ const startConnect = () => {
384
+ if (!id) return;
385
+ setActionError(null);
386
+ openMetaOAuthPopup(`/api/meta-oauth/start?configId=${id}&popup=1`, (result) => {
387
+ if (result.error) setActionError(result.error);
388
+ loadDoc();
389
+ });
390
+ };
391
+ const disconnect = () => {
392
+ if (!id) return;
393
+ setSaving(true);
394
+ setActionError(null);
395
+ postJson("/api/meta-oauth/disconnect", { configId: id }).then((data) => {
396
+ if (data.error) {
397
+ setActionError(data.error);
398
+ return;
399
+ }
400
+ const cleared = clearedMetaUserConnection();
401
+ for (const [path, value] of Object.entries(cleared)) {
402
+ dispatchFields({ type: "UPDATE", path, value: value ?? "" });
403
+ }
404
+ autoOnce.current = { page: false, catalog: false, pixel: false, number: false };
405
+ setAutoPageFailed(false);
406
+ setPages(null);
407
+ setCatalogs(null);
408
+ setPixels(null);
409
+ setNumbers(null);
410
+ setFacebookName(null);
411
+ setSelectedPageId("");
412
+ setSelectedCatalogId("");
413
+ setSelectedPixelId("");
414
+ setSelectedNumberId("");
415
+ loadDoc();
416
+ }).catch(() => setActionError("Failed to disconnect")).finally(() => setSaving(false));
417
+ };
418
+ const postJson = (url, body) => fetch(url, {
419
+ method: "POST",
420
+ headers: { "Content-Type": "application/json" },
421
+ body: JSON.stringify(body)
422
+ }).then((res) => res.json());
423
+ const selectPage = (pageId) => {
424
+ const chosen = pageId || selectedPageId;
425
+ if (!id || !chosen) return;
426
+ setSaving(true);
427
+ setActionError(null);
428
+ postJson("/api/meta-oauth/select-page", { configId: id, pageId: chosen }).then((data) => {
429
+ if (data.error) {
430
+ setActionError(data.error);
431
+ if (pageId) setAutoPageFailed(true);
432
+ return;
433
+ }
434
+ dispatchFields({ type: "UPDATE", path: "facebookPageId", value: data.facebookPageId });
435
+ dispatchFields({ type: "UPDATE", path: "facebookPageName", value: data.facebookPageName });
436
+ dispatchFields({ type: "UPDATE", path: "instagramBusinessAccountId", value: data.instagramBusinessAccountId || "" });
437
+ dispatchFields({ type: "UPDATE", path: "instagramUsername", value: data.instagramUsername || "" });
438
+ dispatchFields({ type: "UPDATE", path: "connectionStatus", value: "connected" });
439
+ dispatchFields({ type: "UPDATE", path: "authMethod", value: "oauth" });
440
+ loadDoc();
441
+ setPages(null);
442
+ }).catch(() => setActionError("Failed to select Page")).finally(() => setSaving(false));
443
+ };
444
+ const rememberCatalog = (catalogId, businessId) => {
445
+ dispatchFields({ type: "UPDATE", path: "catalogEnabled", value: true });
446
+ dispatchFields({ type: "UPDATE", path: "catalogId", value: catalogId });
447
+ dispatchFields({ type: "UPDATE", path: "catalogSourceCollection", value: "catalogue-items" });
448
+ if (businessId) dispatchFields({ type: "UPDATE", path: "businessManagerId", value: businessId });
449
+ };
450
+ const useCatalog = (catalogId) => {
451
+ const choice = catalogId || selectedCatalogId || doc?.catalogId || "";
452
+ const catalog = catalogs?.find((item) => item.id === choice);
453
+ if (!id || !catalog) return;
454
+ setSaving(true);
455
+ setStepMessage(null);
456
+ postJson("/api/meta-catalog/select", { configId: id, catalogId: catalog.id, businessId: catalog.businessId }).then((data) => {
457
+ if (data.error) {
458
+ setAssetsError(data.error);
459
+ return;
460
+ }
461
+ rememberCatalog(catalog.id, catalog.businessId);
462
+ setStepMessage(`Catalog \u201C${catalog.name}\u201D is the one this site syncs to.`);
463
+ loadDoc();
464
+ }).catch(() => setAssetsError("Failed to save the catalog")).finally(() => setSaving(false));
465
+ };
466
+ const createCatalog = () => {
467
+ if (!id || !newCatalogName.trim()) return;
468
+ setSaving(true);
469
+ setStepMessage(null);
470
+ postJson("/api/meta-catalog/create", {
471
+ configId: id,
472
+ name: newCatalogName.trim(),
473
+ businessId: createBusinessId || businesses[0]?.id
474
+ }).then((data) => {
475
+ if (data.error) {
476
+ setAssetsError(data.error);
477
+ return;
478
+ }
479
+ rememberCatalog(data.catalogId, data.businessId);
480
+ setNewCatalogName("");
481
+ setStepMessage(`Created catalog \u201C${data.name}\u201D and selected it for this site.`);
482
+ loadAssets();
483
+ loadDoc();
484
+ }).catch(() => setAssetsError("Failed to create the catalog")).finally(() => setSaving(false));
485
+ };
486
+ const rememberPixel = (pixelId, businessId) => {
487
+ dispatchFields({ type: "UPDATE", path: "pixelEnabled", value: true });
488
+ dispatchFields({ type: "UPDATE", path: "pixelId", value: pixelId });
489
+ if (businessId) dispatchFields({ type: "UPDATE", path: "businessManagerId", value: businessId });
490
+ };
491
+ const usePixel = (pixelId) => {
492
+ const choice = pixelId || selectedPixelId || doc?.pixelId || "";
493
+ const pixel = pixels?.find((item) => item.id === choice);
494
+ if (!id || !choice) return;
495
+ setSaving(true);
496
+ setStepMessage(null);
497
+ postJson("/api/meta-oauth/select-pixel", { configId: id, pixelId: choice }).then((data) => {
498
+ if (data.error) {
499
+ setAssetsError(data.error);
500
+ return;
501
+ }
502
+ rememberPixel(data.pixelId, pixel?.businessId);
503
+ setStepMessage(`Pixel \u201C${data.name}\u201D is the one this site uses.`);
504
+ loadDoc();
505
+ }).catch(() => setAssetsError("Failed to save the Pixel")).finally(() => setSaving(false));
506
+ };
507
+ const createPixel = () => {
508
+ if (!id || !newPixelName.trim()) return;
509
+ setSaving(true);
510
+ setStepMessage(null);
511
+ postJson("/api/meta-oauth/pixels", {
512
+ configId: id,
513
+ name: newPixelName.trim(),
514
+ businessId: createBusinessId || businesses[0]?.id
515
+ }).then((data) => {
516
+ if (data.error) {
517
+ setAssetsError(data.error);
518
+ return;
519
+ }
520
+ rememberPixel(data.pixelId, data.businessId);
521
+ setNewPixelName("");
522
+ setStepMessage(`Created Pixel \u201C${newPixelName.trim()}\u201D and selected it for this site.`);
523
+ loadAssets();
524
+ loadDoc();
525
+ }).catch(() => setAssetsError("Failed to create the Pixel")).finally(() => setSaving(false));
526
+ };
527
+ const useNumber = (phoneNumberId) => {
528
+ const choice = phoneNumberId || selectedNumberId || doc?.whatsappPhoneNumberId || "";
529
+ if (!id || !choice) return;
530
+ setSaving(true);
531
+ setStepMessage(null);
532
+ postJson("/api/meta-whatsapp/select", { configId: id, phoneNumberId: choice }).then((data) => {
533
+ if (data.error) {
534
+ setAssetsError(data.error);
535
+ return;
536
+ }
537
+ dispatchFields({ type: "UPDATE", path: "whatsappEnabled", value: true });
538
+ dispatchFields({ type: "UPDATE", path: "whatsappPhoneNumberId", value: data.phoneNumberId });
539
+ dispatchFields({ type: "UPDATE", path: "whatsappBusinessAccountId", value: data.wabaId });
540
+ loadDoc();
541
+ }).catch(() => setAssetsError("Failed to save the WhatsApp number")).finally(() => setSaving(false));
542
+ };
543
+ (0, import_react3.useEffect)(() => {
544
+ if (autoOnce.current.page || !isConnected || hasPage || !pages || pages.length !== 1) return;
545
+ autoOnce.current.page = true;
546
+ selectPage(pages[0].id);
547
+ }, [isConnected, hasPage, pages]);
548
+ (0, import_react3.useEffect)(() => {
549
+ if (autoOnce.current.catalog || !hasPage || doc?.catalogId || !catalogs || catalogs.length !== 1) return;
550
+ autoOnce.current.catalog = true;
551
+ useCatalog(catalogs[0].id);
552
+ }, [hasPage, doc?.catalogId, catalogs]);
553
+ (0, import_react3.useEffect)(() => {
554
+ if (autoOnce.current.pixel || !hasPage || doc?.pixelId || !pixels || pixels.length !== 1) return;
555
+ autoOnce.current.pixel = true;
556
+ usePixel(pixels[0].id);
557
+ }, [hasPage, doc?.pixelId, pixels]);
558
+ (0, import_react3.useEffect)(() => {
559
+ if (autoOnce.current.number || !hasPage || doc?.whatsappPhoneNumberId || !numbers || numbers.length !== 1) return;
560
+ autoOnce.current.number = true;
561
+ useNumber(numbers[0].id);
562
+ }, [hasPage, doc?.whatsappPhoneNumberId, numbers]);
563
+ if (!id) {
564
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(FieldWrapper, { path: "metaConnectPanel", label: "Connect to Meta Business", children: [
565
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MetaAppInfoBadge, { appInfo }),
566
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "Save the document first, then Connect will be available." })
567
+ ] });
568
+ }
569
+ const pagePicker = pages === null ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: loadPages, disabled: loadingPages, children: loadingPages ? "Loading Pages\u2026" : "Load My Pages" }) : pages.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "No Pages found for this Facebook account. Make sure you admin at least one Facebook Page." }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: rowStyle, children: [
570
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
571
+ StyledSelect,
572
+ {
573
+ path: "metaConnectPanel_pageSelect",
574
+ value: selectedPageId,
575
+ options: pages.map((page) => ({ label: page.name, value: page.id })),
576
+ placeholder: "Select a Page",
577
+ onChange: setSelectedPageId
578
+ }
579
+ ) }),
580
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: () => selectPage(), disabled: !selectedPageId || saving, children: saving ? "Saving\u2026" : "Use This Page" })
581
+ ] });
582
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(FieldWrapper, { path: "metaConnectPanel", label: "Connect to Meta Business", children: [
583
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MetaAppInfoBadge, { appInfo }),
584
+ redirectMsg.error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorState, { message: redirectMsg.error }),
585
+ redirectMsg.success && !isConnected && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SuccessState, { message: "Connected. Loading the Pages on this Facebook login\u2026" }),
586
+ actionError && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorState, { message: actionError }),
587
+ loadingDoc ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(LoadingState, { message: "Loading connection status\u2026" }) : !isConnected ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
588
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "Log in with the Facebook account that manages this site. The Page, catalog, Pixel, and WhatsApp number fill in from that login. After that they stay read-only." }),
589
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: startConnect, disabled: !appInfo.configured, children: "Log in with Facebook" })
590
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
591
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SuccessState, { message: facebookName ? `Signed in as ${facebookName}` : "Signed in with Facebook" }),
592
+ hasPage && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
593
+ DetailList,
594
+ {
595
+ items: [
596
+ { label: "Facebook login", value: facebookName || "\u2014" },
597
+ { label: "Facebook Page", value: `${doc?.facebookPageName} (${doc?.facebookPageId})` },
598
+ {
599
+ label: "Instagram",
600
+ value: doc?.instagramUsername ? `@${doc.instagramUsername}` : "No Instagram Business account linked to this Page"
601
+ },
602
+ { label: "Catalog", value: doc?.catalogId || "Not chosen yet" },
603
+ { label: "Pixel", value: doc?.pixelId || "Not chosen yet" },
604
+ { label: "WhatsApp", value: doc?.whatsappEnabled && doc?.whatsappPhoneNumberId ? doc.whatsappPhoneNumberId : "Not chosen yet" }
605
+ ]
606
+ }
607
+ ),
608
+ !hasPage && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: stepStyle, children: [
609
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: stepTitle, children: "1. Facebook Page" }),
610
+ pages?.length === 1 && !autoPageFailed ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(LoadingState, { message: "Saving the Page from this Facebook login\u2026" }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
611
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: hintStyle, children: "Pick the Page this site publishes as. Its Instagram account is detected from that Page. Once saved, it stays read-only." }),
612
+ pagePicker
613
+ ] })
614
+ ] }),
615
+ hasPage && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
616
+ assetsError && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorState, { message: assetsError }),
617
+ stepMessage && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SuccessState, { message: stepMessage }),
618
+ catalogs === null ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(LoadingState, { message: "Loading catalogs, Pixels, and WhatsApp numbers\u2026" }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
619
+ !doc?.catalogId && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: stepStyle, children: [
620
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: stepTitle, children: "2. Catalog" }),
621
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: hintStyle, children: "Commerce catalogue items sync to this catalog. Create one if this Facebook login does not have one yet." }),
622
+ businesses.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { marginBottom: "0.75rem" }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
623
+ StyledSelect,
624
+ {
625
+ path: "metaConnectPanel_business",
626
+ value: createBusinessId || businesses[0]?.id || "",
627
+ options: businesses.map((business) => ({ label: business.name, value: business.id })),
628
+ placeholder: "Business that will own a new catalog or Pixel",
629
+ onChange: setCreateBusinessId
630
+ }
631
+ ) }),
632
+ catalogs.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { ...rowStyle, marginBottom: "0.75rem" }, children: [
633
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
634
+ StyledSelect,
635
+ {
636
+ path: "metaConnectPanel_catalog",
637
+ value: selectedCatalogId || doc?.catalogId || "",
638
+ options: catalogs.map((catalog) => ({
639
+ label: `${catalog.name} (${catalog.businessName})`,
640
+ value: catalog.id
641
+ })),
642
+ placeholder: "Select a catalog",
643
+ onChange: setSelectedCatalogId
644
+ }
645
+ ) }),
646
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: () => useCatalog(), disabled: !(selectedCatalogId || doc?.catalogId) || saving, children: "Use this catalog" })
647
+ ] }),
648
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: rowStyle, children: [
649
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
650
+ "input",
651
+ {
652
+ style: nameInputStyle,
653
+ value: newCatalogName,
654
+ placeholder: "New catalog name",
655
+ onChange: (event) => setNewCatalogName(event.target.value)
656
+ }
657
+ ),
658
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: createCatalog, disabled: !newCatalogName.trim() || saving, children: saving ? "Saving\u2026" : "Create catalog" })
659
+ ] })
660
+ ] }),
661
+ !doc?.pixelId && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: stepStyle, children: [
662
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: stepTitle, children: "3. Pixel" }),
663
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: hintStyle, children: "Used for the Conversions API. Create one if this login does not have a Pixel yet." }),
664
+ (pixels ?? []).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { ...rowStyle, marginBottom: "0.75rem" }, children: [
665
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
666
+ StyledSelect,
667
+ {
668
+ path: "metaConnectPanel_pixel",
669
+ value: selectedPixelId || doc?.pixelId || "",
670
+ options: (pixels ?? []).map((pixel) => ({ label: `${pixel.name} (${pixel.id})`, value: pixel.id })),
671
+ placeholder: "Select a Pixel",
672
+ onChange: setSelectedPixelId
673
+ }
674
+ ) }),
675
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: () => usePixel(), disabled: !(selectedPixelId || doc?.pixelId) || saving, children: "Use this Pixel" })
676
+ ] }),
677
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: rowStyle, children: [
678
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
679
+ "input",
680
+ {
681
+ style: nameInputStyle,
682
+ value: newPixelName,
683
+ placeholder: "New Pixel name",
684
+ onChange: (event) => setNewPixelName(event.target.value)
685
+ }
686
+ ),
687
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: createPixel, disabled: !newPixelName.trim() || saving, children: saving ? "Saving\u2026" : "Create Pixel" })
688
+ ] })
689
+ ] }),
690
+ !doc?.whatsappPhoneNumberId && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: stepStyle, children: [
691
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: stepTitle, children: "4. Official WhatsApp" }),
692
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: hintStyle, children: "Choose the number this site sends alerts from. Once saved, it stays read-only. Leave it unset to keep the existing WhatsApp bridge." }),
693
+ numbers === null ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(LoadingState, { message: "Looking up WhatsApp numbers." }) : numbers.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "No WhatsApp Business numbers on this Facebook login. Disconnect, then log in again, if this account should include WhatsApp." }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: rowStyle, children: [
694
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
695
+ StyledSelect,
696
+ {
697
+ path: "metaConnectPanel_whatsapp",
698
+ value: selectedNumberId || doc?.whatsappPhoneNumberId || "",
699
+ options: (numbers ?? []).map((number) => ({
700
+ label: `${number.displayPhone}${number.verifiedName ? ` \xB7 ${number.verifiedName}` : ""} (${number.wabaName})`,
701
+ value: number.id
702
+ })),
703
+ placeholder: "Select a WhatsApp number",
704
+ onChange: setSelectedNumberId
705
+ }
706
+ ) }),
707
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: () => useNumber(), disabled: !(selectedNumberId || doc?.whatsappPhoneNumberId) || saving, children: saving ? "Saving\u2026" : "Use for notifications" })
708
+ ] })
709
+ ] })
710
+ ] })
711
+ ] }),
712
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { ...stepStyle, display: "flex", flexDirection: "column", gap: "0.5rem", alignItems: "flex-start" }, children: [
713
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: hintStyle, children: "Disconnect removes this site\u2019s Facebook login and the Page, catalog, Pixel, and WhatsApp saved from it. You can log in again afterwards." }),
714
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: disconnect, disabled: saving, children: saving ? "Disconnecting\u2026" : "Disconnect" })
715
+ ] })
716
+ ] })
717
+ ] });
718
+ };
719
+ // Annotate the CommonJS export names for ESM import in node:
720
+ 0 && (module.exports = {
721
+ MetaConnectPanelField,
722
+ MetaTenantDefaults
723
+ });