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,142 @@
1
+ // src/components/shared.tsx
2
+ import React from "react";
3
+ import { Button, FieldLabel, SelectInput } from "@payloadcms/ui";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ var fieldWrapperStyle = {
6
+ marginBottom: "1.5rem"
7
+ };
8
+ var descriptionStyle = {
9
+ fontSize: "0.8125rem",
10
+ color: "var(--theme-elevation-500, #6b7280)",
11
+ marginTop: "0.25rem",
12
+ lineHeight: 1.4
13
+ };
14
+ var messageBoxStyle = (variant) => ({
15
+ padding: "0.75rem 1rem",
16
+ borderRadius: "var(--style-radius, 0.25rem)",
17
+ border: "1px solid",
18
+ 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)",
19
+ 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)",
20
+ 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)",
21
+ fontSize: "0.875rem",
22
+ lineHeight: 1.4,
23
+ marginBottom: "0.75rem"
24
+ });
25
+ var FieldWrapper = ({ path, label, description, children }) => /* @__PURE__ */ jsxs("div", { style: fieldWrapperStyle, children: [
26
+ label && /* @__PURE__ */ jsx(FieldLabel, { label, path }),
27
+ children,
28
+ description && /* @__PURE__ */ jsx("div", { style: descriptionStyle, children: description })
29
+ ] });
30
+ var LoadingState = ({ message }) => /* @__PURE__ */ jsxs("div", { style: messageBoxStyle("info"), children: [
31
+ "\u23F3 ",
32
+ message
33
+ ] });
34
+ var EmptyState = ({ message }) => /* @__PURE__ */ jsx("div", { style: messageBoxStyle("info"), children: message });
35
+ var ErrorState = ({ message }) => /* @__PURE__ */ jsxs("div", { style: messageBoxStyle("error"), children: [
36
+ "\u26A0\uFE0F ",
37
+ message
38
+ ] });
39
+ var SuccessState = ({ message }) => /* @__PURE__ */ jsxs("div", { style: messageBoxStyle("success"), children: [
40
+ "\u2705 ",
41
+ message
42
+ ] });
43
+ var ConnectButton = ({ onClick, disabled, children }) => /* @__PURE__ */ jsx(Button, { type: "button", buttonStyle: "primary", size: "medium", disabled, onClick, children });
44
+ var StyledSelect = ({
45
+ path,
46
+ value,
47
+ options,
48
+ placeholder = "Select an option",
49
+ onChange
50
+ }) => /* @__PURE__ */ jsx(
51
+ SelectInput,
52
+ {
53
+ path,
54
+ name: path,
55
+ value,
56
+ onChange: (option) => {
57
+ const selected = Array.isArray(option) ? option[0] : option;
58
+ onChange(selected?.value != null ? String(selected.value) : "");
59
+ },
60
+ options: [{ label: `\u2014 ${placeholder} \u2014`, value: "" }, ...options]
61
+ }
62
+ );
63
+ function useMetaAppInfo() {
64
+ const [state, setState] = React.useState({ configured: false, maskedAppId: null, loading: true });
65
+ React.useEffect(() => {
66
+ 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 }));
67
+ }, []);
68
+ return state;
69
+ }
70
+ var MetaAppInfoBadge = ({ appInfo }) => {
71
+ if (appInfo.loading) return null;
72
+ if (!appInfo.configured) {
73
+ return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 an admin needs to set META_APP_ID and META_APP_SECRET." });
74
+ }
75
+ return /* @__PURE__ */ jsxs("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
76
+ /* @__PURE__ */ jsx("span", { children: "Platform Meta App" }),
77
+ /* @__PURE__ */ jsx("code", { children: appInfo.maskedAppId })
78
+ ] });
79
+ };
80
+ var DetailList = ({ items }) => /* @__PURE__ */ 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__ */ jsxs(React.Fragment, { children: [
81
+ /* @__PURE__ */ jsx("span", { style: { color: "var(--theme-elevation-500, #6b7280)" }, children: item.label }),
82
+ /* @__PURE__ */ jsx("span", { children: item.value })
83
+ ] }, item.label)) });
84
+ var META_OAUTH_MESSAGE_SOURCE = "payload-meta-oauth";
85
+ function openMetaOAuthPopup(url, onResult) {
86
+ const popup = window.open(url, "payload-meta-oauth", "popup=yes,width=520,height=720");
87
+ if (!popup) {
88
+ window.location.assign(url.replace(/([?&])popup=1\b/, "$1popup=0"));
89
+ return;
90
+ }
91
+ let settled = false;
92
+ const finish = (result) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ window.removeEventListener("message", onMessage);
96
+ window.clearInterval(timer);
97
+ onResult(result);
98
+ };
99
+ const onMessage = (event) => {
100
+ if (event.origin !== window.location.origin) return;
101
+ const data = event.data;
102
+ if (!data || data.source !== META_OAUTH_MESSAGE_SOURCE) return;
103
+ finish({ ok: Boolean(data.ok), error: data.error ? String(data.error) : null });
104
+ };
105
+ window.addEventListener("message", onMessage);
106
+ const timer = window.setInterval(() => {
107
+ if (popup.closed) finish({ ok: false, error: null });
108
+ }, 400);
109
+ }
110
+ function useOAuthRedirectMessage(successParam, errorParam) {
111
+ const [state, setState] = React.useState({ success: false, error: null });
112
+ React.useEffect(() => {
113
+ if (typeof window === "undefined") return;
114
+ const params = new URLSearchParams(window.location.search);
115
+ const success = params.get(successParam) === "1";
116
+ const error = params.get(errorParam);
117
+ if (success || error) {
118
+ setState({ success, error });
119
+ params.delete(successParam);
120
+ params.delete(errorParam);
121
+ const newSearch = params.toString();
122
+ const newUrl = `${window.location.pathname}${newSearch ? `?${newSearch}` : ""}`;
123
+ window.history.replaceState({}, "", newUrl);
124
+ }
125
+ }, []);
126
+ return state;
127
+ }
128
+
129
+ export {
130
+ FieldWrapper,
131
+ LoadingState,
132
+ EmptyState,
133
+ ErrorState,
134
+ SuccessState,
135
+ ConnectButton,
136
+ StyledSelect,
137
+ useMetaAppInfo,
138
+ MetaAppInfoBadge,
139
+ DetailList,
140
+ openMetaOAuthPopup,
141
+ useOAuthRedirectMessage
142
+ };
@@ -0,0 +1,26 @@
1
+ // src/oauth/clearedConnection.ts
2
+ function clearedMetaUserConnection() {
3
+ return {
4
+ accessToken: null,
5
+ oauthUserAccessToken: null,
6
+ oauthExpiresAt: null,
7
+ facebookPageId: null,
8
+ facebookPageName: null,
9
+ instagramBusinessAccountId: null,
10
+ instagramUsername: null,
11
+ businessManagerId: null,
12
+ pixelId: null,
13
+ pixelEnabled: false,
14
+ catalogId: null,
15
+ catalogEnabled: false,
16
+ whatsappPhoneNumberId: null,
17
+ whatsappBusinessAccountId: null,
18
+ whatsappEnabled: false,
19
+ authMethod: "manual",
20
+ connectionStatus: "disconnected"
21
+ };
22
+ }
23
+
24
+ export {
25
+ clearedMetaUserConnection
26
+ };
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Commerce catalog controls for one site. The Facebook account that connected
5
+ * this site is the only account whose catalogs are listed. Saving a catalogue
6
+ * item also pushes that item; this button sends the whole catalogue.
7
+ */
8
+ declare const MetaCatalogSyncField: React.FC;
9
+
10
+ export { MetaCatalogSyncField };
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Commerce catalog controls for one site. The Facebook account that connected
5
+ * this site is the only account whose catalogs are listed. Saving a catalogue
6
+ * item also pushes that item; this button sends the whole catalogue.
7
+ */
8
+ declare const MetaCatalogSyncField: React.FC;
9
+
10
+ export { MetaCatalogSyncField };
@@ -0,0 +1,195 @@
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/MetaCatalogSync/index.tsx
32
+ var MetaCatalogSync_exports = {};
33
+ __export(MetaCatalogSync_exports, {
34
+ MetaCatalogSyncField: () => MetaCatalogSyncField
35
+ });
36
+ module.exports = __toCommonJS(MetaCatalogSync_exports);
37
+ var import_react2 = require("react");
38
+ var import_ui2 = require("@payloadcms/ui");
39
+
40
+ // src/components/shared.tsx
41
+ var import_react = __toESM(require("react"));
42
+ var import_ui = require("@payloadcms/ui");
43
+ var import_jsx_runtime = require("react/jsx-runtime");
44
+ var fieldWrapperStyle = {
45
+ marginBottom: "1.5rem"
46
+ };
47
+ var descriptionStyle = {
48
+ fontSize: "0.8125rem",
49
+ color: "var(--theme-elevation-500, #6b7280)",
50
+ marginTop: "0.25rem",
51
+ lineHeight: 1.4
52
+ };
53
+ var messageBoxStyle = (variant) => ({
54
+ padding: "0.75rem 1rem",
55
+ borderRadius: "var(--style-radius, 0.25rem)",
56
+ border: "1px solid",
57
+ 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)",
58
+ 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)",
59
+ 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)",
60
+ fontSize: "0.875rem",
61
+ lineHeight: 1.4,
62
+ marginBottom: "0.75rem"
63
+ });
64
+ var FieldWrapper = ({ path, label, description, children }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: fieldWrapperStyle, children: [
65
+ label && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui.FieldLabel, { label, path }),
66
+ children,
67
+ description && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: descriptionStyle, children: description })
68
+ ] });
69
+ var EmptyState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: messageBoxStyle("info"), children: message });
70
+ var ErrorState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: messageBoxStyle("error"), children: [
71
+ "\u26A0\uFE0F ",
72
+ message
73
+ ] });
74
+ var SuccessState = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: messageBoxStyle("success"), children: [
75
+ "\u2705 ",
76
+ message
77
+ ] });
78
+ var ConnectButton = ({ onClick, disabled, children }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui.Button, { type: "button", buttonStyle: "primary", size: "medium", disabled, onClick, children });
79
+ var StyledSelect = ({
80
+ path,
81
+ value,
82
+ options,
83
+ placeholder = "Select an option",
84
+ onChange
85
+ }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
86
+ import_ui.SelectInput,
87
+ {
88
+ path,
89
+ name: path,
90
+ value,
91
+ onChange: (option) => {
92
+ const selected = Array.isArray(option) ? option[0] : option;
93
+ onChange(selected?.value != null ? String(selected.value) : "");
94
+ },
95
+ options: [{ label: `\u2014 ${placeholder} \u2014`, value: "" }, ...options]
96
+ }
97
+ );
98
+
99
+ // src/components/MetaCatalogSync/index.tsx
100
+ var import_jsx_runtime2 = require("react/jsx-runtime");
101
+ var MetaCatalogSyncField = () => {
102
+ const { id } = (0, import_ui2.useDocumentInfo)();
103
+ const { dispatchFields } = (0, import_ui2.useForm)();
104
+ const catalogEnabled = (0, import_ui2.useFormFields)(([fields]) => Boolean(fields.catalogEnabled?.value));
105
+ const sourceCollection = (0, import_ui2.useFormFields)(([fields]) => fields.catalogSourceCollection?.value);
106
+ const [catalogs, setCatalogs] = (0, import_react2.useState)(null);
107
+ const [selected, setSelected] = (0, import_react2.useState)("");
108
+ const [loading, setLoading] = (0, import_react2.useState)(false);
109
+ const [syncing, setSyncing] = (0, import_react2.useState)(false);
110
+ const [error, setError] = (0, import_react2.useState)(null);
111
+ const [message, setMessage] = (0, import_react2.useState)(null);
112
+ const loadCatalogs = (0, import_react2.useCallback)(() => {
113
+ if (!id) return;
114
+ setLoading(true);
115
+ setError(null);
116
+ fetch(`/api/meta-catalog/catalogs?configId=${id}`).then((res) => res.json()).then((data) => {
117
+ if (data.error) {
118
+ setError(data.error);
119
+ return;
120
+ }
121
+ setCatalogs(data.catalogs ?? []);
122
+ }).catch(() => setError("Failed to load catalogs from the connected Facebook account")).finally(() => setLoading(false));
123
+ }, [id]);
124
+ const useCatalog = () => {
125
+ if (!id || !selected) return;
126
+ const catalog = catalogs?.find((item) => item.id === selected);
127
+ if (!catalog) return;
128
+ setSyncing(true);
129
+ setError(null);
130
+ fetch("/api/meta-catalog/select", {
131
+ method: "POST",
132
+ headers: { "Content-Type": "application/json" },
133
+ body: JSON.stringify({ configId: id, catalogId: catalog.id, businessId: catalog.businessId })
134
+ }).then((res) => res.json()).then((data) => {
135
+ if (data.error) {
136
+ setError(data.error);
137
+ return;
138
+ }
139
+ dispatchFields({ type: "UPDATE", path: "catalogEnabled", value: true });
140
+ dispatchFields({ type: "UPDATE", path: "catalogId", value: catalog.id });
141
+ dispatchFields({ type: "UPDATE", path: "businessManagerId", value: catalog.businessId });
142
+ if (!sourceCollection) {
143
+ dispatchFields({ type: "UPDATE", path: "catalogSourceCollection", value: "catalogue-items" });
144
+ }
145
+ setMessage(`This site will sync commerce products to \u201C${catalog.name}\u201D. Save the document after you set the product link template.`);
146
+ }).catch(() => setError("Failed to save the catalog")).finally(() => setSyncing(false));
147
+ };
148
+ const syncNow = () => {
149
+ if (!id) return;
150
+ setSyncing(true);
151
+ setError(null);
152
+ setMessage(null);
153
+ fetch("/api/meta-catalog/sync", {
154
+ method: "POST",
155
+ headers: { "Content-Type": "application/json" },
156
+ body: JSON.stringify({ configId: id })
157
+ }).then((res) => res.json()).then((data) => {
158
+ if (data.error) {
159
+ setError(data.error);
160
+ return;
161
+ }
162
+ const problems = Array.isArray(data.errors) && data.errors.length ? ` ${data.errors[0]}` : "";
163
+ setMessage(`Sent ${data.synced} product${data.synced === 1 ? "" : "s"} to Meta. ${data.skipped} skipped (no title, price, or link).${problems}`);
164
+ }).catch(() => setError("Product sync failed")).finally(() => setSyncing(false));
165
+ };
166
+ if (!id) {
167
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(FieldWrapper, { path: "metaCatalogSyncPanel", label: "Sync products", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "Save this connection first." }) });
168
+ }
169
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(FieldWrapper, { path: "metaCatalogSyncPanel", label: "Sync products", children: [
170
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: { fontSize: "0.8125rem", lineHeight: 1.45, marginTop: 0 }, children: "Uses the Facebook login that connected this site. Commerce catalogue items are sent to the chosen catalog when they are saved, and when you sync the whole catalogue here." }),
171
+ error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorState, { message: error }),
172
+ message && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SuccessState, { message }),
173
+ catalogs === null ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: loadCatalogs, disabled: loading, children: loading ? "Loading catalogs\u2026" : "Load catalogs from my Facebook" }) : catalogs.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmptyState, { message: "No product catalogs on this Facebook account. Create one in Meta Commerce Manager, then load again." }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "flex", gap: "0.75rem", alignItems: "flex-end" }, children: [
174
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
175
+ StyledSelect,
176
+ {
177
+ path: "metaCatalogSyncPanel_catalog",
178
+ value: selected,
179
+ options: catalogs.map((catalog) => ({
180
+ label: `${catalog.name} (${catalog.businessName})`,
181
+ value: catalog.id
182
+ })),
183
+ placeholder: "Select a catalog",
184
+ onChange: setSelected
185
+ }
186
+ ) }),
187
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: useCatalog, disabled: !selected || syncing, children: "Use this catalog" })
188
+ ] }),
189
+ catalogEnabled && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { marginTop: "0.75rem" }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectButton, { onClick: syncNow, disabled: syncing, children: syncing ? "Syncing\u2026" : "Sync commerce products now" }) })
190
+ ] });
191
+ };
192
+ // Annotate the CommonJS export names for ESM import in node:
193
+ 0 && (module.exports = {
194
+ MetaCatalogSyncField
195
+ });
@@ -0,0 +1,108 @@
1
+ "use client";
2
+ import {
3
+ ConnectButton,
4
+ EmptyState,
5
+ ErrorState,
6
+ FieldWrapper,
7
+ StyledSelect,
8
+ SuccessState
9
+ } from "../../chunk-HCQSD757.mjs";
10
+
11
+ // src/components/MetaCatalogSync/index.tsx
12
+ import { useCallback, useState } from "react";
13
+ import { useDocumentInfo, useForm, useFormFields } from "@payloadcms/ui";
14
+ import { jsx, jsxs } from "react/jsx-runtime";
15
+ var MetaCatalogSyncField = () => {
16
+ const { id } = useDocumentInfo();
17
+ const { dispatchFields } = useForm();
18
+ const catalogEnabled = useFormFields(([fields]) => Boolean(fields.catalogEnabled?.value));
19
+ const sourceCollection = useFormFields(([fields]) => fields.catalogSourceCollection?.value);
20
+ const [catalogs, setCatalogs] = useState(null);
21
+ const [selected, setSelected] = useState("");
22
+ const [loading, setLoading] = useState(false);
23
+ const [syncing, setSyncing] = useState(false);
24
+ const [error, setError] = useState(null);
25
+ const [message, setMessage] = useState(null);
26
+ const loadCatalogs = useCallback(() => {
27
+ if (!id) return;
28
+ setLoading(true);
29
+ setError(null);
30
+ fetch(`/api/meta-catalog/catalogs?configId=${id}`).then((res) => res.json()).then((data) => {
31
+ if (data.error) {
32
+ setError(data.error);
33
+ return;
34
+ }
35
+ setCatalogs(data.catalogs ?? []);
36
+ }).catch(() => setError("Failed to load catalogs from the connected Facebook account")).finally(() => setLoading(false));
37
+ }, [id]);
38
+ const useCatalog = () => {
39
+ if (!id || !selected) return;
40
+ const catalog = catalogs?.find((item) => item.id === selected);
41
+ if (!catalog) return;
42
+ setSyncing(true);
43
+ setError(null);
44
+ fetch("/api/meta-catalog/select", {
45
+ method: "POST",
46
+ headers: { "Content-Type": "application/json" },
47
+ body: JSON.stringify({ configId: id, catalogId: catalog.id, businessId: catalog.businessId })
48
+ }).then((res) => res.json()).then((data) => {
49
+ if (data.error) {
50
+ setError(data.error);
51
+ return;
52
+ }
53
+ dispatchFields({ type: "UPDATE", path: "catalogEnabled", value: true });
54
+ dispatchFields({ type: "UPDATE", path: "catalogId", value: catalog.id });
55
+ dispatchFields({ type: "UPDATE", path: "businessManagerId", value: catalog.businessId });
56
+ if (!sourceCollection) {
57
+ dispatchFields({ type: "UPDATE", path: "catalogSourceCollection", value: "catalogue-items" });
58
+ }
59
+ setMessage(`This site will sync commerce products to \u201C${catalog.name}\u201D. Save the document after you set the product link template.`);
60
+ }).catch(() => setError("Failed to save the catalog")).finally(() => setSyncing(false));
61
+ };
62
+ const syncNow = () => {
63
+ if (!id) return;
64
+ setSyncing(true);
65
+ setError(null);
66
+ setMessage(null);
67
+ fetch("/api/meta-catalog/sync", {
68
+ method: "POST",
69
+ headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify({ configId: id })
71
+ }).then((res) => res.json()).then((data) => {
72
+ if (data.error) {
73
+ setError(data.error);
74
+ return;
75
+ }
76
+ const problems = Array.isArray(data.errors) && data.errors.length ? ` ${data.errors[0]}` : "";
77
+ setMessage(`Sent ${data.synced} product${data.synced === 1 ? "" : "s"} to Meta. ${data.skipped} skipped (no title, price, or link).${problems}`);
78
+ }).catch(() => setError("Product sync failed")).finally(() => setSyncing(false));
79
+ };
80
+ if (!id) {
81
+ return /* @__PURE__ */ jsx(FieldWrapper, { path: "metaCatalogSyncPanel", label: "Sync products", children: /* @__PURE__ */ jsx(EmptyState, { message: "Save this connection first." }) });
82
+ }
83
+ return /* @__PURE__ */ jsxs(FieldWrapper, { path: "metaCatalogSyncPanel", label: "Sync products", children: [
84
+ /* @__PURE__ */ jsx("p", { style: { fontSize: "0.8125rem", lineHeight: 1.45, marginTop: 0 }, children: "Uses the Facebook login that connected this site. Commerce catalogue items are sent to the chosen catalog when they are saved, and when you sync the whole catalogue here." }),
85
+ error && /* @__PURE__ */ jsx(ErrorState, { message: error }),
86
+ message && /* @__PURE__ */ jsx(SuccessState, { message }),
87
+ catalogs === null ? /* @__PURE__ */ jsx(ConnectButton, { onClick: loadCatalogs, disabled: loading, children: loading ? "Loading catalogs\u2026" : "Load catalogs from my Facebook" }) : catalogs.length === 0 ? /* @__PURE__ */ jsx(EmptyState, { message: "No product catalogs on this Facebook account. Create one in Meta Commerce Manager, then load again." }) : /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "0.75rem", alignItems: "flex-end" }, children: [
88
+ /* @__PURE__ */ jsx("div", { style: { flex: 1 }, children: /* @__PURE__ */ jsx(
89
+ StyledSelect,
90
+ {
91
+ path: "metaCatalogSyncPanel_catalog",
92
+ value: selected,
93
+ options: catalogs.map((catalog) => ({
94
+ label: `${catalog.name} (${catalog.businessName})`,
95
+ value: catalog.id
96
+ })),
97
+ placeholder: "Select a catalog",
98
+ onChange: setSelected
99
+ }
100
+ ) }),
101
+ /* @__PURE__ */ jsx(ConnectButton, { onClick: useCatalog, disabled: !selected || syncing, children: "Use this catalog" })
102
+ ] }),
103
+ catalogEnabled && /* @__PURE__ */ jsx("div", { style: { marginTop: "0.75rem" }, children: /* @__PURE__ */ jsx(ConnectButton, { onClick: syncNow, disabled: syncing, children: syncing ? "Syncing\u2026" : "Sync commerce products now" }) })
104
+ ] });
105
+ };
106
+ export {
107
+ MetaCatalogSyncField
108
+ };
@@ -0,0 +1,20 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Fills the Organization and Site dropdowns from the person who is signed in.
5
+ * An editor has one site. An organization admin with one site gets that site.
6
+ * The organization is chosen first. Changing it clears a site that belongs to
7
+ * another organization. Choosing a site still confirms the organization that
8
+ * owns that site.
9
+ */
10
+ declare const MetaTenantDefaults: React.FC;
11
+
12
+ /**
13
+ * After Continue with Facebook, this site's login picks a Page, a catalog
14
+ * (or creates one), a Pixel (or creates one), and an official WhatsApp
15
+ * number. Payload notifications use that number. The OpenWA bridge is left
16
+ * in place for sites that do not turn official WhatsApp on.
17
+ */
18
+ declare const MetaConnectPanelField: React.FC;
19
+
20
+ export { MetaConnectPanelField, MetaTenantDefaults };
@@ -0,0 +1,20 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Fills the Organization and Site dropdowns from the person who is signed in.
5
+ * An editor has one site. An organization admin with one site gets that site.
6
+ * The organization is chosen first. Changing it clears a site that belongs to
7
+ * another organization. Choosing a site still confirms the organization that
8
+ * owns that site.
9
+ */
10
+ declare const MetaTenantDefaults: React.FC;
11
+
12
+ /**
13
+ * After Continue with Facebook, this site's login picks a Page, a catalog
14
+ * (or creates one), a Pixel (or creates one), and an official WhatsApp
15
+ * number. Payload notifications use that number. The OpenWA bridge is left
16
+ * in place for sites that do not turn official WhatsApp on.
17
+ */
18
+ declare const MetaConnectPanelField: React.FC;
19
+
20
+ export { MetaConnectPanelField, MetaTenantDefaults };