opscms-meta-plugin 0.6.1 → 0.7.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Added
6
+
7
+ - **A catalogue item's page address can use the slug of its category: `{category.slug}`.** A shop whose pages are one per category, with the items sizes of it (AvrilBeetails: `/adun/<flavour>`), has no
8
+ slug on its items, so `{slug}` gave every link the item's number and a page that does not exist. The template may now be `https://avrilbeetails.com/adun/{category.slug}`. Both `{slug}` and
9
+ `{category.slug}` may be used together. An item whose category has no slug is left out of the sync and the feed (with a link that leads nowhere Meta would only warn).
10
+
11
+ ### Changed
12
+
13
+ - **A failed call to Meta says what to do.** Meta's own message for a person is shown when it gives one, and a Pixel that cannot be created because the business has not accepted Meta's Pixel
14
+ terms (error 10, subcode 1784018: "Application does not have permission for this action") says so and where to accept them. A failed Pixel creation is also written to the log.
15
+
3
16
  ## 0.6.1
4
17
 
5
18
  ### Fixed
package/README.md CHANGED
@@ -233,7 +233,7 @@ Generic by design: reads whichever collection `catalogSourceCollection` designat
233
233
  | `description` | `description`, `excerpt`, `body` (HTML stripped) |
234
234
  | `price` | `price`, `price_from`, `priceFrom` |
235
235
  | `image_link` | `image`, `featuredImage`, `photo` (resolved to an absolute URL) |
236
- | `link` | `catalogItemUrlTemplate` with `{slug}` substituted |
236
+ | `link` | `catalogItemUrlTemplate` with `{slug}` (the item's slug, else its number) and/or `{category.slug}` (the slug of the item's category) substituted; an item whose `{category.slug}` cannot be filled is left out |
237
237
 
238
238
  Items missing a `title` or `price` are skipped rather than emitted as invalid rows — Meta rejects the whole feed on malformed entries, so a few incomplete source documents shouldn't take down catalog sync for everything else.
239
239
 
package/dist/index.js CHANGED
@@ -769,7 +769,7 @@ var MetaConfig = {
769
769
  name: "catalogItemUrlTemplate",
770
770
  type: "text",
771
771
  admin: {
772
- description: 'Item page URL template on the live site \u2014 "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}. Required before products can sync (Meta rejects an item with no link).',
772
+ description: `Item page URL template on the live site. "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}; "{category.slug}" by the slug of the item's category, for a shop with one page per category whose items are sizes of it, e.g. https://avrilbeetails.com/adun/{category.slug}. Required before products can sync (Meta rejects an item with no link).`,
773
773
  condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
774
774
  }
775
775
  },
@@ -910,6 +910,104 @@ var MetaConfig = {
910
910
  timestamps: true
911
911
  };
912
912
 
913
+ // src/sync/catalogProduct.ts
914
+ var COMMERCE_COLLECTION = "catalogue-items";
915
+ function firstDefined(...values) {
916
+ for (const value of values) {
917
+ if (value !== void 0 && value !== null && value !== "") return value;
918
+ }
919
+ return void 0;
920
+ }
921
+ function plainText(value) {
922
+ if (typeof value === "string") return value;
923
+ if (typeof value === "number") return String(value);
924
+ if (value && typeof value === "object") {
925
+ const record = value;
926
+ for (const entry of Object.values(record)) {
927
+ if (typeof entry === "string" && entry.trim()) return entry;
928
+ }
929
+ }
930
+ return "";
931
+ }
932
+ function stripHtml(input) {
933
+ return input.replace(/<[^>]+>/g, "").trim();
934
+ }
935
+ function resolveImageUrl(media, serverUrl4) {
936
+ if (!media) return "";
937
+ if (typeof media === "string") {
938
+ if (media.startsWith("http://") || media.startsWith("https://")) return media;
939
+ return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
940
+ }
941
+ if (typeof media === "object") {
942
+ const record = media;
943
+ const url = typeof record.url === "string" ? record.url : "";
944
+ if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
945
+ const filename = typeof record.filename === "string" ? record.filename : "";
946
+ if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
947
+ }
948
+ return "";
949
+ }
950
+ function relationId2(value) {
951
+ if (typeof value === "string" || typeof value === "number") return value;
952
+ if (value && typeof value === "object" && "id" in value) {
953
+ const id = value.id;
954
+ if (typeof id === "string" || typeof id === "number") return id;
955
+ }
956
+ return void 0;
957
+ }
958
+ function catalogSourceSlug(configured) {
959
+ const slug = typeof configured === "string" ? configured.trim() : "";
960
+ return slug || COMMERCE_COLLECTION;
961
+ }
962
+ var URL_TEMPLATE_PLACEHOLDERS = ["{slug}", "{category.slug}"];
963
+ function hasUrlPlaceholder(template) {
964
+ return URL_TEMPLATE_PLACEHOLDERS.some((placeholder) => template.includes(placeholder));
965
+ }
966
+ function itemLink(doc, template) {
967
+ let link = template.trim();
968
+ if (!hasUrlPlaceholder(link)) return null;
969
+ if (link.includes("{category.slug}")) {
970
+ const category = doc.category;
971
+ const categorySlug = category && typeof category === "object" ? plainText(category.slug).trim() : "";
972
+ if (!categorySlug) return null;
973
+ link = link.split("{category.slug}").join(encodeURIComponent(categorySlug));
974
+ }
975
+ if (link.includes("{slug}")) link = link.split("{slug}").join(encodeURIComponent(plainText(firstDefined(doc.slug, doc.id))));
976
+ return link;
977
+ }
978
+ function toCatalogItem(doc, options) {
979
+ const title = plainText(firstDefined(doc.title, doc.name, doc.heading)).trim();
980
+ const price = firstDefined(doc.price, doc.price_from, doc.priceFrom);
981
+ if (!title || price === void 0 || price === null || price === "") return null;
982
+ const amount = Number(price);
983
+ if (!Number.isFinite(amount)) return null;
984
+ const link = itemLink(doc, options.urlTemplate);
985
+ if (!link) return null;
986
+ const rawDescription = firstDefined(doc.description, doc.excerpt, doc.body);
987
+ const description = rawDescription ? stripHtml(plainText(rawDescription)).slice(0, 5e3) : title;
988
+ const available = doc.available === void 0 ? true : Boolean(doc.available);
989
+ const currency = (options.currency || "NGN").toUpperCase();
990
+ const image = resolveImageUrl(firstDefined(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
991
+ const item = {
992
+ id: String(doc.id),
993
+ title,
994
+ description,
995
+ availability: available ? "in stock" : "out of stock",
996
+ condition: "new",
997
+ price: `${amount.toFixed(2)} ${currency}`,
998
+ link
999
+ };
1000
+ if (image) item.image_link = image;
1001
+ if (options.brand) item.brand = options.brand;
1002
+ return item;
1003
+ }
1004
+ function updateRequest(item) {
1005
+ return { method: "UPDATE", data: item };
1006
+ }
1007
+ function deleteRequest(retailerId) {
1008
+ return { method: "DELETE", data: { id: retailerId } };
1009
+ }
1010
+
913
1011
  // src/endpoints/metaCatalogFeed.ts
914
1012
  function csvEscape(value) {
915
1013
  const str = value === null || value === void 0 ? "" : String(value);
@@ -918,16 +1016,16 @@ function csvEscape(value) {
918
1016
  }
919
1017
  return str;
920
1018
  }
921
- function firstDefined(...values) {
1019
+ function firstDefined2(...values) {
922
1020
  for (const v of values) {
923
1021
  if (v !== void 0 && v !== null && v !== "") return v;
924
1022
  }
925
1023
  return void 0;
926
1024
  }
927
- function stripHtml(input) {
1025
+ function stripHtml2(input) {
928
1026
  return input.replace(/<[^>]+>/g, "").trim();
929
1027
  }
930
- function resolveImageUrl(media, serverUrl4) {
1028
+ function resolveImageUrl2(media, serverUrl4) {
931
1029
  if (!media) return "";
932
1030
  if (typeof media === "string") {
933
1031
  if (media.startsWith("http://") || media.startsWith("https://")) return media;
@@ -999,16 +1097,15 @@ var metaCatalogFeedEndpoint = {
999
1097
  const rows = [header.join(",")];
1000
1098
  for (const item of items) {
1001
1099
  const id = String(item.id);
1002
- const title = String(firstDefined(item.title, item.name, item.heading) ?? "");
1003
- const rawDescription = firstDefined(item.description, item.excerpt, item.body);
1004
- const description = rawDescription ? stripHtml(String(rawDescription)).slice(0, 5e3) : "";
1005
- const price = firstDefined(item.price, item.price_from, item.priceFrom);
1100
+ const title = String(firstDefined2(item.title, item.name, item.heading) ?? "");
1101
+ const rawDescription = firstDefined2(item.description, item.excerpt, item.body);
1102
+ const description = rawDescription ? stripHtml2(String(rawDescription)).slice(0, 5e3) : "";
1103
+ const price = firstDefined2(item.price, item.price_from, item.priceFrom);
1006
1104
  const available = item.available === void 0 ? true : Boolean(item.available);
1007
- const slug = String(firstDefined(item.slug, item.id));
1008
- const link = urlTemplate.replace("{slug}", encodeURIComponent(slug));
1009
- const image = firstDefined(item.image, item.featuredImage, item.photo);
1010
- const imageLink = resolveImageUrl(image, serverUrl4);
1011
- if (!title || price === void 0) continue;
1105
+ const link = itemLink(item, urlTemplate);
1106
+ const image = firstDefined2(item.image, item.featuredImage, item.photo);
1107
+ const imageLink = resolveImageUrl2(image, serverUrl4);
1108
+ if (!title || price === void 0 || !link) continue;
1012
1109
  rows.push([
1013
1110
  csvEscape(id),
1014
1111
  csvEscape(title),
@@ -1204,10 +1301,21 @@ var BASE_DELAY_MS = 800;
1204
1301
  function sleep(ms) {
1205
1302
  return new Promise((resolve) => setTimeout(resolve, ms));
1206
1303
  }
1304
+ var KNOWN_SUBCODES = {
1305
+ 1784018: "This business has not accepted Meta's Pixel terms. Open Events Manager for the business, start connecting a Web data source, accept the terms, then try again (or create the Pixel there and choose it here)."
1306
+ };
1307
+ function explainGraphError(body) {
1308
+ const error = body?.error;
1309
+ if (!error) return null;
1310
+ if (error.error_subcode && KNOWN_SUBCODES[error.error_subcode]) return KNOWN_SUBCODES[error.error_subcode];
1311
+ if (error.error_user_msg) return error.error_user_title ? `${error.error_user_title}: ${error.error_user_msg}` : error.error_user_msg;
1312
+ return error.message ?? null;
1313
+ }
1207
1314
  async function parseGraphError(res) {
1208
1315
  try {
1209
1316
  const body = await res.json();
1210
- if (body?.error?.message) return body.error.message;
1317
+ const said = explainGraphError(body);
1318
+ if (said) return said;
1211
1319
  } catch {
1212
1320
  }
1213
1321
  return `Graph API error: ${res.status}`;
@@ -1334,89 +1442,6 @@ function oauthPopupResponse(args) {
1334
1442
  });
1335
1443
  }
1336
1444
 
1337
- // src/sync/catalogProduct.ts
1338
- var COMMERCE_COLLECTION = "catalogue-items";
1339
- function firstDefined2(...values) {
1340
- for (const value of values) {
1341
- if (value !== void 0 && value !== null && value !== "") return value;
1342
- }
1343
- return void 0;
1344
- }
1345
- function plainText(value) {
1346
- if (typeof value === "string") return value;
1347
- if (typeof value === "number") return String(value);
1348
- if (value && typeof value === "object") {
1349
- const record = value;
1350
- for (const entry of Object.values(record)) {
1351
- if (typeof entry === "string" && entry.trim()) return entry;
1352
- }
1353
- }
1354
- return "";
1355
- }
1356
- function stripHtml2(input) {
1357
- return input.replace(/<[^>]+>/g, "").trim();
1358
- }
1359
- function resolveImageUrl2(media, serverUrl4) {
1360
- if (!media) return "";
1361
- if (typeof media === "string") {
1362
- if (media.startsWith("http://") || media.startsWith("https://")) return media;
1363
- return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
1364
- }
1365
- if (typeof media === "object") {
1366
- const record = media;
1367
- const url = typeof record.url === "string" ? record.url : "";
1368
- if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
1369
- const filename = typeof record.filename === "string" ? record.filename : "";
1370
- if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
1371
- }
1372
- return "";
1373
- }
1374
- function relationId2(value) {
1375
- if (typeof value === "string" || typeof value === "number") return value;
1376
- if (value && typeof value === "object" && "id" in value) {
1377
- const id = value.id;
1378
- if (typeof id === "string" || typeof id === "number") return id;
1379
- }
1380
- return void 0;
1381
- }
1382
- function catalogSourceSlug(configured) {
1383
- const slug = typeof configured === "string" ? configured.trim() : "";
1384
- return slug || COMMERCE_COLLECTION;
1385
- }
1386
- function toCatalogItem(doc, options) {
1387
- const title = plainText(firstDefined2(doc.title, doc.name, doc.heading)).trim();
1388
- const price = firstDefined2(doc.price, doc.price_from, doc.priceFrom);
1389
- if (!title || price === void 0 || price === null || price === "") return null;
1390
- const amount = Number(price);
1391
- if (!Number.isFinite(amount)) return null;
1392
- const slug = plainText(firstDefined2(doc.slug, doc.id));
1393
- const template = options.urlTemplate.trim();
1394
- if (!template.includes("{slug}")) return null;
1395
- const rawDescription = firstDefined2(doc.description, doc.excerpt, doc.body);
1396
- const description = rawDescription ? stripHtml2(plainText(rawDescription)).slice(0, 5e3) : title;
1397
- const available = doc.available === void 0 ? true : Boolean(doc.available);
1398
- const currency = (options.currency || "NGN").toUpperCase();
1399
- const image = resolveImageUrl2(firstDefined2(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
1400
- const item = {
1401
- id: String(doc.id),
1402
- title,
1403
- description,
1404
- availability: available ? "in stock" : "out of stock",
1405
- condition: "new",
1406
- price: `${amount.toFixed(2)} ${currency}`,
1407
- link: template.replace("{slug}", encodeURIComponent(slug))
1408
- };
1409
- if (image) item.image_link = image;
1410
- if (options.brand) item.brand = options.brand;
1411
- return item;
1412
- }
1413
- function updateRequest(item) {
1414
- return { method: "UPDATE", data: item };
1415
- }
1416
- function deleteRequest(retailerId) {
1417
- return { method: "DELETE", data: { id: retailerId } };
1418
- }
1419
-
1420
1445
  // src/sync/catalogSync.ts
1421
1446
  function decryptToken(value) {
1422
1447
  if (typeof value !== "string" || !value || value.includes("\u2022")) return "";
@@ -1469,14 +1494,26 @@ async function pushBatch(catalogId, token, requests) {
1469
1494
  const messages = (result.data?.validation_status ?? []).flatMap((row) => row.errors ?? []).map((error) => error.message).filter((message) => Boolean(message));
1470
1495
  return messages.length ? messages.join("; ") : null;
1471
1496
  }
1497
+ async function withCategoryRead(payload, doc, template) {
1498
+ if (!template.includes("{category.slug}")) return doc;
1499
+ const category = doc.category;
1500
+ if (category == null || typeof category === "object") return doc;
1501
+ try {
1502
+ const read = await payload.findByID({ collection: asCollectionSlug("catalogue-categories"), id: category, depth: 0, overrideAccess: true });
1503
+ return { ...doc, category: read };
1504
+ } catch {
1505
+ return doc;
1506
+ }
1507
+ }
1472
1508
  async function syncCatalogDoc(payload, doc, method, collectionSlug) {
1473
1509
  const siteId = relationId2(doc.site);
1474
1510
  if (siteId == null || doc.id == null) return;
1475
1511
  const config = await findCatalogConfig(payload, siteId);
1476
1512
  if (!config || config.sourceCollection !== collectionSlug) return;
1477
1513
  const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
1514
+ const readDoc = method === "DELETE" ? doc : await withCategoryRead(payload, doc, config.urlTemplate);
1478
1515
  const request = method === "DELETE" ? deleteRequest(String(doc.id)) : (() => {
1479
- const item = toCatalogItem(doc, {
1516
+ const item = toCatalogItem(readDoc, {
1480
1517
  urlTemplate: config.urlTemplate,
1481
1518
  serverUrl: serverUrl4,
1482
1519
  brand: config.brand
@@ -1896,6 +1933,7 @@ var metaOAuthCreatePixelEndpoint = {
1896
1933
  access_token: token
1897
1934
  });
1898
1935
  if (!result.ok || !result.data?.id) {
1936
+ req.payload.logger.warn(`[meta:pixel] creating a Pixel on business ${business.id} failed (${result.status}): ${result.error || "no reason given"}`);
1899
1937
  return Response.json({ error: result.error || "Pixel creation failed" }, { status: 502 });
1900
1938
  }
1901
1939
  await req.payload.update({
@@ -2178,7 +2216,7 @@ var metaCatalogSyncEndpoint = {
2178
2216
  return Response.json({ error: "Turn on Commerce Catalog and choose a catalog first." }, { status: 400 });
2179
2217
  }
2180
2218
  if (!config.catalogItemUrlTemplate) {
2181
- return Response.json({ error: "Set the item page URL template (it must contain {slug}) before syncing." }, { status: 400 });
2219
+ return Response.json({ error: "Set the item page URL template (it must contain {slug} or {category.slug}) before syncing." }, { status: 400 });
2182
2220
  }
2183
2221
  const siteId = relationId2(config.site);
2184
2222
  if (siteId == null) return Response.json({ error: "This Meta connection has no site." }, { status: 400 });
package/dist/index.mjs CHANGED
@@ -733,7 +733,7 @@ var MetaConfig = {
733
733
  name: "catalogItemUrlTemplate",
734
734
  type: "text",
735
735
  admin: {
736
- description: 'Item page URL template on the live site \u2014 "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}. Required before products can sync (Meta rejects an item with no link).',
736
+ description: `Item page URL template on the live site. "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}; "{category.slug}" by the slug of the item's category, for a shop with one page per category whose items are sizes of it, e.g. https://avrilbeetails.com/adun/{category.slug}. Required before products can sync (Meta rejects an item with no link).`,
737
737
  condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
738
738
  }
739
739
  },
@@ -874,6 +874,104 @@ var MetaConfig = {
874
874
  timestamps: true
875
875
  };
876
876
 
877
+ // src/sync/catalogProduct.ts
878
+ var COMMERCE_COLLECTION = "catalogue-items";
879
+ function firstDefined(...values) {
880
+ for (const value of values) {
881
+ if (value !== void 0 && value !== null && value !== "") return value;
882
+ }
883
+ return void 0;
884
+ }
885
+ function plainText(value) {
886
+ if (typeof value === "string") return value;
887
+ if (typeof value === "number") return String(value);
888
+ if (value && typeof value === "object") {
889
+ const record = value;
890
+ for (const entry of Object.values(record)) {
891
+ if (typeof entry === "string" && entry.trim()) return entry;
892
+ }
893
+ }
894
+ return "";
895
+ }
896
+ function stripHtml(input) {
897
+ return input.replace(/<[^>]+>/g, "").trim();
898
+ }
899
+ function resolveImageUrl(media, serverUrl4) {
900
+ if (!media) return "";
901
+ if (typeof media === "string") {
902
+ if (media.startsWith("http://") || media.startsWith("https://")) return media;
903
+ return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
904
+ }
905
+ if (typeof media === "object") {
906
+ const record = media;
907
+ const url = typeof record.url === "string" ? record.url : "";
908
+ if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
909
+ const filename = typeof record.filename === "string" ? record.filename : "";
910
+ if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
911
+ }
912
+ return "";
913
+ }
914
+ function relationId2(value) {
915
+ if (typeof value === "string" || typeof value === "number") return value;
916
+ if (value && typeof value === "object" && "id" in value) {
917
+ const id = value.id;
918
+ if (typeof id === "string" || typeof id === "number") return id;
919
+ }
920
+ return void 0;
921
+ }
922
+ function catalogSourceSlug(configured) {
923
+ const slug = typeof configured === "string" ? configured.trim() : "";
924
+ return slug || COMMERCE_COLLECTION;
925
+ }
926
+ var URL_TEMPLATE_PLACEHOLDERS = ["{slug}", "{category.slug}"];
927
+ function hasUrlPlaceholder(template) {
928
+ return URL_TEMPLATE_PLACEHOLDERS.some((placeholder) => template.includes(placeholder));
929
+ }
930
+ function itemLink(doc, template) {
931
+ let link = template.trim();
932
+ if (!hasUrlPlaceholder(link)) return null;
933
+ if (link.includes("{category.slug}")) {
934
+ const category = doc.category;
935
+ const categorySlug = category && typeof category === "object" ? plainText(category.slug).trim() : "";
936
+ if (!categorySlug) return null;
937
+ link = link.split("{category.slug}").join(encodeURIComponent(categorySlug));
938
+ }
939
+ if (link.includes("{slug}")) link = link.split("{slug}").join(encodeURIComponent(plainText(firstDefined(doc.slug, doc.id))));
940
+ return link;
941
+ }
942
+ function toCatalogItem(doc, options) {
943
+ const title = plainText(firstDefined(doc.title, doc.name, doc.heading)).trim();
944
+ const price = firstDefined(doc.price, doc.price_from, doc.priceFrom);
945
+ if (!title || price === void 0 || price === null || price === "") return null;
946
+ const amount = Number(price);
947
+ if (!Number.isFinite(amount)) return null;
948
+ const link = itemLink(doc, options.urlTemplate);
949
+ if (!link) return null;
950
+ const rawDescription = firstDefined(doc.description, doc.excerpt, doc.body);
951
+ const description = rawDescription ? stripHtml(plainText(rawDescription)).slice(0, 5e3) : title;
952
+ const available = doc.available === void 0 ? true : Boolean(doc.available);
953
+ const currency = (options.currency || "NGN").toUpperCase();
954
+ const image = resolveImageUrl(firstDefined(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
955
+ const item = {
956
+ id: String(doc.id),
957
+ title,
958
+ description,
959
+ availability: available ? "in stock" : "out of stock",
960
+ condition: "new",
961
+ price: `${amount.toFixed(2)} ${currency}`,
962
+ link
963
+ };
964
+ if (image) item.image_link = image;
965
+ if (options.brand) item.brand = options.brand;
966
+ return item;
967
+ }
968
+ function updateRequest(item) {
969
+ return { method: "UPDATE", data: item };
970
+ }
971
+ function deleteRequest(retailerId) {
972
+ return { method: "DELETE", data: { id: retailerId } };
973
+ }
974
+
877
975
  // src/endpoints/metaCatalogFeed.ts
878
976
  function csvEscape(value) {
879
977
  const str = value === null || value === void 0 ? "" : String(value);
@@ -882,16 +980,16 @@ function csvEscape(value) {
882
980
  }
883
981
  return str;
884
982
  }
885
- function firstDefined(...values) {
983
+ function firstDefined2(...values) {
886
984
  for (const v of values) {
887
985
  if (v !== void 0 && v !== null && v !== "") return v;
888
986
  }
889
987
  return void 0;
890
988
  }
891
- function stripHtml(input) {
989
+ function stripHtml2(input) {
892
990
  return input.replace(/<[^>]+>/g, "").trim();
893
991
  }
894
- function resolveImageUrl(media, serverUrl4) {
992
+ function resolveImageUrl2(media, serverUrl4) {
895
993
  if (!media) return "";
896
994
  if (typeof media === "string") {
897
995
  if (media.startsWith("http://") || media.startsWith("https://")) return media;
@@ -963,16 +1061,15 @@ var metaCatalogFeedEndpoint = {
963
1061
  const rows = [header.join(",")];
964
1062
  for (const item of items) {
965
1063
  const id = String(item.id);
966
- const title = String(firstDefined(item.title, item.name, item.heading) ?? "");
967
- const rawDescription = firstDefined(item.description, item.excerpt, item.body);
968
- const description = rawDescription ? stripHtml(String(rawDescription)).slice(0, 5e3) : "";
969
- const price = firstDefined(item.price, item.price_from, item.priceFrom);
1064
+ const title = String(firstDefined2(item.title, item.name, item.heading) ?? "");
1065
+ const rawDescription = firstDefined2(item.description, item.excerpt, item.body);
1066
+ const description = rawDescription ? stripHtml2(String(rawDescription)).slice(0, 5e3) : "";
1067
+ const price = firstDefined2(item.price, item.price_from, item.priceFrom);
970
1068
  const available = item.available === void 0 ? true : Boolean(item.available);
971
- const slug = String(firstDefined(item.slug, item.id));
972
- const link = urlTemplate.replace("{slug}", encodeURIComponent(slug));
973
- const image = firstDefined(item.image, item.featuredImage, item.photo);
974
- const imageLink = resolveImageUrl(image, serverUrl4);
975
- if (!title || price === void 0) continue;
1069
+ const link = itemLink(item, urlTemplate);
1070
+ const image = firstDefined2(item.image, item.featuredImage, item.photo);
1071
+ const imageLink = resolveImageUrl2(image, serverUrl4);
1072
+ if (!title || price === void 0 || !link) continue;
976
1073
  rows.push([
977
1074
  csvEscape(id),
978
1075
  csvEscape(title),
@@ -1168,10 +1265,21 @@ var BASE_DELAY_MS = 800;
1168
1265
  function sleep(ms) {
1169
1266
  return new Promise((resolve) => setTimeout(resolve, ms));
1170
1267
  }
1268
+ var KNOWN_SUBCODES = {
1269
+ 1784018: "This business has not accepted Meta's Pixel terms. Open Events Manager for the business, start connecting a Web data source, accept the terms, then try again (or create the Pixel there and choose it here)."
1270
+ };
1271
+ function explainGraphError(body) {
1272
+ const error = body?.error;
1273
+ if (!error) return null;
1274
+ if (error.error_subcode && KNOWN_SUBCODES[error.error_subcode]) return KNOWN_SUBCODES[error.error_subcode];
1275
+ if (error.error_user_msg) return error.error_user_title ? `${error.error_user_title}: ${error.error_user_msg}` : error.error_user_msg;
1276
+ return error.message ?? null;
1277
+ }
1171
1278
  async function parseGraphError(res) {
1172
1279
  try {
1173
1280
  const body = await res.json();
1174
- if (body?.error?.message) return body.error.message;
1281
+ const said = explainGraphError(body);
1282
+ if (said) return said;
1175
1283
  } catch {
1176
1284
  }
1177
1285
  return `Graph API error: ${res.status}`;
@@ -1275,89 +1383,6 @@ function oauthPopupResponse(args) {
1275
1383
  });
1276
1384
  }
1277
1385
 
1278
- // src/sync/catalogProduct.ts
1279
- var COMMERCE_COLLECTION = "catalogue-items";
1280
- function firstDefined2(...values) {
1281
- for (const value of values) {
1282
- if (value !== void 0 && value !== null && value !== "") return value;
1283
- }
1284
- return void 0;
1285
- }
1286
- function plainText(value) {
1287
- if (typeof value === "string") return value;
1288
- if (typeof value === "number") return String(value);
1289
- if (value && typeof value === "object") {
1290
- const record = value;
1291
- for (const entry of Object.values(record)) {
1292
- if (typeof entry === "string" && entry.trim()) return entry;
1293
- }
1294
- }
1295
- return "";
1296
- }
1297
- function stripHtml2(input) {
1298
- return input.replace(/<[^>]+>/g, "").trim();
1299
- }
1300
- function resolveImageUrl2(media, serverUrl4) {
1301
- if (!media) return "";
1302
- if (typeof media === "string") {
1303
- if (media.startsWith("http://") || media.startsWith("https://")) return media;
1304
- return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
1305
- }
1306
- if (typeof media === "object") {
1307
- const record = media;
1308
- const url = typeof record.url === "string" ? record.url : "";
1309
- if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
1310
- const filename = typeof record.filename === "string" ? record.filename : "";
1311
- if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
1312
- }
1313
- return "";
1314
- }
1315
- function relationId2(value) {
1316
- if (typeof value === "string" || typeof value === "number") return value;
1317
- if (value && typeof value === "object" && "id" in value) {
1318
- const id = value.id;
1319
- if (typeof id === "string" || typeof id === "number") return id;
1320
- }
1321
- return void 0;
1322
- }
1323
- function catalogSourceSlug(configured) {
1324
- const slug = typeof configured === "string" ? configured.trim() : "";
1325
- return slug || COMMERCE_COLLECTION;
1326
- }
1327
- function toCatalogItem(doc, options) {
1328
- const title = plainText(firstDefined2(doc.title, doc.name, doc.heading)).trim();
1329
- const price = firstDefined2(doc.price, doc.price_from, doc.priceFrom);
1330
- if (!title || price === void 0 || price === null || price === "") return null;
1331
- const amount = Number(price);
1332
- if (!Number.isFinite(amount)) return null;
1333
- const slug = plainText(firstDefined2(doc.slug, doc.id));
1334
- const template = options.urlTemplate.trim();
1335
- if (!template.includes("{slug}")) return null;
1336
- const rawDescription = firstDefined2(doc.description, doc.excerpt, doc.body);
1337
- const description = rawDescription ? stripHtml2(plainText(rawDescription)).slice(0, 5e3) : title;
1338
- const available = doc.available === void 0 ? true : Boolean(doc.available);
1339
- const currency = (options.currency || "NGN").toUpperCase();
1340
- const image = resolveImageUrl2(firstDefined2(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
1341
- const item = {
1342
- id: String(doc.id),
1343
- title,
1344
- description,
1345
- availability: available ? "in stock" : "out of stock",
1346
- condition: "new",
1347
- price: `${amount.toFixed(2)} ${currency}`,
1348
- link: template.replace("{slug}", encodeURIComponent(slug))
1349
- };
1350
- if (image) item.image_link = image;
1351
- if (options.brand) item.brand = options.brand;
1352
- return item;
1353
- }
1354
- function updateRequest(item) {
1355
- return { method: "UPDATE", data: item };
1356
- }
1357
- function deleteRequest(retailerId) {
1358
- return { method: "DELETE", data: { id: retailerId } };
1359
- }
1360
-
1361
1386
  // src/sync/catalogSync.ts
1362
1387
  function decryptToken(value) {
1363
1388
  if (typeof value !== "string" || !value || value.includes("\u2022")) return "";
@@ -1410,14 +1435,26 @@ async function pushBatch(catalogId, token, requests) {
1410
1435
  const messages = (result.data?.validation_status ?? []).flatMap((row) => row.errors ?? []).map((error) => error.message).filter((message) => Boolean(message));
1411
1436
  return messages.length ? messages.join("; ") : null;
1412
1437
  }
1438
+ async function withCategoryRead(payload, doc, template) {
1439
+ if (!template.includes("{category.slug}")) return doc;
1440
+ const category = doc.category;
1441
+ if (category == null || typeof category === "object") return doc;
1442
+ try {
1443
+ const read = await payload.findByID({ collection: asCollectionSlug("catalogue-categories"), id: category, depth: 0, overrideAccess: true });
1444
+ return { ...doc, category: read };
1445
+ } catch {
1446
+ return doc;
1447
+ }
1448
+ }
1413
1449
  async function syncCatalogDoc(payload, doc, method, collectionSlug) {
1414
1450
  const siteId = relationId2(doc.site);
1415
1451
  if (siteId == null || doc.id == null) return;
1416
1452
  const config = await findCatalogConfig(payload, siteId);
1417
1453
  if (!config || config.sourceCollection !== collectionSlug) return;
1418
1454
  const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
1455
+ const readDoc = method === "DELETE" ? doc : await withCategoryRead(payload, doc, config.urlTemplate);
1419
1456
  const request = method === "DELETE" ? deleteRequest(String(doc.id)) : (() => {
1420
- const item = toCatalogItem(doc, {
1457
+ const item = toCatalogItem(readDoc, {
1421
1458
  urlTemplate: config.urlTemplate,
1422
1459
  serverUrl: serverUrl4,
1423
1460
  brand: config.brand
@@ -1837,6 +1874,7 @@ var metaOAuthCreatePixelEndpoint = {
1837
1874
  access_token: token
1838
1875
  });
1839
1876
  if (!result.ok || !result.data?.id) {
1877
+ req.payload.logger.warn(`[meta:pixel] creating a Pixel on business ${business.id} failed (${result.status}): ${result.error || "no reason given"}`);
1840
1878
  return Response.json({ error: result.error || "Pixel creation failed" }, { status: 502 });
1841
1879
  }
1842
1880
  await req.payload.update({
@@ -2119,7 +2157,7 @@ var metaCatalogSyncEndpoint = {
2119
2157
  return Response.json({ error: "Turn on Commerce Catalog and choose a catalog first." }, { status: 400 });
2120
2158
  }
2121
2159
  if (!config.catalogItemUrlTemplate) {
2122
- return Response.json({ error: "Set the item page URL template (it must contain {slug}) before syncing." }, { status: 400 });
2160
+ return Response.json({ error: "Set the item page URL template (it must contain {slug} or {category.slug}) before syncing." }, { status: 400 });
2123
2161
  }
2124
2162
  const siteId = relationId2(config.site);
2125
2163
  if (siteId == null) return Response.json({ error: "This Meta connection has no site." }, { status: 400 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opscms-meta-plugin",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Payload CMS plugin for connecting multi-tenant sites to Meta's network (Facebook Pixel + Conversions API, Facebook/Instagram Commerce Catalog, WhatsApp Business Cloud API). Modular per-channel, per-site — nothing hardcoded to one product line.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",