@aglyn/plugins-commerce 1.0.0-beta.243 → 1.0.0-beta.246

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 (57) hide show
  1. package/README.md +4 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/commerce-console-page.js +10 -0
  4. package/src/lib/components/commerce-console-page.js.map +1 -1
  5. package/src/lib/components/console/product-zones.d.ts +7 -1
  6. package/src/lib/components/console/product-zones.js.map +1 -1
  7. package/src/lib/components/console/products-hub-zone.component.d.ts +3 -2
  8. package/src/lib/components/console/products-hub-zone.component.js +9 -1
  9. package/src/lib/components/console/products-hub-zone.component.js.map +1 -1
  10. package/src/lib/components/console/review-settings-card.component.d.ts +14 -0
  11. package/src/lib/components/console/review-settings-card.component.js +168 -0
  12. package/src/lib/components/console/review-settings-card.component.js.map +1 -0
  13. package/src/lib/components/console/reviews-moderation-card.component.d.ts +14 -0
  14. package/src/lib/components/console/reviews-moderation-card.component.js +85 -11
  15. package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
  16. package/src/lib/components/product-reviews.d.ts +29 -1
  17. package/src/lib/components/product-reviews.js +97 -12
  18. package/src/lib/components/product-reviews.js.map +1 -1
  19. package/src/lib/model/commerce.d.ts +11 -2
  20. package/src/lib/model/commerce.js +14 -2
  21. package/src/lib/model/commerce.js.map +1 -1
  22. package/src/lib/model/index.d.ts +1 -0
  23. package/src/lib/model/index.js +1 -0
  24. package/src/lib/model/index.js.map +1 -1
  25. package/src/lib/model/product-reviews.d.ts +124 -0
  26. package/src/lib/model/product-reviews.js +133 -0
  27. package/src/lib/model/product-reviews.js.map +1 -0
  28. package/src/lib/model/store-setup-content.d.ts +145 -0
  29. package/src/lib/model/store-setup-content.js +813 -0
  30. package/src/lib/model/store-setup-content.js.map +1 -0
  31. package/src/lib/server/membership-reset.js +8 -2
  32. package/src/lib/server/membership-reset.js.map +1 -1
  33. package/src/lib/server/order-event-triggers.d.ts +2 -0
  34. package/src/lib/server/order-event-triggers.js +18 -1
  35. package/src/lib/server/order-event-triggers.js.map +1 -1
  36. package/src/lib/server/review-requests.d.ts +102 -0
  37. package/src/lib/server/review-requests.js +346 -0
  38. package/src/lib/server/review-requests.js.map +1 -0
  39. package/src/lib/server/review-tokens.d.ts +82 -0
  40. package/src/lib/server/review-tokens.js +119 -0
  41. package/src/lib/server/review-tokens.js.map +1 -0
  42. package/src/lib/server/reviews.d.ts +36 -3
  43. package/src/lib/server/reviews.js +310 -52
  44. package/src/lib/server/reviews.js.map +1 -1
  45. package/src/lib/server/store-setup-ai-capability.d.ts +61 -0
  46. package/src/lib/server/store-setup-ai-capability.js +343 -0
  47. package/src/lib/server/store-setup-ai-capability.js.map +1 -0
  48. package/src/lib/server/store-setup-ai-writer.console.d.ts +27 -0
  49. package/src/lib/server/store-setup-ai-writer.console.js +44 -0
  50. package/src/lib/server/store-setup-ai-writer.console.js.map +1 -0
  51. package/src/lib/server/store-setup-ai-writer.d.ts +37 -0
  52. package/src/lib/server/store-setup-ai-writer.js +174 -0
  53. package/src/lib/server/store-setup-ai-writer.js.map +1 -0
  54. package/src/lib/server.js +27 -0
  55. package/src/lib/server.js.map +1 -1
  56. package/src/lib/tenant-emails.js +58 -0
  57. package/src/lib/tenant-emails.js.map +1 -1
@@ -0,0 +1,174 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { hostRoleCanPublish } from "@aglyn/aglyn/app-utils/organizations";
18
+ import { checkEntitlement } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { applyStoreSetupChange, readStoreSetupChange, storeSetupFacts } from "../model/store-setup-content.js";
20
+ /** The refusal for a member without the publishing role (admin or editor). */ export const STORE_SETUP_ROLE_REFUSAL = 'Changing store settings through AI needs an admin or editor role';
21
+ /** The refusal for a plan without commerce. */ export const STORE_SETUP_PLAN_REFUSAL = 'Selling online is not included in your plan — see Billing';
22
+ /** What a member is told while a lockdown refuses writes to the site. */ export const STORE_SETUP_LOCKED_REFUSAL = 'This site is not accepting changes right now.';
23
+ const SECTION_NAMES = {
24
+ shipping: 'Shipping',
25
+ pickup: 'Local pickup',
26
+ 'local-delivery': 'Local delivery',
27
+ tax: 'Taxes'
28
+ };
29
+ function locationOf(id, data) {
30
+ var _data_postalAddress;
31
+ const postal = (_data_postalAddress = data['postalAddress']) != null ? _data_postalAddress : {};
32
+ return {
33
+ id,
34
+ name: typeof data['name'] === 'string' ? data['name'] : undefined,
35
+ address: typeof data['address'] === 'string' ? data['address'] : undefined,
36
+ city: typeof postal['city'] === 'string' ? postal['city'] : undefined,
37
+ pickup: data['pickup']
38
+ };
39
+ }
40
+ export function createStoreSetupAiWriter(deps) {
41
+ const hostRef = (hostId)=>deps.firestore().collection('hosts').doc(hostId);
42
+ const settingsRef = (hostId)=>hostRef(hostId).collection('settings').doc('store');
43
+ async function refusalFor(host, context) {
44
+ var _host_data, _data_memberRoles, _context_org;
45
+ if (!host.exists) return {
46
+ status: 404,
47
+ error: 'Unknown site'
48
+ };
49
+ const data = (_host_data = host.data()) != null ? _host_data : {};
50
+ const role = ((_data_memberRoles = data['memberRoles']) != null ? _data_memberRoles : {})[context.uid];
51
+ if (!hostRoleCanPublish(role)) return {
52
+ status: 403,
53
+ error: STORE_SETUP_ROLE_REFUSAL
54
+ };
55
+ if (!checkEntitlement((_context_org = context.org) != null ? _context_org : {}, 'commerce')) {
56
+ return {
57
+ status: 403,
58
+ error: STORE_SETUP_PLAN_REFUSAL
59
+ };
60
+ }
61
+ if (await deps.lockdown({
62
+ uid: context.uid,
63
+ org: context.org,
64
+ host: data
65
+ })) {
66
+ return {
67
+ status: 403,
68
+ error: STORE_SETUP_LOCKED_REFUSAL
69
+ };
70
+ }
71
+ return null;
72
+ }
73
+ return {
74
+ refusal: async (context)=>refusalFor(await hostRef(context.hostId).get(), context),
75
+ check: (content)=>{
76
+ const read = readStoreSetupChange(content);
77
+ if (read.ok === false) return {
78
+ ok: false,
79
+ problems: read.problems
80
+ };
81
+ return {
82
+ ok: true,
83
+ facts: {
84
+ section: read.value.section,
85
+ live: true
86
+ }
87
+ };
88
+ },
89
+ // The settings are one document, not one per change: whatever id is
90
+ // asked, the store's setup as it stands.
91
+ read: async ({ hostId, id })=>{
92
+ var _snapshot_data;
93
+ const snapshot = await settingsRef(hostId).get();
94
+ if (!snapshot.exists) return null;
95
+ return {
96
+ id,
97
+ name: 'Store settings',
98
+ versionId: null,
99
+ facts: storeSetupFacts((_snapshot_data = snapshot.data()) != null ? _snapshot_data : {})
100
+ };
101
+ },
102
+ write: async (request)=>{
103
+ const read = readStoreSetupChange(request.content);
104
+ if (read.ok === false) return {
105
+ ok: false,
106
+ status: 400,
107
+ error: read.problems[0]
108
+ };
109
+ const change = read.value;
110
+ const refusal = await refusalFor(await hostRef(request.hostId).get(), request);
111
+ if (refusal) return _extends({
112
+ ok: false
113
+ }, refusal);
114
+ const needsLocations = 'location' in change && Boolean(change.location);
115
+ const db = deps.firestore();
116
+ const ref = settingsRef(request.hostId);
117
+ const locations = hostRef(request.hostId).collection('locations');
118
+ return db.runTransaction(async (tx)=>{
119
+ var _settings_data, _ref;
120
+ // Every read before any write, which Firestore requires.
121
+ const [settings, places] = await Promise.all([
122
+ tx.get(ref),
123
+ needsLocations ? tx.get(locations) : Promise.resolve(null)
124
+ ]);
125
+ const applied = applyStoreSetupChange({
126
+ settings: (_settings_data = settings.data()) != null ? _settings_data : {},
127
+ locations: ((_ref = places == null ? void 0 : places.docs) != null ? _ref : []).map((doc)=>{
128
+ var _doc_data;
129
+ return locationOf(doc.id, (_doc_data = doc.data()) != null ? _doc_data : {});
130
+ })
131
+ }, change, {
132
+ zoneId: `${request.id}-zone`,
133
+ rateId: `${request.id}-rate`
134
+ });
135
+ if (applied.ok === false) return {
136
+ ok: false,
137
+ status: applied.status,
138
+ error: applied.error
139
+ };
140
+ const write = applied.write;
141
+ if ((write == null ? void 0 : write.target) === 'settings') {
142
+ tx.set(ref, {
143
+ [write.field]: write.value
144
+ }, {
145
+ mergeFields: [
146
+ write.field
147
+ ]
148
+ });
149
+ } else if ((write == null ? void 0 : write.target) === 'location') {
150
+ // The card's `updateDoc`: the map replaced whole, so a cleared field is cleared.
151
+ tx.update(locations.doc(write.locationId), {
152
+ pickup: write.value
153
+ });
154
+ }
155
+ return {
156
+ ok: true,
157
+ replayed: write === null,
158
+ // One per item: the settings are one document, so the item names the change.
159
+ id: request.id,
160
+ name: request.name.trim() || SECTION_NAMES[change.section] || 'Store settings',
161
+ versionId: null,
162
+ facts: {
163
+ section: change.section,
164
+ summary: applied.summary,
165
+ warnings: applied.warnings,
166
+ live: true
167
+ }
168
+ };
169
+ });
170
+ }
171
+ };
172
+ }
173
+
174
+ //# sourceMappingURL=store-setup-ai-writer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/store-setup-ai-writer.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hostRoleCanPublish } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type {\n PluginDraftContext,\n PluginDraftRecord,\n PluginDraftRefusal,\n PluginDraftWrite,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n applyStoreSetupChange,\n readStoreSetupChange,\n storeSetupFacts,\n type StoreSetupLocation,\n} from '../model/store-setup-content'\n\n/*==========================================\n * THE STORE'S SHIPPING AND TAX SETUP AN AI BUILD CHANGES (AGL-3749)\n *\n * The writer commerce registers for the `store-settings` resource on core's\n * resource-drafts seam, which the `store-shipping`, `store-pickup`,\n * `store-delivery` and `store-tax` build operations execute\n * (`store-setup-ai-capability.ts`). It writes exactly what the console's\n * Shipping, Local delivery, Taxes and Inventory locations cards write:\n *\n * - who: an admin or an editor on the site (`hostRoleCanPublish`), the\n * plan's `commerce` feature, and no lockdown refusing a write to the site, its workspace or\n * the member (`hostWritesFrozen`). The role is stricter than the cards,\n * which the Firestore rules let an author save too (`canWriteHostContent`):\n * these settings change what checkout charges, and an AI change of them\n * is live at once, so it takes the publishing role (Zach, 2026-10-12);\n * - what: the change is read and applied by `store-setup-content.ts`,\n * through the cards' own normalizers and checks — the zone-coverage\n * summary, the pickup and delivery normalizers, delivery's \"can't offer\n * it yet\" problems, and the manual-tax-without-an-origin refusal;\n * - how: one map of `settings/store` replaced whole (`mergeFields`, as the\n * Local delivery card saves), or one location's `pickup` (as the\n * Inventory locations card saves), inside a transaction, so two items of\n * one plan changing the same map never lose each other's change.\n *\n * Store settings have no draft state: the cards save them live, and so does\n * this. The plan card is where the person agrees to the change.\n *\n * Asked again for the same change, it writes nothing: a zone, a rate, a\n * delivery zone and a tax rate are found by name or region before anything\n * is added, a new one takes an id derived from the request, and a change the\n * settings already hold is reported as done (`replayed`).\n *\n * Nothing here connects an account or stores a credential: carrier rates and\n * outside tax services are set up by a person in their own cards.\n *=========================================*/\n\ntype Firestore = FirebaseFirestore.Firestore\ntype Stored = Record<string, unknown>\n\n/** The refusal for a member without the publishing role (admin or editor). */\nexport const STORE_SETUP_ROLE_REFUSAL = 'Changing store settings through AI needs an admin or editor role'\n/** The refusal for a plan without commerce. */\nexport const STORE_SETUP_PLAN_REFUSAL = 'Selling online is not included in your plan — see Billing'\n/** What a member is told while a lockdown refuses writes to the site. */\nexport const STORE_SETUP_LOCKED_REFUSAL = 'This site is not accepting changes right now.'\n\n/** Whether a lockdown refuses this member's write to this site; `true` refuses. */\nexport type StoreSetupLockdownCheck = (input: {\n uid: string\n org: PluginDraftContext['org']\n host: Stored\n}) => Promise<boolean>\n\nexport interface StoreSetupAiWriterDeps {\n firestore: () => Firestore\n lockdown: StoreSetupLockdownCheck\n}\n\nconst SECTION_NAMES: Record<string, string> = {\n shipping: 'Shipping',\n pickup: 'Local pickup',\n 'local-delivery': 'Local delivery',\n tax: 'Taxes',\n}\n\nfunction locationOf(id: string, data: Stored): StoreSetupLocation {\n const postal = (data['postalAddress'] ?? {}) as Stored\n return {\n id,\n name: typeof data['name'] === 'string' ? data['name'] : undefined,\n address: typeof data['address'] === 'string' ? data['address'] : undefined,\n city: typeof postal['city'] === 'string' ? (postal['city'] as string) : undefined,\n pickup: data['pickup'],\n }\n}\n\nexport function createStoreSetupAiWriter(deps: StoreSetupAiWriterDeps): PluginResourceDraftWriter {\n const hostRef = (hostId: string) => deps.firestore().collection('hosts').doc(hostId)\n const settingsRef = (hostId: string) => hostRef(hostId).collection('settings').doc('store')\n\n async function refusalFor(\n host: FirebaseFirestore.DocumentSnapshot,\n context: Pick<PluginDraftContext, 'uid' | 'org'>,\n ): Promise<PluginDraftRefusal | null> {\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const data = (host.data() ?? {}) as Stored\n const role = ((data['memberRoles'] ?? {}) as Stored)[context.uid]\n if (!hostRoleCanPublish(role)) return { status: 403, error: STORE_SETUP_ROLE_REFUSAL }\n if (!checkEntitlement((context.org ?? {}) as never, 'commerce')) {\n return { status: 403, error: STORE_SETUP_PLAN_REFUSAL }\n }\n if (await deps.lockdown({ uid: context.uid, org: context.org, host: data })) {\n return { status: 403, error: STORE_SETUP_LOCKED_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => refusalFor(await hostRef(context.hostId).get(), context),\n\n check: (content) => {\n const read = readStoreSetupChange(content)\n if (read.ok === false) return { ok: false, problems: read.problems }\n return { ok: true, facts: { section: read.value.section, live: true } }\n },\n\n // The settings are one document, not one per change: whatever id is\n // asked, the store's setup as it stands.\n read: async ({ hostId, id }): Promise<PluginDraftRecord | null> => {\n const snapshot = await settingsRef(hostId).get()\n if (!snapshot.exists) return null\n return { id, name: 'Store settings', versionId: null, facts: storeSetupFacts((snapshot.data() ?? {}) as Stored) }\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readStoreSetupChange(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] as string }\n const change = read.value\n const refusal = await refusalFor(await hostRef(request.hostId).get(), request)\n if (refusal) return { ok: false, ...refusal }\n const needsLocations = 'location' in change && Boolean(change.location)\n const db = deps.firestore()\n const ref = settingsRef(request.hostId)\n const locations = hostRef(request.hostId).collection('locations')\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [settings, places] = await Promise.all([\n tx.get(ref),\n needsLocations ? tx.get(locations) : Promise.resolve(null),\n ])\n const applied = applyStoreSetupChange(\n {\n settings: (settings.data() ?? {}) as Stored,\n locations: (places?.docs ?? []).map((doc) => locationOf(doc.id, (doc.data() ?? {}) as Stored)),\n },\n change,\n { zoneId: `${request.id}-zone`, rateId: `${request.id}-rate` },\n )\n if (applied.ok === false) return { ok: false, status: applied.status, error: applied.error }\n const write = applied.write\n if (write?.target === 'settings') {\n tx.set(ref, { [write.field]: write.value }, { mergeFields: [write.field] })\n } else if (write?.target === 'location') {\n // The card's `updateDoc`: the map replaced whole, so a cleared field is cleared.\n tx.update(locations.doc(write.locationId), { pickup: write.value })\n }\n return {\n ok: true,\n replayed: write === null,\n // One per item: the settings are one document, so the item names the change.\n id: request.id,\n name: request.name.trim() || SECTION_NAMES[change.section] || 'Store settings',\n versionId: null,\n facts: { section: change.section, summary: applied.summary, warnings: applied.warnings, live: true },\n }\n })\n },\n }\n}\n"],"names":["hostRoleCanPublish","checkEntitlement","applyStoreSetupChange","readStoreSetupChange","storeSetupFacts","STORE_SETUP_ROLE_REFUSAL","STORE_SETUP_PLAN_REFUSAL","STORE_SETUP_LOCKED_REFUSAL","SECTION_NAMES","shipping","pickup","tax","locationOf","id","data","postal","name","undefined","address","city","createStoreSetupAiWriter","deps","hostRef","hostId","firestore","collection","doc","settingsRef","refusalFor","host","context","exists","status","error","role","uid","org","lockdown","refusal","get","check","content","read","ok","problems","facts","section","value","live","snapshot","versionId","write","request","change","needsLocations","Boolean","location","db","ref","locations","runTransaction","tx","settings","places","Promise","all","resolve","applied","docs","map","zoneId","rateId","target","set","field","mergeFields","update","locationId","replayed","trim","summary","warnings"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,gBAAgB,QAAQ,2CAA0C;AAQ3E,SACEC,qBAAqB,EACrBC,oBAAoB,EACpBC,eAAe,QAEV,kCAA8B;AAyCrC,4EAA4E,GAC5E,OAAO,MAAMC,2BAA2B,mEAAkE;AAC1G,6CAA6C,GAC7C,OAAO,MAAMC,2BAA2B,4DAA2D;AACnG,uEAAuE,GACvE,OAAO,MAAMC,6BAA6B,gDAA+C;AAczF,MAAMC,gBAAwC;IAC5CC,UAAU;IACVC,QAAQ;IACR,kBAAkB;IAClBC,KAAK;AACP;AAEA,SAASC,WAAWC,EAAU,EAAEC,IAAY;QAC1BA;IAAhB,MAAMC,UAAUD,sBAAAA,IAAI,CAAC,gBAAgB,YAArBA,sBAAyB,CAAC;IAC1C,OAAO;QACLD;QACAG,MAAM,OAAOF,IAAI,CAAC,OAAO,KAAK,WAAWA,IAAI,CAAC,OAAO,GAAGG;QACx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C,EAAE;oBACdG,MAAMoC,QAAQpC,IAAI,CAAC+D,IAAI,MAAMvE,aAAa,CAAC6C,OAAOP,OAAO,CAAC,IAAI;oBAC9DI,WAAW;oBACXL,OAAO;wBAAEC,SAASO,OAAOP,OAAO;wBAAEkC,SAASb,QAAQa,OAAO;wBAAEC,UAAUd,QAAQc,QAAQ;wBAAEjC,MAAM;oBAAK;gBACrG;YACF;QACF;IACF;AACF"}
package/src/lib/server.js CHANGED
@@ -28,6 +28,8 @@ import { registerCommerceMediaPublishGuard } from "./server/media-publish-guard.
28
28
  import { registerCommerceRecurringCharges } from "./server/recurring-charges.js";
29
29
  import { registerProductCardReader } from "./server/product-card.js";
30
30
  import { registerProductAiCapability } from "./server/product-ai-capability.js";
31
+ import { registerStoreSetupAiCapabilities } from "./server/store-setup-ai-capability.js";
32
+ import { registerStoreSetupAiWriter } from "./server/store-setup-ai-writer.console.js";
31
33
  import { registerProductDraftWriter } from "./server/product-drafts.js";
32
34
  import { registerCommerceTaxProfile } from "./server/tax-profile.js";
33
35
  import { registerTaxReturnSource } from "@aglyn/aglyn/plugin-manager/plugin-tax-return-sources";
@@ -154,6 +156,26 @@ registerPluginJob({
154
156
  if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`);
155
157
  }
156
158
  });
159
+ /**
160
+ * The review-request email (AGL-3736). HOURLY: a request is owed days after
161
+ * fulfilment, so an hour's lateness is invisible, and the scan is one
162
+ * collection-group range query over `reviewRequestDueAtMs` — a field only
163
+ * orders still owed a request carry, so an empty beat costs one read.
164
+ */ registerPluginJob({
165
+ pluginId: BUNDLE_ID,
166
+ name: 'review-request-emails',
167
+ intervalMinutes: 60,
168
+ description: 'Email each buyer one review request, with a single-use link per product, ' + 'days after their order is fulfilled (AGL-3736).',
169
+ lockdown: {
170
+ scope: 'per-host'
171
+ },
172
+ handler: async (gate)=>{
173
+ if (!isEmailConfigured()) return;
174
+ const { scanReviewRequests } = await import("./server/review-requests.js");
175
+ const { sent } = await scanReviewRequests(gate);
176
+ if (sent) console.info(`commerce: sent ${sent} review requests`);
177
+ }
178
+ });
157
179
  /**
158
180
  * The missing-decrement detector (AGL-2358).
159
181
  *
@@ -343,6 +365,11 @@ registerPluginJob({
343
365
  registerProductDraftWriter();
344
366
  // …and the operation an AI build plans for it, which that writer executes.
345
367
  registerProductAiCapability();
368
+ // …and the store's shipping, pickup, local delivery and tax settings an AI
369
+ // build sets up (AGL-3749), written live as the console's cards write them,
370
+ // with the four operations that writer executes.
371
+ registerStoreSetupAiWriter();
372
+ registerStoreSetupAiCapabilities();
346
373
  // …and why a file somebody is SELLING may not be made public (AGL-3080).
347
374
  // The media library asks before it hands an asset its permanent CDN URL
348
375
  // back; what a product is, and which of its fields hold paid media, is
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","req","res","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","localFulfillmentHandler","productSaveHandler","productStockHandler","orderNoteHandler","orderRestockAnswerHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,0BAA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M,MAAM,CAAC,0BAAsB,EAAGM,gBAAgB,CAAChB,SAASU;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpEnI,uBACE,iCACA;QACEsH,KAAK,OAAOC,SAASU,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGO,iBAAiB,CAACjB,SAASU;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnCnI,uBAAuB,gCAAgC,OAAOmH,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGqB,yBAAyB,CAACtB,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvD/F,2BAA2B,IAAMd,cAAcmI,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","req","res","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","localFulfillmentHandler","productSaveHandler","productStockHandler","orderNoteHandler","orderRestockAnswerHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,gCAAgC,QAAQ,wCAAoC;AACrF,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,0BAAsB;AACjE,SAASC,uBAAuB,QAAQ,wDAAuD;AAC/F,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,0BAA0B,QAAQ,4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AKC;IAEvF,wEAAwE;IACxE,wEAAwE;IACxE,wEAAwE;IACxE,yEAAyE;IACzE,sEAAsE;IACtEvH,uBACE,gCACA;QACEyH,KAAK,OAAOC,SAASU,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,0BAAsB,EAAGM,gBAAgB,CAAChB,SAASU;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpEtI,uBACE,iCACA;QACEyH,KAAK,OAAOC,SAASU,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGO,iBAAiB,CAACjB,SAASU;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnCtI,uBAAuB,gCAAgC,OAAOsH,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGqB,yBAAyB,CAACtB,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDhG,2BAA2B,IAAMhB,cAAcsI,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
@@ -780,6 +780,64 @@ const ORDER_FOOTER_REASON = 'You’re receiving this because you placed an order
780
780
  ],
781
781
  footerReason: 'You’re receiving this because you started a checkout with {{host.businessName}}.'
782
782
  },
783
+ {
784
+ // AGL-3736: days after fulfilment, one per order, with a single-use
785
+ // link per product that opens its review form pre-verified.
786
+ key: 'review-request',
787
+ name: 'Review request',
788
+ description: 'Asks a buyer to review what they bought, a set number of days after ' + 'the order is fulfilled. One per order; each product has its own ' + 'single-use link. Turn it off or change the delay in Settings → Reviews.',
789
+ requiresFeature: 'productReviews',
790
+ pluginId: 'commerce',
791
+ plugin: 'Commerce',
792
+ control: 'besigner',
793
+ defaultSubject: 'How was your order from {{host.businessName}}?',
794
+ mergeTokens: [
795
+ ORDER_NUMBER_TOKEN,
796
+ {
797
+ name: 'review.products',
798
+ description: 'Each product to review, one per line, with its own review link',
799
+ sample: 'House Blend: https://shop.example.com/products/house-blend?review=…'
800
+ },
801
+ {
802
+ name: 'review.url',
803
+ description: 'The review link for the first product',
804
+ sample: 'https://shop.example.com/products/house-blend?review=…'
805
+ },
806
+ {
807
+ name: 'review.productName',
808
+ description: 'The first product’s name',
809
+ sample: 'House Blend'
810
+ }
811
+ ],
812
+ defaultBody: [
813
+ {
814
+ block: 'text',
815
+ text: 'How did we do?',
816
+ variant: 'heading'
817
+ },
818
+ {
819
+ block: 'text',
820
+ text: 'Thanks again for your order {{order.number}} from ' + '{{host.businessName}}. Would you tell other shoppers what you ' + 'think? Each link opens the product with a review form.',
821
+ variant: 'body'
822
+ },
823
+ {
824
+ block: 'text',
825
+ text: '{{review.products}}',
826
+ variant: 'body'
827
+ },
828
+ {
829
+ block: 'button',
830
+ label: 'Write a review',
831
+ href: '{{review.url}}'
832
+ },
833
+ {
834
+ block: 'text',
835
+ text: 'Each link works once, for 60 days.',
836
+ variant: 'caption'
837
+ }
838
+ ],
839
+ footerReason: ORDER_FOOTER_REASON
840
+ },
783
841
  {
784
842
  key: 'member-post',
785
843
  name: 'New member post',