@infuro/cms-core 1.0.34 → 1.0.36

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 (152) hide show
  1. package/README.md +13 -0
  2. package/dist/OrderTrackPage-W3J6WIG2.js +426 -0
  3. package/dist/OrderTrackPage-Z6FCJQYY.cjs +428 -0
  4. package/dist/admin.cjs +35254 -21613
  5. package/dist/admin.d.cts +192 -9
  6. package/dist/admin.d.ts +192 -9
  7. package/dist/admin.js +34301 -20755
  8. package/dist/api.cjs +137 -17531
  9. package/dist/api.d.cts +633 -3
  10. package/dist/api.d.ts +633 -3
  11. package/dist/api.js +15 -17528
  12. package/dist/auth.cjs +192 -1034
  13. package/dist/auth.d.cts +197 -54
  14. package/dist/auth.d.ts +197 -54
  15. package/dist/auth.js +4 -966
  16. package/dist/chunk-2AEVFOQP.cjs +30436 -0
  17. package/dist/chunk-3DZRIZOD.cjs +52 -0
  18. package/dist/chunk-5ELSW2UP.js +150 -0
  19. package/dist/chunk-7NMT3GBR.cjs +29 -0
  20. package/dist/chunk-COBORIJH.cjs +2373 -0
  21. package/dist/chunk-CRFV5WJK.js +16 -0
  22. package/dist/chunk-D5FBNKQM.cjs +104 -0
  23. package/dist/chunk-FG6I64HP.js +604 -0
  24. package/dist/chunk-GO7PPYNU.js +76 -0
  25. package/dist/chunk-HCIRL37O.js +21 -0
  26. package/dist/chunk-HF3L2GIT.cjs +194 -0
  27. package/dist/chunk-HT5DI3XW.cjs +82 -0
  28. package/dist/chunk-JC6DLWTE.js +21 -0
  29. package/dist/chunk-JS2W7XZ4.js +30312 -0
  30. package/dist/chunk-JXF23MPG.js +25 -0
  31. package/dist/chunk-KFFB6EMZ.js +123 -0
  32. package/dist/chunk-KPKFNLQQ.cjs +648 -0
  33. package/dist/chunk-LI2IXVAY.js +171 -0
  34. package/dist/chunk-MQBT33IV.js +48 -0
  35. package/dist/chunk-OOTLNH63.cjs +18 -0
  36. package/dist/chunk-PNOKNSG2.cjs +222 -0
  37. package/dist/chunk-SHUYVCID.js +4 -0
  38. package/dist/chunk-SPQFNIYJ.cjs +132 -0
  39. package/dist/chunk-SYBOCAWB.js +97 -0
  40. package/dist/chunk-TDV6EJHV.js +192 -0
  41. package/dist/chunk-UCKN4BBY.cjs +24 -0
  42. package/dist/chunk-UF3BYUXY.js +616 -0
  43. package/dist/chunk-UPLVMVRX.cjs +23 -0
  44. package/dist/chunk-USNT2KNT.cjs +6 -0
  45. package/dist/chunk-VMY2S32H.js +2342 -0
  46. package/dist/chunk-WEMDMVHQ.js +216 -0
  47. package/dist/chunk-WO2DW4AU.cjs +182 -0
  48. package/dist/chunk-X47PBV4I.js +79 -0
  49. package/dist/chunk-X6H5VBQ2.cjs +620 -0
  50. package/dist/chunk-XQ3QUHWR.cjs +83 -0
  51. package/dist/chunk-XW5ATPRW.cjs +155 -0
  52. package/dist/cli.cjs +107 -86
  53. package/dist/cli.js +66 -29
  54. package/dist/email-queue-CGZBVVAS.js +2 -0
  55. package/dist/email-queue-TPZWLTIV.cjs +23 -0
  56. package/dist/emit-order-notification-trigger-D2N3KFHL.cjs +16 -0
  57. package/dist/emit-order-notification-trigger-IVLWKKJL.js +3 -0
  58. package/dist/erp-config-enabled-CUMQ6N2V.cjs +11 -0
  59. package/dist/erp-config-enabled-T37X7T34.js +2 -0
  60. package/dist/erp-order-invoice-3YISSOWW.js +3 -0
  61. package/dist/erp-order-invoice-ZR5F2KTA.cjs +12 -0
  62. package/dist/event-order-defaults-EMWBIGL3.cjs +39 -0
  63. package/dist/event-order-defaults-SDRNAZHC.js +2 -0
  64. package/dist/hooks.cjs +259 -132
  65. package/dist/hooks.d.cts +42 -1
  66. package/dist/hooks.d.ts +42 -1
  67. package/dist/hooks.js +234 -91
  68. package/dist/index.cjs +3679 -22356
  69. package/dist/index.d.cts +2173 -643
  70. package/dist/index.d.ts +2173 -643
  71. package/dist/index.js +2587 -22119
  72. package/dist/interpolate-WAKPN56R.cjs +11 -0
  73. package/dist/interpolate-WDUWDF3I.js +2 -0
  74. package/dist/migrations/1779400000000-ConvertStatusToEnum.ts +142 -0
  75. package/dist/migrations/1779400000000-SeedDefaultCurrencies.ts +33 -0
  76. package/dist/migrations/1779500000000-VendorRolesAndPermissions.ts +102 -0
  77. package/dist/migrations/1779600000000-VendorRegistrationProfile.ts +52 -0
  78. package/dist/migrations/1779700000000-CollectionIsCatalog.ts +22 -0
  79. package/dist/migrations/1779710000000-CollectionPlatformCatalog.ts +60 -0
  80. package/dist/migrations/1779720000000-ProductCategoryPlatformCatalog.ts +157 -0
  81. package/dist/migrations/1779800000000-EventsAndEventProducts.ts +173 -0
  82. package/dist/migrations/1779810000000-BackfillVendorRoleEventsPermissions.ts +38 -0
  83. package/dist/migrations/1779820000000-FixProductsCategoryForeignKey.ts +70 -0
  84. package/dist/migrations/1779830000000-ProductTitleColumn.ts +32 -0
  85. package/dist/migrations/1779840000000-EventAboutAndVisibilityFields.ts +34 -0
  86. package/dist/migrations/1779850000000-EventCityCountrySplit.ts +43 -0
  87. package/dist/migrations/1779860000000-CreateCombos.ts +140 -0
  88. package/dist/migrations/1780100000000-OrderAttendeesEventId.ts +55 -0
  89. package/dist/migrations/1780110000000-EventContactFormId.ts +49 -0
  90. package/dist/migrations/1780130000000-ProductVariants.ts +54 -0
  91. package/dist/migrations/1780140000000-EventManagementEnhancements.ts +44 -0
  92. package/dist/migrations/1780160000000-EventRegistrationGstProductContactForm.ts +79 -0
  93. package/dist/migrations/1780170000000-ComboCurrencyPrices.ts +20 -0
  94. package/dist/migrations/1781110000000-VendorOwnerCombosPermission.ts +38 -0
  95. package/dist/migrations/1781120000000-RefundPoliciesAndRequests.ts +225 -0
  96. package/dist/migrations/1781130000000-CreateAttendees.ts +44 -0
  97. package/dist/migrations/1781140000000-EventOrderNotifications.ts +29 -0
  98. package/dist/migrations/1781150000000-EventNamedLists.ts +28 -0
  99. package/dist/migrations/1781160000000-RefundPolicyEventTiers.ts +27 -0
  100. package/dist/migrations/1781170000000-EventRefundPolicy.ts +42 -0
  101. package/dist/migrations/1781180000000-RemoveCartItemsUniqueConstraint.ts +15 -0
  102. package/dist/migrations/1781190000000-RenameProductTaxesToProductConfig.ts +84 -0
  103. package/dist/migrations/1781200000000-VendorOwnerProductConfigPermissions.ts +51 -0
  104. package/dist/migrations/1781210000000-VendorRoleProductConfigPermissions.ts +46 -0
  105. package/dist/migrations/1781220000000-AddWhatsappTriggerBindings.ts +23 -0
  106. package/dist/migrations/1781230000000-AddOrderNotificationTriggers.ts +46 -0
  107. package/dist/migrations/1781240000000-DropEventOrderNotificationColumns.ts +29 -0
  108. package/dist/migrations/1781250000000-RemoveOrderRefundedTrigger.ts +36 -0
  109. package/dist/migrations/helpers/vendor-role-seed.ts +243 -0
  110. package/dist/paid-order-erp-3USEG6WL.js +3 -0
  111. package/dist/paid-order-erp-FSQ3GSXE.cjs +12 -0
  112. package/dist/pg-boss-service-4XF2TQ2E.js +2 -0
  113. package/dist/pg-boss-service-L6MTF4EQ.cjs +15 -0
  114. package/dist/razorpay-KLO2KNCB.js +49 -0
  115. package/dist/razorpay-U23LGY72.cjs +56 -0
  116. package/dist/rbac-debug-db-HWP65A4O.cjs +35 -0
  117. package/dist/rbac-debug-db-QJH3AD34.js +33 -0
  118. package/dist/sms-defaults-2NL24H57.js +2 -0
  119. package/dist/sms-defaults-KCOPKQBA.cjs +19 -0
  120. package/dist/stripe-4FD27QVJ.js +51 -0
  121. package/dist/stripe-VU6OEG2D.cjs +57 -0
  122. package/dist/theme.cjs +31 -59
  123. package/dist/theme.d.cts +78 -3
  124. package/dist/theme.d.ts +78 -3
  125. package/dist/theme.js +23 -20
  126. package/dist/vendor-invite-status-77O7ZQ3U.cjs +19 -0
  127. package/dist/vendor-invite-status-PWJ3DE76.js +2 -0
  128. package/dist/whatsapp-trigger-dispatcher-ONHXI7UY.cjs +19 -0
  129. package/dist/whatsapp-trigger-dispatcher-PWFI4FKP.js +6 -0
  130. package/package.json +147 -142
  131. package/dist/admin.cjs.map +0 -1
  132. package/dist/admin.js.map +0 -1
  133. package/dist/api.cjs.map +0 -1
  134. package/dist/api.js.map +0 -1
  135. package/dist/auth.cjs.map +0 -1
  136. package/dist/auth.js.map +0 -1
  137. package/dist/cli.cjs.map +0 -1
  138. package/dist/cli.js.map +0 -1
  139. package/dist/config-DJ5CmQvS.d.cts +0 -8
  140. package/dist/config-DJ5CmQvS.d.ts +0 -8
  141. package/dist/hooks.cjs.map +0 -1
  142. package/dist/hooks.js.map +0 -1
  143. package/dist/index-Bf5GO8fu.d.cts +0 -583
  144. package/dist/index-DOiJuMQA.d.ts +0 -583
  145. package/dist/index.cjs.map +0 -1
  146. package/dist/index.js.map +0 -1
  147. package/dist/theme.cjs.map +0 -1
  148. package/dist/theme.js.map +0 -1
  149. package/dist/types-DCVaXlPV.d.cts +0 -78
  150. package/dist/types-DCVaXlPV.d.ts +0 -78
  151. package/dist/vendor-scope-DTYhJk_I.d.cts +0 -129
  152. package/dist/vendor-scope-DTYhJk_I.d.ts +0 -129
@@ -0,0 +1,2373 @@
1
+ 'use strict';
2
+
3
+ var chunkUCKN4BBY_cjs = require('./chunk-UCKN4BBY.cjs');
4
+ var chunkXW5ATPRW_cjs = require('./chunk-XW5ATPRW.cjs');
5
+ var chunkOOTLNH63_cjs = require('./chunk-OOTLNH63.cjs');
6
+ var chunkSPQFNIYJ_cjs = require('./chunk-SPQFNIYJ.cjs');
7
+ var chunkUSNT2KNT_cjs = require('./chunk-USNT2KNT.cjs');
8
+ var clientSes = require('@aws-sdk/client-ses');
9
+ var nodemailer = require('nodemailer');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var nodemailer__default = /*#__PURE__*/_interopDefault(nodemailer);
14
+
15
+ // src/lib/event-order-template-context.ts
16
+ function resolvePublicSiteUrl() {
17
+ if (typeof process !== "undefined") {
18
+ const u = (process.env.CMS_PUBLIC_URL || process.env.NEXT_PUBLIC_SITE_URL || "").trim();
19
+ if (u) return u.replace(/\/+$/, "");
20
+ const v = (process.env.VERCEL_URL || "").trim();
21
+ if (v) return v.startsWith("http") ? v.replace(/\/+$/, "") : `https://${v.replace(/\/+$/, "")}`;
22
+ }
23
+ return "";
24
+ }
25
+ chunkUSNT2KNT_cjs.__name(resolvePublicSiteUrl, "resolvePublicSiteUrl");
26
+ function buildOrderTrackUrl(qrToken, siteUrl) {
27
+ const token = qrToken?.trim();
28
+ if (!token) return "";
29
+ const base = (siteUrl ?? resolvePublicSiteUrl()).replace(/\/+$/, "");
30
+ if (!base) return `/track/${token}`;
31
+ return `${base}/track/${token}`;
32
+ }
33
+ chunkUSNT2KNT_cjs.__name(buildOrderTrackUrl, "buildOrderTrackUrl");
34
+ function buildOrderQrImageUrl(trackUrl, size = 200) {
35
+ if (!trackUrl.trim()) return "";
36
+ return `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(trackUrl)}`;
37
+ }
38
+ chunkUSNT2KNT_cjs.__name(buildOrderQrImageUrl, "buildOrderQrImageUrl");
39
+ function formatOrderDetailsText(input) {
40
+ const { orderNumber, total, currency, lines } = input;
41
+ const header = `Order: ${orderNumber}
42
+ Total: ${total} ${currency}`;
43
+ if (!lines.length) return header;
44
+ const items = lines.map((line) => `- ${line.name} \xD7 ${line.quantity} (${line.total} ${line.currency})`).join("\n");
45
+ return `${header}
46
+
47
+ Items:
48
+ ${items}`;
49
+ }
50
+ chunkUSNT2KNT_cjs.__name(formatOrderDetailsText, "formatOrderDetailsText");
51
+ function formatOrderDetailsHtml(input) {
52
+ const text = formatOrderDetailsText(input);
53
+ const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
54
+ return `<pre style="font-family:inherit;white-space:pre-wrap;margin:0">${escaped}</pre>`;
55
+ }
56
+ chunkUSNT2KNT_cjs.__name(formatOrderDetailsHtml, "formatOrderDetailsHtml");
57
+ function buildEventOrderTemplateVariables(input) {
58
+ const { event, order, contact, productNames, orderLines = [], siteUrl } = input;
59
+ const trackUrl = buildOrderTrackUrl(order.qrToken, siteUrl);
60
+ const qrImageUrl = buildOrderQrImageUrl(trackUrl);
61
+ const orderDetailsPayload = {
62
+ orderNumber: String(order.orderNumber ?? ""),
63
+ total: String(order.total ?? ""),
64
+ currency: String(order.currency ?? "INR"),
65
+ lines: orderLines
66
+ };
67
+ return {
68
+ eventName: event.name ?? "",
69
+ eventSlug: event.slug ?? "",
70
+ venue: event.venue ?? "",
71
+ startDate: formatEventDate(event.startDate),
72
+ orderNumber: String(order.orderNumber ?? ""),
73
+ orderTotal: String(order.total ?? ""),
74
+ currency: String(order.currency ?? "INR"),
75
+ customerName: contact.name?.trim() || contact.email?.split("@")[0] || "Guest",
76
+ customerEmail: contact.email?.trim() || "",
77
+ customerPhone: contact.phone?.trim() || "",
78
+ productNames,
79
+ trackUrl,
80
+ qrImageUrl,
81
+ orderDetails: formatOrderDetailsText(orderDetailsPayload),
82
+ orderDetailsHtml: formatOrderDetailsHtml(orderDetailsPayload)
83
+ };
84
+ }
85
+ chunkUSNT2KNT_cjs.__name(buildEventOrderTemplateVariables, "buildEventOrderTemplateVariables");
86
+ function formatEventDate(d) {
87
+ if (!d) return "";
88
+ try {
89
+ return new Date(d).toLocaleString(void 0, {
90
+ dateStyle: "medium",
91
+ timeStyle: "short"
92
+ });
93
+ } catch {
94
+ return String(d);
95
+ }
96
+ }
97
+ chunkUSNT2KNT_cjs.__name(formatEventDate, "formatEventDate");
98
+
99
+ // src/lib/order-notification-context.ts
100
+ async function loadOrderLines(dataSource, entityMap, orderId, currency) {
101
+ if (!entityMap.order_items) return [];
102
+ const itemRows = await dataSource.getRepository(entityMap.order_items).find({
103
+ where: {
104
+ orderId
105
+ },
106
+ relations: [
107
+ "product"
108
+ ],
109
+ order: {
110
+ id: "ASC"
111
+ }
112
+ });
113
+ return itemRows.map((item) => {
114
+ const row = item;
115
+ const name = row.product?.name || row.product?.title || `Product #${row.productId}`;
116
+ return {
117
+ name: String(name),
118
+ quantity: Number(row.quantity) || 1,
119
+ total: row.total,
120
+ currency
121
+ };
122
+ });
123
+ }
124
+ chunkUSNT2KNT_cjs.__name(loadOrderLines, "loadOrderLines");
125
+ async function loadPrimaryEvent(dataSource, entityMap, itemRows) {
126
+ if (!entityMap.event_products || !entityMap.events) {
127
+ return {
128
+ productNames: []
129
+ };
130
+ }
131
+ const epRepo = dataSource.getRepository(entityMap.event_products);
132
+ const eventRepo = dataSource.getRepository(entityMap.events);
133
+ const eventMap = /* @__PURE__ */ new Map();
134
+ for (const item of itemRows) {
135
+ const productId = item.productId;
136
+ const productName = item.product?.name || item.product?.title || `Product #${productId}`;
137
+ const eps = await epRepo.find({
138
+ where: {
139
+ productId,
140
+ isActive: true
141
+ }
142
+ });
143
+ for (const ep of eps) {
144
+ const eventId = ep.eventId;
145
+ const existing = eventMap.get(eventId);
146
+ if (existing) {
147
+ if (!existing.productNames.includes(String(productName))) {
148
+ existing.productNames.push(String(productName));
149
+ }
150
+ } else {
151
+ const event = await eventRepo.findOne({
152
+ where: {
153
+ id: eventId,
154
+ deleted: false
155
+ }
156
+ });
157
+ if (event) {
158
+ eventMap.set(eventId, {
159
+ event,
160
+ productNames: [
161
+ String(productName)
162
+ ]
163
+ });
164
+ }
165
+ }
166
+ }
167
+ }
168
+ const first = eventMap.values().next().value;
169
+ if (!first) return {
170
+ productNames: []
171
+ };
172
+ return {
173
+ event: first.event,
174
+ productNames: first.productNames
175
+ };
176
+ }
177
+ chunkUSNT2KNT_cjs.__name(loadPrimaryEvent, "loadPrimaryEvent");
178
+ async function loadOrderNotificationContexts(orderId, deps) {
179
+ if (!deps.entityMap.orders) return null;
180
+ const order = await deps.dataSource.getRepository(deps.entityMap.orders).findOne({
181
+ where: {
182
+ id: orderId,
183
+ deleted: false
184
+ },
185
+ relations: [
186
+ "contact"
187
+ ]
188
+ });
189
+ if (!order) return null;
190
+ const o = order;
191
+ const contact = o.contact ?? {};
192
+ const currency = String(o.currency ?? "INR");
193
+ const siteUrl = resolvePublicSiteUrl();
194
+ const itemRows = await deps.dataSource.getRepository(deps.entityMap.order_items).find({
195
+ where: {
196
+ orderId
197
+ },
198
+ relations: [
199
+ "product"
200
+ ],
201
+ order: {
202
+ id: "ASC"
203
+ }
204
+ });
205
+ const orderLines = await loadOrderLines(deps.dataSource, deps.entityMap, orderId, currency);
206
+ const { event, productNames: eventProductNames } = await loadPrimaryEvent(deps.dataSource, deps.entityMap, itemRows);
207
+ const allProductNames = orderLines.map((line) => line.name);
208
+ const productNames = eventProductNames.length > 0 ? eventProductNames.join(", ") : allProductNames.join(", ");
209
+ const variables = event ? buildEventOrderTemplateVariables({
210
+ event,
211
+ order: {
212
+ orderNumber: o.orderNumber,
213
+ total: o.total,
214
+ currency,
215
+ qrToken: o.qrToken
216
+ },
217
+ contact,
218
+ productNames,
219
+ orderLines,
220
+ siteUrl
221
+ }) : buildEventOrderTemplateVariables({
222
+ event: {
223
+ name: productNames || "Your order",
224
+ slug: "",
225
+ venue: "",
226
+ startDate: null
227
+ },
228
+ order: {
229
+ orderNumber: o.orderNumber,
230
+ total: o.total,
231
+ currency,
232
+ qrToken: o.qrToken
233
+ },
234
+ contact,
235
+ productNames,
236
+ orderLines,
237
+ siteUrl
238
+ });
239
+ return {
240
+ order: {
241
+ id: o.id,
242
+ orderNumber: String(o.orderNumber ?? ""),
243
+ total: o.total,
244
+ currency,
245
+ qrToken: o.qrToken
246
+ },
247
+ contact,
248
+ orderLines,
249
+ productNames,
250
+ event,
251
+ variables
252
+ };
253
+ }
254
+ chunkUSNT2KNT_cjs.__name(loadOrderNotificationContexts, "loadOrderNotificationContexts");
255
+
256
+ // src/plugins/whatsapp/whatsapp-queue.ts
257
+ var WHATSAPP_QUEUE_NAME = "whatsapp";
258
+ function maskPhone(raw) {
259
+ const digits = raw.replace(/\D/g, "");
260
+ if (digits.length <= 4) return "****";
261
+ return `${"*".repeat(Math.max(0, digits.length - 4))}${digits.slice(-4)}`;
262
+ }
263
+ chunkUSNT2KNT_cjs.__name(maskPhone, "maskPhone");
264
+ function registerWhatsAppQueueProcessor(cms) {
265
+ const queue = cms.getPlugin("queue");
266
+ const whatsapp = cms.getPlugin("whatsapp");
267
+ if (!queue) {
268
+ console.warn("[whatsapp] queue processor not registered: queue plugin missing");
269
+ return;
270
+ }
271
+ if (!whatsapp || typeof whatsapp.send !== "function") {
272
+ console.warn("[whatsapp] queue processor not registered: whatsapp plugin missing or not configured");
273
+ return;
274
+ }
275
+ queue.registerProcessor(WHATSAPP_QUEUE_NAME, async (data) => {
276
+ const payload = data;
277
+ if (!payload.to) {
278
+ console.warn("[whatsapp] queue job skipped: missing recipient");
279
+ return;
280
+ }
281
+ console.log("[whatsapp] queue job processing", {
282
+ to: maskPhone(payload.to),
283
+ templateKey: payload.templateKey ?? null,
284
+ externalTemplateRef: payload.externalTemplateRef ?? null
285
+ });
286
+ try {
287
+ const ok = await whatsapp.send(payload);
288
+ if (ok) {
289
+ console.log("[whatsapp] queue job completed", {
290
+ to: maskPhone(payload.to),
291
+ sent: true
292
+ });
293
+ } else {
294
+ console.warn("[whatsapp] queue job completed without delivery", {
295
+ to: maskPhone(payload.to),
296
+ sent: false
297
+ });
298
+ }
299
+ } catch (err) {
300
+ console.error("[whatsapp] queue job failed", {
301
+ to: maskPhone(payload.to),
302
+ error: err instanceof Error ? err.message : String(err)
303
+ });
304
+ }
305
+ });
306
+ console.log("[whatsapp] queue processor registered", {
307
+ queue: WHATSAPP_QUEUE_NAME
308
+ });
309
+ }
310
+ chunkUSNT2KNT_cjs.__name(registerWhatsAppQueueProcessor, "registerWhatsAppQueueProcessor");
311
+ async function queueWhatsApp(cms, payload) {
312
+ const queue = cms.getPlugin("queue");
313
+ if (queue) {
314
+ console.log("[whatsapp] enqueue", {
315
+ to: maskPhone(payload.to),
316
+ templateKey: payload.templateKey ?? null,
317
+ externalTemplateRef: payload.externalTemplateRef ?? null
318
+ });
319
+ await queue.add(WHATSAPP_QUEUE_NAME, payload);
320
+ return true;
321
+ }
322
+ const whatsapp = cms.getPlugin("whatsapp");
323
+ if (whatsapp && typeof whatsapp.send === "function") {
324
+ console.log("[whatsapp] no queue plugin \u2014 sending immediately", {
325
+ to: maskPhone(payload.to)
326
+ });
327
+ return whatsapp.send(payload);
328
+ }
329
+ console.warn("[whatsapp] send skipped: neither queue nor whatsapp plugin available", {
330
+ to: maskPhone(payload.to)
331
+ });
332
+ return false;
333
+ }
334
+ chunkUSNT2KNT_cjs.__name(queueWhatsApp, "queueWhatsApp");
335
+
336
+ // src/plugins/whatsapp/whatsapp-service.ts
337
+ function norm(v) {
338
+ const t = v?.trim();
339
+ return t || void 0;
340
+ }
341
+ chunkUSNT2KNT_cjs.__name(norm, "norm");
342
+ function pick(plugin, db, env, ...keys) {
343
+ for (const key of keys) {
344
+ const pk = key;
345
+ if (pk in plugin && plugin[pk] !== void 0 && String(plugin[pk]).trim() !== "") {
346
+ const v = norm(String(plugin[pk]));
347
+ if (v) return v;
348
+ }
349
+ if (norm(db[key])) return norm(db[key]);
350
+ if (norm(env[key])) return norm(env[key]);
351
+ }
352
+ return void 0;
353
+ }
354
+ chunkUSNT2KNT_cjs.__name(pick, "pick");
355
+ function mergeWhatsAppConfigLayers(env, db, plugin) {
356
+ return {
357
+ accessToken: pick(plugin, db, env, "accessToken", "WHATSAPP_ACCESS_TOKEN"),
358
+ phoneNumberId: pick(plugin, db, env, "phoneNumberId", "WHATSAPP_PHONE_NUMBER_ID"),
359
+ apiVersion: pick(plugin, db, env, "apiVersion", "WHATSAPP_API_VERSION") ?? "v21.0"
360
+ };
361
+ }
362
+ chunkUSNT2KNT_cjs.__name(mergeWhatsAppConfigLayers, "mergeWhatsAppConfigLayers");
363
+ function isWhatsAppPluginEnabled(db) {
364
+ const v = (db.enabled ?? "true").toLowerCase();
365
+ return v !== "false" && v !== "0";
366
+ }
367
+ chunkUSNT2KNT_cjs.__name(isWhatsAppPluginEnabled, "isWhatsAppPluginEnabled");
368
+ function whatsAppConfigured(config) {
369
+ return Boolean(config.accessToken?.trim() && config.phoneNumberId?.trim());
370
+ }
371
+ chunkUSNT2KNT_cjs.__name(whatsAppConfigured, "whatsAppConfigured");
372
+ function normalizeWhatsAppRecipient(to) {
373
+ const digits = to.replace(/\D/g, "");
374
+ return digits;
375
+ }
376
+ chunkUSNT2KNT_cjs.__name(normalizeWhatsAppRecipient, "normalizeWhatsAppRecipient");
377
+ function resolveMetaWhatsAppTemplateName(opts) {
378
+ const ref = opts.externalTemplateRef?.trim();
379
+ const rowName = opts.name?.trim();
380
+ if (ref && !/^\d+$/.test(ref)) return ref;
381
+ if (rowName) return rowName;
382
+ return ref || void 0;
383
+ }
384
+ chunkUSNT2KNT_cjs.__name(resolveMetaWhatsAppTemplateName, "resolveMetaWhatsAppTemplateName");
385
+ function maskPhone2(digits) {
386
+ if (digits.length <= 4) return "****";
387
+ return `${"*".repeat(Math.max(0, digits.length - 4))}${digits.slice(-4)}`;
388
+ }
389
+ chunkUSNT2KNT_cjs.__name(maskPhone2, "maskPhone");
390
+ function logWhatsApp(level, message, extra) {
391
+ const line = extra ? `${message} ${JSON.stringify(extra)}` : message;
392
+ if (level === "info") console.log(`[whatsapp] ${line}`);
393
+ else if (level === "warn") console.warn(`[whatsapp] ${line}`);
394
+ else console.error(`[whatsapp] ${line}`);
395
+ }
396
+ chunkUSNT2KNT_cjs.__name(logWhatsApp, "logWhatsApp");
397
+ var WhatsAppService = class {
398
+ static {
399
+ chunkUSNT2KNT_cjs.__name(this, "WhatsAppService");
400
+ }
401
+ getWhatsAppSettings;
402
+ config;
403
+ getMessageTemplateRow;
404
+ constructor(env, plugin = {}, getWhatsAppSettings, getMessageTemplateRow) {
405
+ this.getWhatsAppSettings = getWhatsAppSettings;
406
+ this.getMessageTemplateRow = getMessageTemplateRow;
407
+ this.config = mergeWhatsAppConfigLayers(env, {}, plugin);
408
+ }
409
+ async mergedConfig() {
410
+ let db = {};
411
+ try {
412
+ db = await this.getWhatsAppSettings?.() ?? {};
413
+ } catch {
414
+ }
415
+ return mergeWhatsAppConfigLayers((typeof process !== "undefined" ? process.env : {}) ?? {}, db, this.config);
416
+ }
417
+ async send(opts) {
418
+ const cfg = await this.mergedConfig();
419
+ if (!whatsAppConfigured(cfg)) {
420
+ logWhatsApp("warn", "send skipped: not configured (Plugins \u2192 WhatsApp or WHATSAPP_ACCESS_TOKEN + WHATSAPP_PHONE_NUMBER_ID)");
421
+ return false;
422
+ }
423
+ const to = normalizeWhatsAppRecipient(opts.to);
424
+ if (!to) {
425
+ logWhatsApp("warn", "send skipped: invalid recipient", {
426
+ rawTo: opts.to
427
+ });
428
+ return false;
429
+ }
430
+ logWhatsApp("info", "send started", {
431
+ to: maskPhone2(to),
432
+ templateKey: opts.templateKey ?? null,
433
+ externalTemplateRef: opts.externalTemplateRef ?? null,
434
+ phoneNumberId: cfg.phoneNumberId
435
+ });
436
+ let templateName = resolveMetaWhatsAppTemplateName({
437
+ externalTemplateRef: opts.externalTemplateRef
438
+ });
439
+ let templateLanguage = opts.templateLanguage?.trim();
440
+ let body = opts.body?.trim() ?? "";
441
+ const variables = opts.variables ?? {};
442
+ if (opts.templateKey?.trim() && this.getMessageTemplateRow) {
443
+ const { resolveEventOrderTemplate: resolveEventOrderTemplate2, EVENT_ORDER_TEMPLATE_KEY } = await import('./event-order-defaults-EMWBIGL3.cjs');
444
+ if (opts.templateKey.trim() === EVENT_ORDER_TEMPLATE_KEY) {
445
+ const resolved = await resolveEventOrderTemplate2("whatsapp", async (ch, key) => {
446
+ const row = await this.getMessageTemplateRow(ch, key);
447
+ if (!row) return null;
448
+ return {
449
+ subject: null,
450
+ body: row.body,
451
+ externalTemplateRef: row.externalTemplateRef,
452
+ enabled: row.enabled
453
+ };
454
+ });
455
+ if (resolved && !resolved.enabled) {
456
+ logWhatsApp("warn", "send skipped: template disabled in message_templates", {
457
+ templateKey: opts.templateKey
458
+ });
459
+ return false;
460
+ }
461
+ if (resolved) {
462
+ body = resolved.body;
463
+ if (resolved.externalTemplateRef) templateName = resolved.externalTemplateRef;
464
+ }
465
+ }
466
+ }
467
+ const { applyTemplateVars: applyTemplateVars2 } = await import('./interpolate-WAKPN56R.cjs');
468
+ if (body) body = applyTemplateVars2(body, variables);
469
+ if (templateName) {
470
+ const paramValues = opts.templateParamOrder?.length ? opts.templateParamOrder.map((key) => String(variables[key] ?? "").slice(0, 1024)) : Object.keys(variables).length ? Object.values(variables) : body ? [
471
+ body
472
+ ] : [];
473
+ logWhatsApp("info", "sending template message", {
474
+ to: maskPhone2(to),
475
+ templateName,
476
+ paramCount: paramValues.length,
477
+ paramOrder: opts.templateParamOrder ?? null
478
+ });
479
+ return this.sendTemplateMessage(cfg, to, templateName, paramValues, templateLanguage);
480
+ }
481
+ if (!body) {
482
+ logWhatsApp("warn", "send skipped: no template name and empty body", {
483
+ to: maskPhone2(to)
484
+ });
485
+ return false;
486
+ }
487
+ logWhatsApp("info", "sending text message", {
488
+ to: maskPhone2(to),
489
+ bodyLength: body.length
490
+ });
491
+ return this.sendTextMessage(cfg, to, body);
492
+ }
493
+ async sendTextMessage(cfg, to, body) {
494
+ const url = `https://graph.facebook.com/${cfg.apiVersion}/${cfg.phoneNumberId}/messages`;
495
+ const res = await fetch(url, {
496
+ method: "POST",
497
+ headers: {
498
+ Authorization: `Bearer ${cfg.accessToken}`,
499
+ "Content-Type": "application/json"
500
+ },
501
+ body: JSON.stringify({
502
+ messaging_product: "whatsapp",
503
+ to,
504
+ type: "text",
505
+ text: {
506
+ body
507
+ }
508
+ })
509
+ });
510
+ if (!res.ok) {
511
+ const errText = await res.text().catch(() => "");
512
+ logWhatsApp("error", "text send failed", {
513
+ status: res.status,
514
+ to: maskPhone2(to),
515
+ error: errText
516
+ });
517
+ return false;
518
+ }
519
+ const data = await res.json().catch(() => ({}));
520
+ logWhatsApp("info", "text send succeeded", {
521
+ to: maskPhone2(to),
522
+ messageId: data.messages?.[0]?.id ?? null
523
+ });
524
+ return true;
525
+ }
526
+ async sendTemplateMessage(cfg, to, templateName, paramValues, templateLanguage) {
527
+ const components = paramValues.length > 0 ? [
528
+ {
529
+ type: "body",
530
+ parameters: paramValues.map((text) => ({
531
+ type: "text",
532
+ text: String(text).slice(0, 1024)
533
+ }))
534
+ }
535
+ ] : void 0;
536
+ const url = `https://graph.facebook.com/${cfg.apiVersion}/${cfg.phoneNumberId}/messages`;
537
+ const payload = {
538
+ messaging_product: "whatsapp",
539
+ to,
540
+ type: "template",
541
+ template: {
542
+ name: templateName,
543
+ language: {
544
+ code: templateLanguage?.trim() || "en"
545
+ },
546
+ ...components ? {
547
+ components
548
+ } : {}
549
+ }
550
+ };
551
+ const res = await fetch(url, {
552
+ method: "POST",
553
+ headers: {
554
+ Authorization: `Bearer ${cfg.accessToken}`,
555
+ "Content-Type": "application/json"
556
+ },
557
+ body: JSON.stringify(payload)
558
+ });
559
+ if (!res.ok) {
560
+ const errText = await res.text().catch(() => "");
561
+ logWhatsApp("error", "template send failed", {
562
+ status: res.status,
563
+ to: maskPhone2(to),
564
+ templateName,
565
+ paramCount: paramValues.length,
566
+ error: errText
567
+ });
568
+ return false;
569
+ }
570
+ const data = await res.json().catch(() => ({}));
571
+ logWhatsApp("info", "template send succeeded", {
572
+ to: maskPhone2(to),
573
+ templateName,
574
+ messageId: data.messages?.[0]?.id ?? null
575
+ });
576
+ return true;
577
+ }
578
+ };
579
+
580
+ // src/plugins/email/templates/layout.ts
581
+ function escapeHtml(s) {
582
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
583
+ }
584
+ chunkUSNT2KNT_cjs.__name(escapeHtml, "escapeHtml");
585
+ function socialLinkInnerHtml(s) {
586
+ if (s.iconUrl?.trim()) {
587
+ return `<img src="${escapeHtml(s.iconUrl.trim())}" alt="" width="20" height="20" style="display:inline-block;vertical-align:middle;border:0;" />`;
588
+ }
589
+ const label = s.icon && s.icon.trim() || "\u{1F517}";
590
+ return escapeHtml(label);
591
+ }
592
+ chunkUSNT2KNT_cjs.__name(socialLinkInnerHtml, "socialLinkInnerHtml");
593
+ function supportLinesHtml(supportEmail, supportPhone, opts) {
594
+ const parts = [];
595
+ const top = opts?.tightTop ? "margin-top:0;" : "margin-top:4px;";
596
+ if (supportEmail) {
597
+ parts.push(`<div style="font-size:13px;color:#444;${top}">&#128231; ${escapeHtml(supportEmail)}</div>`);
598
+ }
599
+ if (supportPhone) {
600
+ parts.push(`<div style="font-size:13px;color:#444;margin-top:2px;">&#128222; ${escapeHtml(supportPhone)}</div>`);
601
+ }
602
+ return parts.join("");
603
+ }
604
+ chunkUSNT2KNT_cjs.__name(supportLinesHtml, "supportLinesHtml");
605
+ function renderLayout(options) {
606
+ const { bodyHtml, companyDetails } = options;
607
+ const { logoUrl, companyName, supportEmail, supportPhone, socialLinks, footerDisclaimer, followUsTitle = "Follow Us" } = companyDetails;
608
+ const supportFooterHtml = supportLinesHtml(supportEmail, supportPhone, {
609
+ tightTop: true
610
+ });
611
+ const hasSocial = Boolean(socialLinks?.length);
612
+ const brandFooterInner = [];
613
+ if (logoUrl) {
614
+ brandFooterInner.push(`<img src="${escapeHtml(logoUrl)}" alt="" style="max-height:28px;max-width:160px;height:auto;width:auto;display:inline-block;vertical-align:middle;margin-right:10px;border:0;" />`);
615
+ }
616
+ if (companyName) {
617
+ brandFooterInner.push(`<span style="font-size:14px;font-weight:600;color:#111;vertical-align:middle;">${escapeHtml(companyName)}</span>`);
618
+ }
619
+ const brandFooterHtml = brandFooterInner.length ? `<div style="line-height:1.4;">${brandFooterInner.join("")}</div>` : "";
620
+ const followTitleHtml = hasSocial && followUsTitle ? `<div class="footer-follow-title" style="font-size:13px;font-weight:600;color:#555;margin:0;">${escapeHtml(followUsTitle)}</div>` : "";
621
+ const socialRowHtml = hasSocial && socialLinks ? `<div class="footer-social-icons" style="margin-top:6px;text-align:left;font-size:0;line-height:0;">${socialLinks.map((s) => `<a href="${escapeHtml(s.url)}" style="display:inline-block;margin-right:12px;text-decoration:none;color:#333;font-size:18px;line-height:1;vertical-align:middle;">${socialLinkInnerHtml(s)}</a>`).join("")}</div>` : "";
622
+ const rowSupport = supportFooterHtml ? `<tr><td class="footer-support-cell" colspan="2" valign="top" style="padding:0 0 10px 0;">${supportFooterHtml}</td></tr>` : "";
623
+ let footerBlock = "";
624
+ if (brandFooterHtml || followTitleHtml || socialRowHtml || footerDisclaimer || rowSupport) {
625
+ const rowBrand = brandFooterHtml ? `<tr><td class="footer-brand-cell" colspan="2" valign="top" style="padding:0 0 10px 0;">${brandFooterHtml}</td></tr>` : "";
626
+ const rowFollowTitle = followTitleHtml ? `<tr><td class="footer-follow-cell" colspan="2" valign="top" style="padding:14px 0 0 0;text-align:left;">${followTitleHtml}</td></tr>` : "";
627
+ const rowSocial = socialRowHtml ? `<tr><td class="footer-social-cell" colspan="2" style="padding:0;text-align:left;">${socialRowHtml}</td></tr>` : "";
628
+ footerBlock = `<table role="presentation" class="footer-main" width="100%" cellpadding="0" cellspacing="0" style="margin-top:28px;padding-top:16px;">${rowBrand}${rowSupport}${rowFollowTitle}${rowSocial}</table>`;
629
+ }
630
+ const disclaimerBlock = footerDisclaimer ? `<div style="margin-top:20px;padding-top:12px;font-size:11px;line-height:1.5;color:#888;">${escapeHtml(footerDisclaimer).replace(/\n/g, "<br/>")}</div>` : "";
631
+ const responsiveCss = `
632
+ @media only screen and (max-width: 600px) {
633
+ .email-wrap { padding-left: 12px !important; padding-right: 12px !important; }
634
+ .footer-follow-cell { padding-top: 12px !important; }
635
+ }
636
+ `;
637
+ return `<!DOCTYPE html>
638
+ <html>
639
+ <head>
640
+ <meta charset="utf-8">
641
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
642
+ <style type="text/css">${responsiveCss}</style>
643
+ </head>
644
+ <body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:14px;line-height:1.5;color:#333;background:#fff;">
645
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#fff;">
646
+ <tr><td class="email-wrap" style="padding:16px;">
647
+ <div>
648
+ ${bodyHtml}
649
+ </div>
650
+ ${footerBlock}
651
+ ${disclaimerBlock}
652
+ </td></tr>
653
+ </table>
654
+ </body>
655
+ </html>`;
656
+ }
657
+ chunkUSNT2KNT_cjs.__name(renderLayout, "renderLayout");
658
+
659
+ // src/plugins/email/templates/types.ts
660
+ function normalizeSocialLinkItem(o) {
661
+ const url = String(o.url ?? "").trim();
662
+ if (!url) return null;
663
+ let iconUrl = String(o.iconUrl ?? o.icon_image ?? "").trim();
664
+ let icon = String(o.icon ?? "").trim();
665
+ if (!iconUrl && /^https?:\/\//i.test(icon)) {
666
+ iconUrl = icon;
667
+ icon = "";
668
+ }
669
+ const item = {
670
+ url
671
+ };
672
+ if (iconUrl) item.iconUrl = iconUrl;
673
+ if (icon) item.icon = icon;
674
+ return item;
675
+ }
676
+ chunkUSNT2KNT_cjs.__name(normalizeSocialLinkItem, "normalizeSocialLinkItem");
677
+ function parseSocialLinksJson(raw) {
678
+ if (raw == null || raw.trim() === "") return void 0;
679
+ try {
680
+ const parsed = JSON.parse(raw);
681
+ if (!Array.isArray(parsed)) return void 0;
682
+ const out = [];
683
+ for (const item of parsed) {
684
+ if (item && typeof item === "object" && "url" in item) {
685
+ const n = normalizeSocialLinkItem(item);
686
+ if (n) out.push(n);
687
+ }
688
+ }
689
+ return out.length ? out : void 0;
690
+ } catch {
691
+ return void 0;
692
+ }
693
+ }
694
+ chunkUSNT2KNT_cjs.__name(parseSocialLinksJson, "parseSocialLinksJson");
695
+ function mergeEmailLayoutCompanyDetails(branding, emailSettings) {
696
+ const fromBranding = getCompanyDetailsFromSettings(branding);
697
+ const pick2 = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((emailVal, fallback) => {
698
+ const t = emailVal?.trim();
699
+ return t || fallback?.trim() || void 0;
700
+ }, "pick");
701
+ const logoUrl = pick2(emailSettings.logoUrl ?? emailSettings.emailLogoUrl, fromBranding.logoUrl);
702
+ const companyName = pick2(emailSettings.companyName ?? emailSettings.emailCompanyName, fromBranding.companyName);
703
+ const supportEmail = pick2(emailSettings.supportEmail ?? emailSettings.emailSupportEmail, fromBranding.supportEmail);
704
+ const supportPhone = pick2(emailSettings.supportPhone, void 0);
705
+ const footerDisclaimer = pick2(emailSettings.footerDisclaimer, void 0);
706
+ const followUsTitle = pick2(emailSettings.followUsTitle, "Follow Us") || "Follow Us";
707
+ const socialFromEmail = parseSocialLinksJson(emailSettings.socialLinks);
708
+ const socialLinks = socialFromEmail?.length ? socialFromEmail : fromBranding.socialLinks;
709
+ return {
710
+ logoUrl,
711
+ companyName,
712
+ supportEmail,
713
+ supportPhone,
714
+ socialLinks,
715
+ footerDisclaimer,
716
+ followUsTitle
717
+ };
718
+ }
719
+ chunkUSNT2KNT_cjs.__name(mergeEmailLayoutCompanyDetails, "mergeEmailLayoutCompanyDetails");
720
+ function getCompanyDetailsFromSettings(settingsGroup) {
721
+ const logoUrl = settingsGroup.logo ?? settingsGroup.logoUrl ?? "";
722
+ const companyName = settingsGroup.companyName ?? settingsGroup.company_name ?? "";
723
+ const supportEmail = settingsGroup.supportEmail ?? settingsGroup.support_email ?? "";
724
+ let socialLinks = [];
725
+ const raw = settingsGroup.socialLinks ?? settingsGroup.social_links;
726
+ if (typeof raw === "string") {
727
+ try {
728
+ const arr = JSON.parse(raw);
729
+ if (Array.isArray(arr)) {
730
+ for (const item of arr) {
731
+ if (item && typeof item === "object") {
732
+ const n = normalizeSocialLinkItem(item);
733
+ if (n) socialLinks.push(n);
734
+ }
735
+ }
736
+ }
737
+ } catch {
738
+ }
739
+ }
740
+ return {
741
+ logoUrl: logoUrl || void 0,
742
+ companyName: companyName || void 0,
743
+ supportEmail: supportEmail || void 0,
744
+ socialLinks: socialLinks.length ? socialLinks : void 0
745
+ };
746
+ }
747
+ chunkUSNT2KNT_cjs.__name(getCompanyDetailsFromSettings, "getCompanyDetailsFromSettings");
748
+
749
+ // src/plugins/email/templates/inline-cta.ts
750
+ function escapeHtml2(s) {
751
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
752
+ }
753
+ chunkUSNT2KNT_cjs.__name(escapeHtml2, "escapeHtml");
754
+ function escapeAttr(s) {
755
+ return escapeHtml2(s);
756
+ }
757
+ chunkUSNT2KNT_cjs.__name(escapeAttr, "escapeAttr");
758
+ function primaryCtaButton(href, label) {
759
+ return `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:20px 0;">
760
+ <tr><td style="border-radius:6px;background:#1a1a1a;">
761
+ <a href="${escapeAttr(href)}" style="display:inline-block;padding:12px 22px;font-size:14px;font-weight:600;color:#ffffff;text-decoration:none;">${escapeHtml2(label)}</a>
762
+ </td></tr>
763
+ </table>`;
764
+ }
765
+ chunkUSNT2KNT_cjs.__name(primaryCtaButton, "primaryCtaButton");
766
+
767
+ // src/plugins/email/templates/signup.ts
768
+ function render(ctx) {
769
+ const { name, loginUrl, verifyEmailUrl, companyDetails } = ctx;
770
+ if (verifyEmailUrl) {
771
+ const subject2 = "Confirm your email";
772
+ const greeting = name && name.trim() ? `Hi ${escapeHtml2(name.trim())},` : "Hi,";
773
+ const bodyHtml2 = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
774
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Thanks for signing up. Please confirm your email address to activate your account. Until you confirm, you won\u2019t be able to sign in.</p>
775
+ ${primaryCtaButton(verifyEmailUrl, "Confirm email address")}
776
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">This link expires in a few days. If you didn\u2019t create an account, you can ignore this message.<br/><span style="word-break:break-all;">${escapeHtml2(verifyEmailUrl)}</span></p>`;
777
+ const text2 = [
778
+ greeting,
779
+ "",
780
+ "Confirm your email to activate your account:",
781
+ verifyEmailUrl,
782
+ "",
783
+ "You cannot sign in until your email is confirmed."
784
+ ].join("\n");
785
+ const html2 = renderLayout({
786
+ bodyHtml: bodyHtml2,
787
+ companyDetails
788
+ });
789
+ return {
790
+ subject: subject2,
791
+ html: html2,
792
+ text: text2
793
+ };
794
+ }
795
+ const subject = "Welcome";
796
+ const bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Welcome${name ? `, ${escapeHtml2(name)}` : ""}.</p><p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Your account has been created.</p>${loginUrl ? `${primaryCtaButton(loginUrl, "Sign in")}` : ""}`;
797
+ const text = `Welcome${name ? `, ${name}` : ""}. Your account has been created.${loginUrl ? ` Sign in: ${loginUrl}` : ""}`;
798
+ const html = renderLayout({
799
+ bodyHtml,
800
+ companyDetails
801
+ });
802
+ return {
803
+ subject,
804
+ html,
805
+ text
806
+ };
807
+ }
808
+ chunkUSNT2KNT_cjs.__name(render, "render");
809
+
810
+ // src/plugins/email/templates/passwordReset.ts
811
+ function render2(ctx) {
812
+ const { resetLink, companyDetails } = ctx;
813
+ const subject = "Reset your password";
814
+ const bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Hello,</p>
815
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">We received a request to reset the password for your account. If you made this request, use the button below to choose a new password.</p>
816
+ <p style="margin:0 0 8px 0;font-size:14px;line-height:1.5;color:#555;">For your security, this link will stop working after a short time. If it expires, request a new reset from the sign-in page.</p>
817
+ ${primaryCtaButton(resetLink, "Reset password")}
818
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">If you did not request a password reset, you can safely ignore this email\u2014your password will stay the same.</p>
819
+ <p style="margin:12px 0 0 0;font-size:12px;line-height:1.5;color:#888;">If the button does not work, copy and paste this URL into your browser:<br/><span style="word-break:break-all;">${escapeHtml2(resetLink)}</span></p>`;
820
+ const text = [
821
+ "Hello,",
822
+ "",
823
+ "We received a request to reset your password. Open the link below to set a new password:",
824
+ resetLink,
825
+ "",
826
+ "This link expires after a limited time.",
827
+ "",
828
+ "If you did not request this, you can ignore this email."
829
+ ].join("\n");
830
+ const html = renderLayout({
831
+ bodyHtml,
832
+ companyDetails
833
+ });
834
+ return {
835
+ subject,
836
+ html,
837
+ text
838
+ };
839
+ }
840
+ chunkUSNT2KNT_cjs.__name(render2, "render");
841
+
842
+ // src/plugins/email/templates/passwordChange.ts
843
+ function render3(ctx) {
844
+ const { name, companyDetails } = ctx;
845
+ const subject = "Password changed";
846
+ const bodyHtml = `<h2>Password changed</h2><p>Your password has been updated successfully${name ? `, ${escapeHtml3(name)}` : ""}.</p>`;
847
+ const text = `Your password has been updated successfully${name ? `, ${name}` : ""}.`;
848
+ const html = renderLayout({
849
+ bodyHtml,
850
+ companyDetails
851
+ });
852
+ return {
853
+ subject,
854
+ html,
855
+ text
856
+ };
857
+ }
858
+ chunkUSNT2KNT_cjs.__name(render3, "render");
859
+ function escapeHtml3(s) {
860
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
861
+ }
862
+ chunkUSNT2KNT_cjs.__name(escapeHtml3, "escapeHtml");
863
+
864
+ // src/plugins/email/templates/orderPlaced.ts
865
+ function formatMoney(amount, currency) {
866
+ const v = typeof amount === "string" ? parseFloat(amount) : amount;
867
+ const num = Number.isFinite(v) ? Number(v).toFixed(2) : String(amount);
868
+ return currency ? `${num} ${currency}` : num;
869
+ }
870
+ chunkUSNT2KNT_cjs.__name(formatMoney, "formatMoney");
871
+ function renderLineItemsHtml(items, currency) {
872
+ if (!items.length) {
873
+ return '<p style="margin:12px 0 0 0;font-size:14px;color:#666;">No line items.</p>';
874
+ }
875
+ const rows = items.map((it) => {
876
+ const name = escapeHtml2(it.productName);
877
+ const sku = it.sku && String(it.sku).trim() ? `<span style="font-size:12px;color:#888;"> (${escapeHtml2(String(it.sku).trim())})</span>` : "";
878
+ const hsn = it.hsn && String(it.hsn).trim() ? `<br/><span style="font-size:11px;color:#888;">HSN: ${escapeHtml2(String(it.hsn).trim())}</span>` : "";
879
+ const taxNote = it.tax != null && String(it.tax).trim() && Number(it.tax) !== 0 ? `<br/><span style="font-size:11px;color:#888;">Tax: ${escapeHtml2(formatMoney(it.tax, currency))}</span>` : "";
880
+ return `<tr>
881
+ <td style="padding:10px 8px 10px 0;border-bottom:1px solid #eee;vertical-align:top;font-size:14px;color:#333;">${name}${sku}${hsn}${taxNote}</td>
882
+ <td align="right" style="padding:10px 8px;border-bottom:1px solid #eee;vertical-align:top;font-size:14px;color:#333;white-space:nowrap;">${escapeHtml2(String(it.quantity))}</td>
883
+ <td align="right" style="padding:10px 8px;border-bottom:1px solid #eee;vertical-align:top;font-size:14px;color:#333;white-space:nowrap;">${escapeHtml2(formatMoney(it.unitPrice, currency))}</td>
884
+ <td align="right" style="padding:10px 0 10px 8px;border-bottom:1px solid #eee;vertical-align:top;font-size:14px;color:#333;white-space:nowrap;">${escapeHtml2(formatMoney(it.lineTotal, currency))}</td>
885
+ </tr>`;
886
+ }).join("");
887
+ return `<p style="margin:16px 0 8px 0;font-size:14px;font-weight:600;color:#111;">Order items</p>
888
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">
889
+ <tr>
890
+ <td style="padding:0 8px 8px 0;font-size:12px;font-weight:600;color:#555;text-transform:uppercase;letter-spacing:0.02em;">Item</td>
891
+ <td align="right" style="padding:0 8px 8px 8px;font-size:12px;font-weight:600;color:#555;text-transform:uppercase;">Qty</td>
892
+ <td align="right" style="padding:0 8px 8px 8px;font-size:12px;font-weight:600;color:#555;text-transform:uppercase;">Price</td>
893
+ <td align="right" style="padding:0 0 8px 8px;font-size:12px;font-weight:600;color:#555;text-transform:uppercase;">Total</td>
894
+ </tr>
895
+ ${rows}
896
+ </table>`;
897
+ }
898
+ chunkUSNT2KNT_cjs.__name(renderLineItemsHtml, "renderLineItemsHtml");
899
+ function renderLineItemsText(items, currency) {
900
+ if (!items.length) return "";
901
+ const lines = items.map((it) => {
902
+ let s = `- ${it.productName} \xD7 ${it.quantity} @ ${formatMoney(it.unitPrice, currency)} = ${formatMoney(it.lineTotal, currency)}`;
903
+ if (it.sku) s += ` [${it.sku}]`;
904
+ if (it.hsn && String(it.hsn).trim()) s += ` HSN:${it.hsn}`;
905
+ if (it.tax != null && Number(it.tax) !== 0) s += ` tax:${formatMoney(it.tax, currency)}`;
906
+ return s;
907
+ });
908
+ return [
909
+ "Items:",
910
+ ...lines
911
+ ].join("\n");
912
+ }
913
+ chunkUSNT2KNT_cjs.__name(renderLineItemsText, "renderLineItemsText");
914
+ function formatAddressLines(addr) {
915
+ if (!addr || typeof addr !== "object") return [];
916
+ const parts = [
917
+ addr.line1,
918
+ addr.line2,
919
+ [
920
+ addr.city,
921
+ addr.state
922
+ ].filter(Boolean).join(", "),
923
+ addr.postalCode,
924
+ addr.country
925
+ ].filter((x) => x != null && String(x).trim() !== "");
926
+ return parts.map((p) => String(p).trim()).filter(Boolean);
927
+ }
928
+ chunkUSNT2KNT_cjs.__name(formatAddressLines, "formatAddressLines");
929
+ function renderAddressesHtml(billing, shipping) {
930
+ const bLines = formatAddressLines(billing);
931
+ const sLines = formatAddressLines(shipping);
932
+ if (!bLines.length && !sLines.length) return "";
933
+ let html = '<p style="margin:16px 0 8px 0;font-size:14px;font-weight:600;color:#111;">Addresses</p>';
934
+ if (bLines.length) {
935
+ html += `<p style="margin:0 0 4px 0;font-size:12px;font-weight:600;color:#555;">Billing</p><p style="margin:0 0 12px 0;font-size:14px;line-height:1.5;color:#333;">${bLines.map((l) => escapeHtml2(l)).join("<br/>")}</p>`;
936
+ }
937
+ if (sLines.length) {
938
+ html += `<p style="margin:0 0 4px 0;font-size:12px;font-weight:600;color:#555;">Shipping</p><p style="margin:0 0 0 0;font-size:14px;line-height:1.5;color:#333;">${sLines.map((l) => escapeHtml2(l)).join("<br/>")}</p>`;
939
+ }
940
+ return html;
941
+ }
942
+ chunkUSNT2KNT_cjs.__name(renderAddressesHtml, "renderAddressesHtml");
943
+ function renderAddressesText(billing, shipping) {
944
+ const bLines = formatAddressLines(billing);
945
+ const sLines = formatAddressLines(shipping);
946
+ const out = [];
947
+ if (bLines.length) out.push("Billing:", ...bLines.map((l) => ` ${l}`));
948
+ if (sLines.length) out.push("Shipping:", ...sLines.map((l) => ` ${l}`));
949
+ return out.length ? out.join("\n") : "";
950
+ }
951
+ chunkUSNT2KNT_cjs.__name(renderAddressesText, "renderAddressesText");
952
+ function render4(ctx) {
953
+ const { orderNumber, total, subtotal, tax, currency, customerName, companyDetails, audience = "customer", internalCustomerEmail, lineItems = [], billingAddress, shippingAddress } = ctx;
954
+ const itemsHtml = renderLineItemsHtml(lineItems, currency);
955
+ const itemsText = renderLineItemsText(lineItems, currency);
956
+ const addrHtml = renderAddressesHtml(billingAddress, shippingAddress);
957
+ const addrText = renderAddressesText(billingAddress, shippingAddress);
958
+ const subtotalLine = subtotal != null && String(subtotal).trim() !== "" ? `<p style="margin:8px 0 0 0;font-size:14px;line-height:1.5;color:#333;"><strong>Subtotal:</strong> ${escapeHtml2(String(subtotal))}${currency ? ` ${escapeHtml2(currency)}` : ""}</p>` : "";
959
+ const taxLine = tax != null && String(tax).trim() !== "" && Number(tax) !== 0 ? `<p style="margin:4px 0 0 0;font-size:14px;line-height:1.5;color:#333;"><strong>Tax:</strong> ${escapeHtml2(String(tax))}${currency ? ` ${escapeHtml2(currency)}` : ""}</p>` : "";
960
+ const totalLine = total != null && String(total).trim() !== "" ? `<p style="margin:12px 0 0 0;font-size:15px;line-height:1.5;color:#333;"><strong>Order total:</strong> ${escapeHtml2(String(total))}${currency ? ` ${escapeHtml2(currency)}` : ""}</p>` : "";
961
+ let subject;
962
+ let bodyHtml;
963
+ let text;
964
+ if (audience === "sales") {
965
+ subject = `New order #${orderNumber}`;
966
+ const who = customerName || internalCustomerEmail ? `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;"><strong>Customer:</strong> ${escapeHtml2(customerName || "\u2014")}${internalCustomerEmail ? ` <span style="color:#555;">(${escapeHtml2(internalCustomerEmail)})</span>` : ""}</p>` : "";
967
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">A new order has been placed and payment completed.</p>
968
+ <p style="margin:0 0 8px 0;font-size:15px;line-height:1.5;color:#333;"><strong>Order number:</strong> ${escapeHtml2(orderNumber)}</p>
969
+ ${who}
970
+ ${addrHtml}
971
+ ${itemsHtml}
972
+ ${subtotalLine}${taxLine}${totalLine}`;
973
+ text = [
974
+ `New order #${orderNumber}`,
975
+ customerName ? `Customer: ${customerName}` : "",
976
+ internalCustomerEmail ? `Email: ${internalCustomerEmail}` : "",
977
+ addrText,
978
+ itemsText,
979
+ subtotal != null ? `Subtotal: ${subtotal}${currency ? ` ${currency}` : ""}` : "",
980
+ tax != null && Number(tax) !== 0 ? `Tax: ${tax}${currency ? ` ${currency}` : ""}` : "",
981
+ total != null ? `Order total: ${total}${currency ? ` ${currency}` : ""}` : ""
982
+ ].filter(Boolean).join("\n\n");
983
+ } else {
984
+ subject = `Order confirmed #${orderNumber}`;
985
+ const thanksPlain = customerName && customerName.trim() ? `Thank you, ${customerName.trim()}.` : "Thank you for your order.";
986
+ const thanksHtml = `${escapeHtml2(thanksPlain)} We\u2019ve received your order and will process it shortly.`;
987
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${thanksHtml}</p>
988
+ <p style="margin:0 0 8px 0;font-size:15px;line-height:1.5;color:#333;"><strong>Order number:</strong> ${escapeHtml2(orderNumber)}</p>
989
+ ${addrHtml}
990
+ ${itemsHtml}
991
+ ${subtotalLine}${taxLine}${totalLine}
992
+ <p style="margin:16px 0 0 0;font-size:13px;line-height:1.5;color:#666;">If you have questions, reply to this email or contact us using the details below.</p>`;
993
+ text = [
994
+ `Order confirmed #${orderNumber}`,
995
+ `${thanksPlain} We\u2019ve received your order and will process it shortly.`,
996
+ "",
997
+ addrText,
998
+ itemsText,
999
+ subtotal != null ? `Subtotal: ${subtotal}${currency ? ` ${currency}` : ""}` : "",
1000
+ tax != null && Number(tax) !== 0 ? `Tax: ${tax}${currency ? ` ${currency}` : ""}` : "",
1001
+ total != null ? `Order total: ${total}${currency ? ` ${currency}` : ""}` : "",
1002
+ "",
1003
+ "We will process your order shortly."
1004
+ ].filter((line, i, arr) => !(line === "" && arr[i - 1] === "")).join("\n");
1005
+ }
1006
+ const html = renderLayout({
1007
+ bodyHtml,
1008
+ companyDetails
1009
+ });
1010
+ return {
1011
+ subject,
1012
+ html,
1013
+ text
1014
+ };
1015
+ }
1016
+ chunkUSNT2KNT_cjs.__name(render4, "render");
1017
+
1018
+ // src/plugins/email/templates/returnInitiated.ts
1019
+ function render5(ctx) {
1020
+ const { returnId, orderNumber, companyDetails } = ctx;
1021
+ const subject = "Return initiated";
1022
+ const bodyHtml = `<h2>Return initiated</h2><p>Your return request has been received.</p>${orderNumber ? `<p><strong>Order:</strong> ${escapeHtml4(orderNumber)}</p>` : ""}${returnId ? `<p><strong>Return ID:</strong> ${escapeHtml4(returnId)}</p>` : ""}`;
1023
+ const text = `Return initiated.${orderNumber ? ` Order: ${orderNumber}` : ""}${returnId ? ` Return ID: ${returnId}` : ""}`;
1024
+ const html = renderLayout({
1025
+ bodyHtml,
1026
+ companyDetails
1027
+ });
1028
+ return {
1029
+ subject,
1030
+ html,
1031
+ text
1032
+ };
1033
+ }
1034
+ chunkUSNT2KNT_cjs.__name(render5, "render");
1035
+ function escapeHtml4(s) {
1036
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1037
+ }
1038
+ chunkUSNT2KNT_cjs.__name(escapeHtml4, "escapeHtml");
1039
+
1040
+ // src/plugins/email/templates/shippingUpdate.ts
1041
+ function render6(ctx) {
1042
+ const { orderNumber, status, trackingUrl, companyDetails } = ctx;
1043
+ const subject = status ? `Shipping update: ${status}` : "Shipping update";
1044
+ const bodyHtml = `<h2>Shipping update</h2>${status ? `<p><strong>Status:</strong> ${escapeHtml5(status)}</p>` : ""}${orderNumber ? `<p><strong>Order:</strong> ${escapeHtml5(orderNumber)}</p>` : ""}${trackingUrl ? `<p><a href="${escapeHtml5(trackingUrl)}">Track your order</a></p>` : ""}`;
1045
+ const text = `Shipping update.${status ? ` Status: ${status}` : ""}${orderNumber ? ` Order: ${orderNumber}` : ""}${trackingUrl ? ` Track: ${trackingUrl}` : ""}`;
1046
+ const html = renderLayout({
1047
+ bodyHtml,
1048
+ companyDetails
1049
+ });
1050
+ return {
1051
+ subject,
1052
+ html,
1053
+ text
1054
+ };
1055
+ }
1056
+ chunkUSNT2KNT_cjs.__name(render6, "render");
1057
+ function escapeHtml5(s) {
1058
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1059
+ }
1060
+ chunkUSNT2KNT_cjs.__name(escapeHtml5, "escapeHtml");
1061
+
1062
+ // src/plugins/email/templates/invite.ts
1063
+ function render7(ctx) {
1064
+ const { inviteLink, email, inviteeName, companyDetails } = ctx;
1065
+ const subject = "You're invited";
1066
+ const greeting = inviteeName && inviteeName.trim() ? `Hello ${escapeHtml2(inviteeName.trim())},` : "Hello,";
1067
+ const bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
1068
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">You have been invited to create your account for <strong>${escapeHtml2(email)}</strong>. Use the secure link below to choose your password and activate access.</p>
1069
+ <p style="margin:0 0 8px 0;font-size:14px;line-height:1.5;color:#555;">This link is personal to you. If you did not expect this invitation, you can ignore this message.</p>
1070
+ ${primaryCtaButton(inviteLink, "Accept invitation & set password")}
1071
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">If the button does not work, copy and paste this URL into your browser:<br/><span style="word-break:break-all;">${escapeHtml2(inviteLink)}</span></p>`;
1072
+ const text = [
1073
+ inviteeName?.trim() ? `Hello ${inviteeName.trim()},` : "Hello,",
1074
+ "",
1075
+ `You have been invited to create your account (${email}).`,
1076
+ "Open this link to set your password:",
1077
+ inviteLink,
1078
+ "",
1079
+ "If you did not expect this invitation, you can ignore this email."
1080
+ ].join("\n");
1081
+ const html = renderLayout({
1082
+ bodyHtml,
1083
+ companyDetails
1084
+ });
1085
+ return {
1086
+ subject,
1087
+ html,
1088
+ text
1089
+ };
1090
+ }
1091
+ chunkUSNT2KNT_cjs.__name(render7, "render");
1092
+
1093
+ // src/plugins/email/templates/formSubmission.ts
1094
+ function render8(ctx) {
1095
+ const { formName, contactName, contactEmail, formData, formFieldRows, companyDetails } = ctx;
1096
+ const subject = `New Form Submission: ${formName}`;
1097
+ const fieldsBlock = formFieldRows && formFieldRows.length > 0 ? formFieldRows.map((r) => `<p style="margin:10px 0 0 0;line-height:1.5;"><strong>${escapeHtml6(r.label)}</strong><br/>${escapeHtml6(r.value)}</p>`).join("") : `<p style="margin:10px 0 0 0;font-size:13px;white-space:pre-wrap;">${escapeHtml6(JSON.stringify(formData, null, 2))}</p>`;
1098
+ const bodyHtml = `<p style="margin:0 0 6px 0;font-size:18px;font-weight:600;color:#111;">New Form Submission</p>
1099
+ <p style="margin:0 0 4px 0;"><strong>Form:</strong> ${escapeHtml6(formName)}</p>
1100
+ <p style="margin:0 0 8px 0;"><strong>Contact:</strong> ${escapeHtml6(contactName)}${contactEmail ? ` (${escapeHtml6(contactEmail)})` : ""}</p>
1101
+ ${fieldsBlock}`;
1102
+ const textLines = [
1103
+ "New Form Submission",
1104
+ `Form: ${formName}`,
1105
+ `Contact: ${contactName}${contactEmail ? ` (${contactEmail})` : ""}`,
1106
+ "",
1107
+ ...formFieldRows?.length ? formFieldRows.map((r) => `${r.label}: ${r.value}`) : [
1108
+ JSON.stringify(formData, null, 2)
1109
+ ]
1110
+ ];
1111
+ const text = textLines.join("\n");
1112
+ const html = renderLayout({
1113
+ bodyHtml,
1114
+ companyDetails
1115
+ });
1116
+ return {
1117
+ subject,
1118
+ html,
1119
+ text
1120
+ };
1121
+ }
1122
+ chunkUSNT2KNT_cjs.__name(render8, "render");
1123
+ function escapeHtml6(s) {
1124
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1125
+ }
1126
+ chunkUSNT2KNT_cjs.__name(escapeHtml6, "escapeHtml");
1127
+
1128
+ // src/plugins/email/templates/otp.ts
1129
+ function render9(ctx) {
1130
+ const { code, companyDetails } = ctx;
1131
+ const name = companyDetails.companyName?.trim() || "Our store";
1132
+ const bodyHtml = `
1133
+ <p>Your verification code is:</p>
1134
+ <p style="font-size:24px;font-weight:bold;letter-spacing:4px;">${escapeHtml7(code)}</p>
1135
+ <p style="color:#666;font-size:14px;">This code expires in 10 minutes. If you did not request it, you can ignore this email.</p>
1136
+ `;
1137
+ const html = renderLayout({
1138
+ bodyHtml,
1139
+ companyDetails
1140
+ });
1141
+ return {
1142
+ subject: `${name}: your sign-in code`,
1143
+ html,
1144
+ text: `Your code is ${code}. It expires in 10 minutes.`
1145
+ };
1146
+ }
1147
+ chunkUSNT2KNT_cjs.__name(render9, "render");
1148
+ function escapeHtml7(s) {
1149
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1150
+ }
1151
+ chunkUSNT2KNT_cjs.__name(escapeHtml7, "escapeHtml");
1152
+
1153
+ // src/plugins/email/templates/chatLead.ts
1154
+ function render10(ctx) {
1155
+ const { contactName, contactEmail, contactPhone, conversationId, latestMessage, intentCode, intentReason, transcript, companyDetails } = ctx;
1156
+ const intentDisplay = intentCode?.trim() ? `${intentCode.trim()}${intentReason?.trim() ? ` \u2014 ${intentReason.trim()}` : ""}` : intentReason;
1157
+ const subject = `Chat lead${intentCode?.trim() ? ` [${intentCode.trim()}]` : ""}: ${contactName || contactEmail || "Visitor"}`;
1158
+ const transcriptBlock = transcript?.trim() ? `<div style="margin-top:16px;padding:12px;background:#f9fafb;border-radius:6px;border:1px solid #e5e7eb;">
1159
+ <p style="margin:0 0 8px 0;font-size:13px;font-weight:600;color:#374151;">Recent conversation</p>
1160
+ <pre style="margin:0;font-size:12px;white-space:pre-wrap;font-family:inherit;color:#4b5563;">${escapeHtml8(transcript.trim())}</pre>
1161
+ </div>` : "";
1162
+ const bodyHtml = `<p style="margin:0 0 6px 0;font-size:18px;font-weight:600;color:#111;">New chat lead</p>
1163
+ <p style="margin:0 0 12px 0;font-size:14px;color:#374151;">A visitor showed interest based on your intent rules.</p>
1164
+ <table style="width:100%;border-collapse:collapse;font-size:14px;">
1165
+ <tr><td style="padding:4px 8px 4px 0;color:#6b7280;vertical-align:top;">Name</td><td>${escapeHtml8(contactName || "\u2014")}</td></tr>
1166
+ <tr><td style="padding:4px 8px 4px 0;color:#6b7280;vertical-align:top;">Email</td><td><a href="mailto:${escapeHtml8(contactEmail)}">${escapeHtml8(contactEmail)}</a></td></tr>
1167
+ <tr><td style="padding:4px 8px 4px 0;color:#6b7280;vertical-align:top;">Phone</td><td>${escapeHtml8(contactPhone?.trim() || "\u2014")}</td></tr>
1168
+ <tr><td style="padding:4px 8px 4px 0;color:#6b7280;vertical-align:top;">Conversation</td><td>#${conversationId}</td></tr>
1169
+ <tr><td style="padding:4px 8px 4px 0;color:#6b7280;vertical-align:top;">Intent</td><td>${escapeHtml8(intentReason)}</td></tr>
1170
+ </table>
1171
+ <p style="margin:16px 0 6px 0;font-size:13px;font-weight:600;color:#374151;">Latest message</p>
1172
+ <p style="margin:0;font-size:14px;white-space:pre-wrap;">${escapeHtml8(latestMessage)}</p>
1173
+ ${transcriptBlock}`;
1174
+ const text = [
1175
+ "New chat lead",
1176
+ `Name: ${contactName || "\u2014"}`,
1177
+ `Email: ${contactEmail}`,
1178
+ `Phone: ${contactPhone?.trim() || "\u2014"}`,
1179
+ `Conversation: #${conversationId}`,
1180
+ `Intent: ${intentDisplay}`,
1181
+ "",
1182
+ "Latest message:",
1183
+ latestMessage,
1184
+ transcript?.trim() ? `
1185
+ Recent conversation:
1186
+ ${transcript.trim()}` : ""
1187
+ ].join("\n");
1188
+ const html = renderLayout({
1189
+ bodyHtml,
1190
+ companyDetails
1191
+ });
1192
+ return {
1193
+ subject,
1194
+ html,
1195
+ text
1196
+ };
1197
+ }
1198
+ chunkUSNT2KNT_cjs.__name(render10, "render");
1199
+ function escapeHtml8(s) {
1200
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1201
+ }
1202
+ chunkUSNT2KNT_cjs.__name(escapeHtml8, "escapeHtml");
1203
+
1204
+ // src/plugins/email/templates/vendorOnboarded.ts
1205
+ function render11(ctx) {
1206
+ const { audience, activation, kind = "vendor_onboard", vendorName, vendorSlug, ownerName, ownerEmail, inviteLink, signInLink, companyDetails } = ctx;
1207
+ const storeLabel = vendorName.trim() || "your store";
1208
+ const greeting = ownerName && ownerName.trim() ? `Hello ${escapeHtml2(ownerName.trim())},` : "Hello,";
1209
+ const slugNote = vendorSlug && vendorSlug.trim() ? `<p style="margin:0 0 8px 0;font-size:14px;line-height:1.5;color:#555;"><strong>Store URL slug:</strong> ${escapeHtml2(vendorSlug.trim())}</p>` : "";
1210
+ let subject;
1211
+ let bodyHtml;
1212
+ let text;
1213
+ if (audience === "internal") {
1214
+ const action = kind === "team_invite" ? "A team member was invited to a vendor store." : activation === "invite" ? "A new vendor store was created and the owner was invited." : "A new vendor store was created with an active owner account.";
1215
+ subject = kind === "team_invite" ? `Team invite: ${storeLabel}` : `New vendor: ${storeLabel}`;
1216
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${action}</p>
1217
+ <p style="margin:0 0 8px 0;font-size:15px;line-height:1.5;color:#333;"><strong>Store:</strong> ${escapeHtml2(storeLabel)}</p>
1218
+ ${slugNote}
1219
+ <p style="margin:0 0 8px 0;font-size:15px;line-height:1.5;color:#333;"><strong>Owner / invitee:</strong> ${escapeHtml2(ownerName?.trim() || "\u2014")} <span style="color:#555;">(${escapeHtml2(ownerEmail)})</span></p>
1220
+ <p style="margin:0 0 0 0;font-size:14px;line-height:1.5;color:#555;"><strong>Activation:</strong> ${escapeHtml2(activation === "invite" ? "Invitation" : "Password set")}</p>`;
1221
+ text = [
1222
+ subject,
1223
+ "",
1224
+ action,
1225
+ `Store: ${storeLabel}`,
1226
+ vendorSlug ? `Slug: ${vendorSlug}` : "",
1227
+ `Owner / invitee: ${ownerName?.trim() || "\u2014"} (${ownerEmail})`,
1228
+ `Activation: ${activation === "invite" ? "Invitation" : "Password set"}`
1229
+ ].filter(Boolean).join("\n");
1230
+ } else if (kind === "team_invite" && activation === "invite" && inviteLink) {
1231
+ subject = `You're invited to ${storeLabel}`;
1232
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
1233
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">You have been invited to join the vendor team for <strong>${escapeHtml2(storeLabel)}</strong>. Use the secure link below to set your password and activate your account.</p>
1234
+ ${primaryCtaButton(inviteLink, "Accept invitation & set password")}
1235
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">If the button does not work, copy and paste this URL into your browser:<br/><span style="word-break:break-all;">${escapeHtml2(inviteLink)}</span></p>`;
1236
+ text = [
1237
+ ownerName?.trim() ? `Hello ${ownerName.trim()},` : "Hello,",
1238
+ "",
1239
+ `You have been invited to join ${storeLabel}.`,
1240
+ "Open this link to set your password:",
1241
+ inviteLink
1242
+ ].join("\n");
1243
+ } else if (activation === "invite" && inviteLink) {
1244
+ subject = `Your vendor store "${storeLabel}" is ready`;
1245
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
1246
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Your vendor store <strong>${escapeHtml2(storeLabel)}</strong> has been created. Accept the invitation below to set your password and access the admin dashboard.</p>
1247
+ ${slugNote}
1248
+ ${primaryCtaButton(inviteLink, "Accept invitation & set password")}
1249
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">If the button does not work, copy and paste this URL into your browser:<br/><span style="word-break:break-all;">${escapeHtml2(inviteLink)}</span></p>`;
1250
+ text = [
1251
+ ownerName?.trim() ? `Hello ${ownerName.trim()},` : "Hello,",
1252
+ "",
1253
+ `Your vendor store "${storeLabel}" has been created.`,
1254
+ "Open this link to set your password:",
1255
+ inviteLink
1256
+ ].join("\n");
1257
+ } else {
1258
+ subject = `Welcome to ${storeLabel}`;
1259
+ const loginUrl = signInLink?.trim() || inviteLink?.trim() || "";
1260
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
1261
+ <p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">Your vendor store <strong>${escapeHtml2(storeLabel)}</strong> has been created and your owner account is ready. Sign in to the admin dashboard to manage your store.</p>
1262
+ ${slugNote}
1263
+ ${loginUrl ? primaryCtaButton(loginUrl, "Sign in to admin") : ""}
1264
+ ${loginUrl ? `<p style="margin:16px 0 0 0;font-size:12px;line-height:1.5;color:#888;">Sign-in URL:<br/><span style="word-break:break-all;">${escapeHtml2(loginUrl)}</span></p>` : ""}`;
1265
+ text = [
1266
+ ownerName?.trim() ? `Hello ${ownerName.trim()},` : "Hello,",
1267
+ "",
1268
+ `Your vendor store "${storeLabel}" has been created.`,
1269
+ loginUrl ? `Sign in: ${loginUrl}` : ""
1270
+ ].filter(Boolean).join("\n");
1271
+ }
1272
+ const html = renderLayout({
1273
+ bodyHtml,
1274
+ companyDetails
1275
+ });
1276
+ return {
1277
+ subject,
1278
+ html,
1279
+ text
1280
+ };
1281
+ }
1282
+ chunkUSNT2KNT_cjs.__name(render11, "render");
1283
+
1284
+ // src/plugins/email/templates/index.ts
1285
+ var templateRenderMap = {
1286
+ signup: render,
1287
+ passwordReset: render2,
1288
+ passwordChange: render3,
1289
+ orderPlaced: render4,
1290
+ returnInitiated: render5,
1291
+ shippingUpdate: render6,
1292
+ invite: render7,
1293
+ formSubmission: render8,
1294
+ otp: render9,
1295
+ chatLead: render10,
1296
+ vendorOnboarded: render11
1297
+ };
1298
+ function getTemplateRenderer(name) {
1299
+ return templateRenderMap[name];
1300
+ }
1301
+ chunkUSNT2KNT_cjs.__name(getTemplateRenderer, "getTemplateRenderer");
1302
+
1303
+ // src/plugins/email/renderer.ts
1304
+ function renderEmail(templateName, ctx, options) {
1305
+ const layoutFn = options?.renderLayout ?? renderLayout;
1306
+ const getBody = options?.getBody;
1307
+ if (getBody) {
1308
+ const custom = getBody(templateName, ctx);
1309
+ if (custom != null) {
1310
+ const html = layoutFn({
1311
+ bodyHtml: custom.bodyHtml,
1312
+ companyDetails: ctx.companyDetails
1313
+ });
1314
+ return {
1315
+ subject: custom.subject,
1316
+ html,
1317
+ text: custom.text
1318
+ };
1319
+ }
1320
+ }
1321
+ const render12 = getTemplateRenderer(templateName);
1322
+ if (!render12) {
1323
+ throw new Error(`Unknown email template: ${templateName}`);
1324
+ }
1325
+ return render12(ctx);
1326
+ }
1327
+ chunkUSNT2KNT_cjs.__name(renderEmail, "renderEmail");
1328
+
1329
+ // src/plugins/email/email-service.ts
1330
+ var SES_REGIONS_WITHOUT_SMTP = /* @__PURE__ */ new Set([
1331
+ "af-south-1",
1332
+ "ap-south-2",
1333
+ "ap-southeast-3",
1334
+ "ap-southeast-5",
1335
+ "ca-west-1",
1336
+ "eu-central-2",
1337
+ "eu-south-1",
1338
+ "il-central-1",
1339
+ "me-central-1",
1340
+ "me-south-1"
1341
+ ]);
1342
+ function sesSmtpHost(region) {
1343
+ return `email-smtp.${region}.amazonaws.com`;
1344
+ }
1345
+ chunkUSNT2KNT_cjs.__name(sesSmtpHost, "sesSmtpHost");
1346
+ function sesRegionSupportsSmtp(region) {
1347
+ return !SES_REGIONS_WITHOUT_SMTP.has(region.trim());
1348
+ }
1349
+ chunkUSNT2KNT_cjs.__name(sesRegionSupportsSmtp, "sesRegionSupportsSmtp");
1350
+ var EmailService = class {
1351
+ static {
1352
+ chunkUSNT2KNT_cjs.__name(this, "EmailService");
1353
+ }
1354
+ config;
1355
+ templateOptions;
1356
+ sesClient;
1357
+ transporter;
1358
+ /** AWS via SMTP (nodemailer) vs SES API SDK. */
1359
+ awsViaSmtp = false;
1360
+ constructor(config) {
1361
+ this.config = config;
1362
+ this.templateOptions = config.templateOptions;
1363
+ if (config.type === "AWS") {
1364
+ if (!config.region) {
1365
+ throw new Error("AWS SES configuration incomplete: AWS_REGION is required");
1366
+ }
1367
+ if (config.user && config.password) {
1368
+ this.awsViaSmtp = true;
1369
+ const host = config.host || sesSmtpHost(config.region);
1370
+ const port = config.port ?? 587;
1371
+ const secure = config.secure ?? false;
1372
+ this.transporter = nodemailer__default.default.createTransport({
1373
+ host,
1374
+ port,
1375
+ secure,
1376
+ auth: {
1377
+ user: config.user,
1378
+ pass: config.password
1379
+ }
1380
+ });
1381
+ } else if (config.accessKeyId && config.secretAccessKey) {
1382
+ this.sesClient = new clientSes.SESClient({
1383
+ region: config.region,
1384
+ credentials: {
1385
+ accessKeyId: config.accessKeyId,
1386
+ secretAccessKey: config.secretAccessKey
1387
+ }
1388
+ });
1389
+ } else {
1390
+ throw new Error("AWS SES configuration incomplete: set SMTP_USER and SMTP_PASSWORD (SES SMTP) or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (SES API)");
1391
+ }
1392
+ } else if (config.type === "SMTP" || config.type === "GMAIL") {
1393
+ if (!config.user || !config.password) throw new Error("SMTP configuration incomplete");
1394
+ const host = config.type === "GMAIL" ? "smtp.gmail.com" : config.host;
1395
+ if (!host) {
1396
+ throw new Error("SMTP configuration incomplete: SMTP_HOST is required when SMTP_TYPE=SMTP (nodemailer otherwise connects to 127.0.0.1)");
1397
+ }
1398
+ const port = config.port ?? 587;
1399
+ const secure = config.secure ?? false;
1400
+ this.transporter = nodemailer__default.default.createTransport({
1401
+ host,
1402
+ port,
1403
+ secure,
1404
+ auth: {
1405
+ user: config.user,
1406
+ pass: config.password
1407
+ }
1408
+ });
1409
+ } else {
1410
+ throw new Error(`Unsupported email type: ${config.type}`);
1411
+ }
1412
+ }
1413
+ async send(emailData) {
1414
+ try {
1415
+ if (this.config.type === "AWS" && this.sesClient) {
1416
+ await this.sesClient.send(new clientSes.SendEmailCommand({
1417
+ Source: emailData.from || this.config.from,
1418
+ Destination: {
1419
+ ToAddresses: [
1420
+ emailData.to || this.config.to
1421
+ ]
1422
+ },
1423
+ Message: {
1424
+ Subject: {
1425
+ Data: emailData.subject,
1426
+ Charset: "UTF-8"
1427
+ },
1428
+ Body: {
1429
+ Html: {
1430
+ Data: emailData.html,
1431
+ Charset: "UTF-8"
1432
+ },
1433
+ ...emailData.text && {
1434
+ Text: {
1435
+ Data: emailData.text,
1436
+ Charset: "UTF-8"
1437
+ }
1438
+ }
1439
+ }
1440
+ }
1441
+ }));
1442
+ return true;
1443
+ }
1444
+ if (this.transporter && (this.config.type === "SMTP" || this.config.type === "GMAIL" || this.config.type === "AWS" && this.awsViaSmtp)) {
1445
+ await this.transporter.sendMail({
1446
+ from: emailData.from || this.config.from,
1447
+ to: emailData.to || this.config.to,
1448
+ subject: emailData.subject,
1449
+ html: emailData.html,
1450
+ text: emailData.text
1451
+ });
1452
+ return true;
1453
+ }
1454
+ return false;
1455
+ } catch (error) {
1456
+ console.error("Email sending failed:", error);
1457
+ return false;
1458
+ }
1459
+ }
1460
+ renderTemplate(templateName, ctx) {
1461
+ return renderEmail(templateName, ctx, this.templateOptions);
1462
+ }
1463
+ /** Default notification recipient from plugin config (SMTP_TO / plugin `to`). */
1464
+ getDefaultTo() {
1465
+ return this.config.to;
1466
+ }
1467
+ };
1468
+ var emailTemplates = {
1469
+ formSubmission: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((data) => ({
1470
+ subject: `New Form Submission: ${data.formName}`,
1471
+ html: `<h2>New Form Submission</h2><p><strong>Form:</strong> ${data.formName}</p><p><strong>Contact:</strong> ${data.contactName} (${data.contactEmail})</p><pre>${JSON.stringify(data.formData, null, 2)}</pre>`,
1472
+ text: `New Form Submission
1473
+ Form: ${data.formName}
1474
+ Contact: ${data.contactName} (${data.contactEmail})
1475
+ ${JSON.stringify(data.formData, null, 2)}`
1476
+ }), "formSubmission"),
1477
+ contactSubmission: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((data) => ({
1478
+ subject: `New Contact Form Submission from ${data.name}`,
1479
+ html: `<h2>New Contact Form Submission</h2><p><strong>Name:</strong> ${data.name}</p><p><strong>Email:</strong> ${data.email}</p>${data.phone ? `<p><strong>Phone:</strong> ${data.phone}</p>` : ""}${data.message ? `<p><strong>Message:</strong></p><p>${data.message}</p>` : ""}`,
1480
+ text: `New Contact Form Submission
1481
+ Name: ${data.name}
1482
+ Email: ${data.email}
1483
+ ${data.phone ? `Phone: ${data.phone}
1484
+ ` : ""}${data.message ? `Message: ${data.message}` : ""}`
1485
+ }), "contactSubmission"),
1486
+ passwordReset: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((data) => ({
1487
+ subject: "Reset your password",
1488
+ html: `<h2>Reset your password</h2><p>Click the link below to set a new password. This link expires in 1 hour.</p><p><a href="${data.resetLink}">${data.resetLink}</a></p>`,
1489
+ text: `Reset your password: ${data.resetLink}
1490
+
1491
+ This link expires in 1 hour.`
1492
+ }), "passwordReset")
1493
+ };
1494
+
1495
+ // src/lib/email-recipients.ts
1496
+ function parseEmailRecipientsFromConfig(raw) {
1497
+ if (raw == null || raw === "") return [];
1498
+ const trimmed = raw.trim();
1499
+ if (trimmed.startsWith("[")) {
1500
+ try {
1501
+ const parsed = JSON.parse(trimmed);
1502
+ if (Array.isArray(parsed)) {
1503
+ return parsed.map((e) => String(e).trim()).filter(Boolean);
1504
+ }
1505
+ } catch {
1506
+ }
1507
+ }
1508
+ return trimmed.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
1509
+ }
1510
+ chunkUSNT2KNT_cjs.__name(parseEmailRecipientsFromConfig, "parseEmailRecipientsFromConfig");
1511
+ function serializeEmailRecipients(emails) {
1512
+ return JSON.stringify(emails);
1513
+ }
1514
+ chunkUSNT2KNT_cjs.__name(serializeEmailRecipients, "serializeEmailRecipients");
1515
+ function joinRecipientsForSend(emails) {
1516
+ if (!emails.length) return null;
1517
+ return emails.join(", ");
1518
+ }
1519
+ chunkUSNT2KNT_cjs.__name(joinRecipientsForSend, "joinRecipientsForSend");
1520
+
1521
+ // src/plugins/llm/chat-email-intent.ts
1522
+ var NONE_INTENT = "NONE";
1523
+ var CHAT_EMAIL_LOG = "[chat-email-tool]";
1524
+ function logChatEmail(step, data) {
1525
+ if (data && Object.keys(data).length > 0) {
1526
+ console.info(CHAT_EMAIL_LOG, step, data);
1527
+ } else {
1528
+ console.info(CHAT_EMAIL_LOG, step);
1529
+ }
1530
+ }
1531
+ chunkUSNT2KNT_cjs.__name(logChatEmail, "logChatEmail");
1532
+ function normalizeIntentKey(raw) {
1533
+ return raw.trim().toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
1534
+ }
1535
+ chunkUSNT2KNT_cjs.__name(normalizeIntentKey, "normalizeIntentKey");
1536
+ function parseIntentsJson(raw) {
1537
+ if (!raw?.trim()) return null;
1538
+ try {
1539
+ const parsed = JSON.parse(raw);
1540
+ if (!Array.isArray(parsed)) return null;
1541
+ const out = [];
1542
+ for (const row of parsed) {
1543
+ if (!row || typeof row !== "object") continue;
1544
+ const o = row;
1545
+ const intent = normalizeIntentKey(String(o.intent ?? o.id ?? ""));
1546
+ const description = String(o.description ?? "").trim();
1547
+ const emailTo = String(o.emailTo ?? o.email ?? "").trim();
1548
+ if (!intent || !description || !emailTo) continue;
1549
+ out.push({
1550
+ intent,
1551
+ description,
1552
+ emailTo
1553
+ });
1554
+ }
1555
+ return out.length > 0 ? out : null;
1556
+ } catch {
1557
+ return null;
1558
+ }
1559
+ }
1560
+ chunkUSNT2KNT_cjs.__name(parseIntentsJson, "parseIntentsJson");
1561
+ function dedupeIntents(intents) {
1562
+ const seen = /* @__PURE__ */ new Set();
1563
+ const out = [];
1564
+ for (const row of intents) {
1565
+ const key = normalizeIntentKey(row.intent);
1566
+ if (!key || seen.has(key)) continue;
1567
+ seen.add(key);
1568
+ out.push({
1569
+ intent: key,
1570
+ description: row.description.trim(),
1571
+ emailTo: row.emailTo.trim()
1572
+ });
1573
+ }
1574
+ return out;
1575
+ }
1576
+ chunkUSNT2KNT_cjs.__name(dedupeIntents, "dedupeIntents");
1577
+ function parseChatEmailToolSettings(map) {
1578
+ const fromJson = parseIntentsJson(map.emailIntents);
1579
+ const intents = dedupeIntents(fromJson ?? []);
1580
+ const legacyPositive = map.emailIntentPrompt?.trim() ?? "";
1581
+ const legacyNegative = map.emailNegativeIntentPrompt?.trim() ?? "";
1582
+ let classifierInstructions = map.emailClassifierInstructions?.trim() ?? "";
1583
+ if (!classifierInstructions && (legacyPositive || legacyNegative)) {
1584
+ const parts = [];
1585
+ if (legacyPositive) parts.push(`Legacy positive signals:
1586
+ ${legacyPositive}`);
1587
+ if (legacyNegative) parts.push(`Do NOT assign an intent when:
1588
+ ${legacyNegative}`);
1589
+ classifierInstructions = parts.join("\n\n");
1590
+ }
1591
+ return {
1592
+ enabled: map.emailToolEnabled === "true",
1593
+ intents,
1594
+ classifierInstructions,
1595
+ toolPrompt: map.emailToolPrompt ?? ""
1596
+ };
1597
+ }
1598
+ chunkUSNT2KNT_cjs.__name(parseChatEmailToolSettings, "parseChatEmailToolSettings");
1599
+ var EMAIL_TOOL_VALIDATION_KEY = "emailTool";
1600
+ function parseEmailToolObject(raw) {
1601
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
1602
+ const o = raw;
1603
+ const intentsRaw = o.intents;
1604
+ let intents;
1605
+ if (Array.isArray(intentsRaw)) {
1606
+ const parsed = parseIntentsJson(JSON.stringify(intentsRaw));
1607
+ if (parsed?.length) intents = parsed;
1608
+ }
1609
+ return {
1610
+ enabled: o.enabled === true,
1611
+ classifierInstructions: typeof o.classifierInstructions === "string" ? o.classifierInstructions.trim() : void 0,
1612
+ toolPrompt: typeof o.toolPrompt === "string" ? o.toolPrompt.trim() : void 0,
1613
+ intents
1614
+ };
1615
+ }
1616
+ chunkUSNT2KNT_cjs.__name(parseEmailToolObject, "parseEmailToolObject");
1617
+ function parseEmailToolFromAgentValidationRules(validationRulesText) {
1618
+ const raw = validationRulesText?.trim();
1619
+ if (!raw) return null;
1620
+ try {
1621
+ const parsed = JSON.parse(raw);
1622
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1623
+ const emailTool = parsed[EMAIL_TOOL_VALIDATION_KEY];
1624
+ return parseEmailToolObject(emailTool);
1625
+ } catch {
1626
+ return null;
1627
+ }
1628
+ }
1629
+ chunkUSNT2KNT_cjs.__name(parseEmailToolFromAgentValidationRules, "parseEmailToolFromAgentValidationRules");
1630
+ function resolveChatEmailToolSettings(configMap, sources) {
1631
+ const fromConfig = parseChatEmailToolSettings(configMap);
1632
+ const resolved = typeof sources === "string" || sources == null ? {
1633
+ chatbotValidationRules: typeof sources === "string" ? sources : null
1634
+ } : sources;
1635
+ const fromChatbot = parseEmailToolFromAgentValidationRules(resolved.chatbotValidationRules);
1636
+ const fromNotify = resolved.notifyAgent ? parseEmailToolFromAgentValidationRules(resolved.notifyAgent.validationRules) : null;
1637
+ const notifySystem = resolved.notifyAgent?.systemInstruction?.trim() ?? "";
1638
+ const intents = fromNotify?.intents?.length ? fromNotify.intents : fromChatbot?.intents?.length ? fromChatbot.intents : fromConfig.intents;
1639
+ const classifierParts = [
1640
+ notifySystem,
1641
+ fromNotify?.classifierInstructions?.trim(),
1642
+ fromChatbot?.classifierInstructions?.trim(),
1643
+ fromConfig.classifierInstructions.trim()
1644
+ ].filter(Boolean);
1645
+ const toolPrompt = fromNotify?.toolPrompt?.trim() || fromChatbot?.toolPrompt?.trim() || fromConfig.toolPrompt?.trim() || "";
1646
+ return {
1647
+ enabled: fromConfig.enabled,
1648
+ intents,
1649
+ classifierInstructions: classifierParts.join("\n\n"),
1650
+ toolPrompt
1651
+ };
1652
+ }
1653
+ chunkUSNT2KNT_cjs.__name(resolveChatEmailToolSettings, "resolveChatEmailToolSettings");
1654
+ function intentByKey(intents, key) {
1655
+ if (!key) return null;
1656
+ const norm2 = normalizeIntentKey(key);
1657
+ return intents.find((i) => i.intent === norm2) ?? null;
1658
+ }
1659
+ chunkUSNT2KNT_cjs.__name(intentByKey, "intentByKey");
1660
+ function buildIntentTableForPrompt(intents) {
1661
+ return intents.map((i) => `- ${i.intent}: ${i.description} \u2192 notify ${i.emailTo}`).join("\n");
1662
+ }
1663
+ chunkUSNT2KNT_cjs.__name(buildIntentTableForPrompt, "buildIntentTableForPrompt");
1664
+ function buildIntentClassifierSystem(config, agentClassifierInstructions) {
1665
+ const table = buildIntentTableForPrompt(config.intents);
1666
+ const extra = [
1667
+ agentClassifierInstructions?.trim(),
1668
+ config.classifierInstructions.trim()
1669
+ ].filter(Boolean).join("\n\n");
1670
+ const intentKeys = config.intents.map((i) => i.intent).join(", ");
1671
+ return `You classify a chat visitor into exactly one lead intent for email routing.
1672
+
1673
+ Available intents (pick the best match):
1674
+ ${table}
1675
+
1676
+ If the visitor is not ready for a lead email (general FAQ, greetings only, spam, off-topic, no clear business need), use intent "${NONE_INTENT}".
1677
+
1678
+ Allowed intent values: ${intentKeys}, or ${NONE_INTENT}.
1679
+
1680
+ ${extra ? `Additional instructions:
1681
+ ${extra}
1682
+ ` : ""}
1683
+ Reply with ONLY valid JSON, no markdown:
1684
+ {"intent":"INTENT_KEY","reason":"short explanation"}
1685
+ Use "${NONE_INTENT}" when no intent applies.`;
1686
+ }
1687
+ chunkUSNT2KNT_cjs.__name(buildIntentClassifierSystem, "buildIntentClassifierSystem");
1688
+ function buildChatEmailAgentContext(settings) {
1689
+ if (!settings.enabled) return "";
1690
+ const classifier = settings.classifierInstructions.trim();
1691
+ const extra = settings.toolPrompt?.trim() ?? "";
1692
+ const parts = [];
1693
+ if (settings.intents.length > 0) {
1694
+ parts.push("## Lead email routing", "When a visitor message clearly matches an intent below, the system sends one team notification email (per conversation). Continue the conversation normally in all cases.");
1695
+ if (classifier) parts.push(`### Routing rules
1696
+ ${classifier}`);
1697
+ parts.push(`### Intent catalog
1698
+ ${buildIntentTableForPrompt(settings.intents)}`);
1699
+ } else if (classifier) {
1700
+ parts.push(`## Lead email routing
1701
+ ${classifier}`);
1702
+ }
1703
+ if (extra) parts.push(`### Assistant behavior
1704
+ ${extra}`);
1705
+ return parts.join("\n\n");
1706
+ }
1707
+ chunkUSNT2KNT_cjs.__name(buildChatEmailAgentContext, "buildChatEmailAgentContext");
1708
+ function buildChatbotSystemPromptWithEmailTool(baseSystemInstruction, guardrailsForPrompt, emailSettings) {
1709
+ let prompt = (baseSystemInstruction ?? "").trim();
1710
+ const guard = guardrailsForPrompt?.trim();
1711
+ if (guard) prompt = [
1712
+ prompt,
1713
+ guard
1714
+ ].filter(Boolean).join("\n\n");
1715
+ if (emailSettings.enabled) {
1716
+ const emailCtx = buildChatEmailAgentContext(emailSettings);
1717
+ if (emailCtx) prompt = [
1718
+ prompt,
1719
+ emailCtx
1720
+ ].filter(Boolean).join("\n\n");
1721
+ }
1722
+ return prompt;
1723
+ }
1724
+ chunkUSNT2KNT_cjs.__name(buildChatbotSystemPromptWithEmailTool, "buildChatbotSystemPromptWithEmailTool");
1725
+ function formatTranscript(history, latestMessage, maxChars = 4e3) {
1726
+ const lines = [];
1727
+ for (const m of history) {
1728
+ const role = m.role === "assistant" ? "Assistant" : m.role === "user" ? "Visitor" : "System";
1729
+ lines.push(`${role}: ${m.content}`);
1730
+ }
1731
+ const last = history[history.length - 1];
1732
+ if (!last || last.role !== "user" || last.content !== latestMessage) {
1733
+ lines.push(`Visitor: ${latestMessage}`);
1734
+ }
1735
+ let text = lines.join("\n");
1736
+ if (text.length > maxChars) text = text.slice(-maxChars);
1737
+ return text;
1738
+ }
1739
+ chunkUSNT2KNT_cjs.__name(formatTranscript, "formatTranscript");
1740
+ function parseIntentJson(raw, intents) {
1741
+ const trimmed = raw.trim();
1742
+ const fence = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
1743
+ const candidate = (fence?.[1] ?? trimmed).trim();
1744
+ const tryParse = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((s) => {
1745
+ const o = JSON.parse(s);
1746
+ let intentRaw = null;
1747
+ if (typeof o.intent === "string") intentRaw = o.intent;
1748
+ else if (o.interested === false) intentRaw = NONE_INTENT;
1749
+ else if (o.interested === true && intents[0]) intentRaw = intents[0].intent;
1750
+ if (intentRaw == null) return null;
1751
+ const reason = typeof o.reason === "string" && o.reason.trim() ? o.reason.trim() : "Classified from conversation";
1752
+ return {
1753
+ intent: normalizeIntentKey(intentRaw),
1754
+ reason
1755
+ };
1756
+ }, "tryParse");
1757
+ try {
1758
+ return tryParse(candidate);
1759
+ } catch {
1760
+ const m = candidate.match(/\{[\s\S]*\}/);
1761
+ if (!m) return null;
1762
+ try {
1763
+ return tryParse(m[0]);
1764
+ } catch {
1765
+ return null;
1766
+ }
1767
+ }
1768
+ }
1769
+ chunkUSNT2KNT_cjs.__name(parseIntentJson, "parseIntentJson");
1770
+ async function detectChatLeadIntent(llm, params) {
1771
+ if (!params.settings.intents.length) {
1772
+ logChatEmail("classify skipped", {
1773
+ reason: "no_intents_configured"
1774
+ });
1775
+ return {
1776
+ intent: null,
1777
+ intentLabel: "NONE",
1778
+ reason: "No lead intents configured",
1779
+ emailTo: null
1780
+ };
1781
+ }
1782
+ logChatEmail("classify start", {
1783
+ intentCount: params.settings.intents.length,
1784
+ intentKeys: params.settings.intents.map((i) => i.intent),
1785
+ model: params.model?.trim() || "(gateway default)",
1786
+ messageChars: params.message.length,
1787
+ historyTurns: params.history.length,
1788
+ hasClassifierInstructions: Boolean(params.agentClassifierInstructions?.trim() || params.settings.classifierInstructions.trim())
1789
+ });
1790
+ const transcript = formatTranscript(params.history, params.message);
1791
+ const contactLines = [
1792
+ params.contact.name?.trim() ? `Name: ${params.contact.name.trim()}` : null,
1793
+ params.contact.email?.trim() ? `Email: ${params.contact.email.trim()}` : null,
1794
+ params.contact.phone?.trim() ? `Phone: ${params.contact.phone.trim()}` : null
1795
+ ].filter(Boolean).join("\n");
1796
+ const userPrompt = `Customer:
1797
+ ${contactLines || "(unknown)"}
1798
+
1799
+ Conversation:
1800
+ ${transcript}
1801
+
1802
+ Pick the single best intent for the visitor's latest message.`;
1803
+ const res = await llm.chatAgent({
1804
+ systemPrompt: buildIntentClassifierSystem(params.settings, params.agentClassifierInstructions),
1805
+ userPrompt,
1806
+ temperature: 0.1,
1807
+ max_tokens: 256,
1808
+ ...params.model?.trim() ? {
1809
+ model: params.model.trim()
1810
+ } : {}
1811
+ });
1812
+ const rawContent = res.content ?? "";
1813
+ logChatEmail("classify llm response", {
1814
+ responseChars: rawContent.length,
1815
+ responsePreview: rawContent.slice(0, 280) + (rawContent.length > 280 ? "\u2026" : "")
1816
+ });
1817
+ const parsed = parseIntentJson(rawContent, params.settings.intents);
1818
+ if (!parsed) {
1819
+ logChatEmail("classify result", {
1820
+ matched: false,
1821
+ outcome: "parse_failed",
1822
+ emailWillSend: false
1823
+ });
1824
+ return {
1825
+ intent: null,
1826
+ intentLabel: "Unclassified",
1827
+ reason: "Could not parse intent classifier response",
1828
+ emailTo: null
1829
+ };
1830
+ }
1831
+ if (parsed.intent === NONE_INTENT) {
1832
+ logChatEmail("classify result", {
1833
+ matched: false,
1834
+ outcome: NONE_INTENT,
1835
+ reason: parsed.reason,
1836
+ emailWillSend: false
1837
+ });
1838
+ return {
1839
+ intent: null,
1840
+ intentLabel: NONE_INTENT,
1841
+ reason: parsed.reason,
1842
+ emailTo: null
1843
+ };
1844
+ }
1845
+ const matched = intentByKey(params.settings.intents, parsed.intent);
1846
+ if (!matched) {
1847
+ logChatEmail("classify result", {
1848
+ matched: false,
1849
+ outcome: "unknown_intent",
1850
+ parsedIntent: parsed.intent,
1851
+ reason: parsed.reason,
1852
+ emailWillSend: false
1853
+ });
1854
+ return {
1855
+ intent: null,
1856
+ intentLabel: parsed.intent,
1857
+ reason: `Unknown intent "${parsed.intent}": ${parsed.reason}`,
1858
+ emailTo: null
1859
+ };
1860
+ }
1861
+ logChatEmail("classify result", {
1862
+ matched: true,
1863
+ outcome: "intent_found",
1864
+ intent: matched.intent,
1865
+ emailTo: matched.emailTo,
1866
+ reason: parsed.reason,
1867
+ emailWillSend: true
1868
+ });
1869
+ return {
1870
+ intent: matched.intent,
1871
+ intentLabel: `${matched.intent} \u2014 ${matched.description}`,
1872
+ reason: parsed.reason,
1873
+ emailTo: matched.emailTo
1874
+ };
1875
+ }
1876
+ chunkUSNT2KNT_cjs.__name(detectChatLeadIntent, "detectChatLeadIntent");
1877
+ function buildTranscriptForLeadEmail(history, latestMessage) {
1878
+ return formatTranscript(history, latestMessage);
1879
+ }
1880
+ chunkUSNT2KNT_cjs.__name(buildTranscriptForLeadEmail, "buildTranscriptForLeadEmail");
1881
+ function parseIntentRecipientEmails(emailTo) {
1882
+ return emailTo.split(/[,;]+/).map((s) => s.trim()).filter((s) => s.length > 0 && s.includes("@"));
1883
+ }
1884
+ chunkUSNT2KNT_cjs.__name(parseIntentRecipientEmails, "parseIntentRecipientEmails");
1885
+
1886
+ // src/plugins/email/chat-lead-email.ts
1887
+ function resolveLeadRecipients(emailPlugin2, emailSettings) {
1888
+ const fromCrm = parseEmailRecipientsFromConfig(emailSettings.crmEmails ?? emailSettings.crmEmail ?? "");
1889
+ if (fromCrm.length > 0) return fromCrm;
1890
+ const fallback = emailPlugin2.getDefaultTo?.() ?? "";
1891
+ if (fallback.trim()) return [
1892
+ fallback.trim()
1893
+ ];
1894
+ return [];
1895
+ }
1896
+ chunkUSNT2KNT_cjs.__name(resolveLeadRecipients, "resolveLeadRecipients");
1897
+ async function sendChatLeadEmail(cms, emailSettings, brandingSettings, input) {
1898
+ console.info(CHAT_EMAIL_LOG, "send start", {
1899
+ conversationId: input.conversationId,
1900
+ intentCode: input.intentCode ?? null,
1901
+ contactEmail: input.contactEmail,
1902
+ contactName: input.contactName,
1903
+ explicitRecipients: input.recipients?.length ?? 0
1904
+ });
1905
+ const email = cms.getPlugin("email");
1906
+ if (!email?.send || !email.renderTemplate) {
1907
+ console.warn(CHAT_EMAIL_LOG, "send failed", {
1908
+ conversationId: input.conversationId,
1909
+ reason: "email_plugin_disabled"
1910
+ });
1911
+ return {
1912
+ sent: false,
1913
+ recipients: [],
1914
+ error: "Email plugin is not enabled"
1915
+ };
1916
+ }
1917
+ const recipients = input.recipients?.filter((r) => r.trim().includes("@")).map((r) => r.trim()) ?? resolveLeadRecipients(email, emailSettings);
1918
+ if (recipients.length === 0) {
1919
+ console.warn(CHAT_EMAIL_LOG, "send failed", {
1920
+ conversationId: input.conversationId,
1921
+ reason: "no_recipients"
1922
+ });
1923
+ return {
1924
+ sent: false,
1925
+ recipients: [],
1926
+ error: "No lead email recipients (configure intent Email To, CRM emails, or SMTP default To)"
1927
+ };
1928
+ }
1929
+ console.info(CHAT_EMAIL_LOG, "send recipients resolved", {
1930
+ conversationId: input.conversationId,
1931
+ recipients,
1932
+ source: input.recipients?.length ? "intent_email_to" : "crm_or_smtp_fallback"
1933
+ });
1934
+ const companyDetails = mergeEmailLayoutCompanyDetails(brandingSettings, emailSettings);
1935
+ const ctx = {
1936
+ ...input,
1937
+ companyDetails: input.companyDetails ?? companyDetails
1938
+ };
1939
+ let anySent = false;
1940
+ for (const to of recipients) {
1941
+ await chunkXW5ATPRW_cjs.queueEmail(cms, {
1942
+ to,
1943
+ templateName: "chatLead",
1944
+ ctx
1945
+ });
1946
+ console.info(CHAT_EMAIL_LOG, "send queued", {
1947
+ conversationId: input.conversationId,
1948
+ to,
1949
+ template: "chatLead"
1950
+ });
1951
+ anySent = true;
1952
+ }
1953
+ console.info(CHAT_EMAIL_LOG, "send complete", {
1954
+ conversationId: input.conversationId,
1955
+ sent: anySent,
1956
+ recipientCount: recipients.length
1957
+ });
1958
+ return {
1959
+ sent: anySent,
1960
+ recipients
1961
+ };
1962
+ }
1963
+ chunkUSNT2KNT_cjs.__name(sendChatLeadEmail, "sendChatLeadEmail");
1964
+
1965
+ // src/plugins/email/index.ts
1966
+ var EMAIL_TYPES = [
1967
+ "AWS",
1968
+ "SMTP",
1969
+ "GMAIL",
1970
+ "SENDGRID"
1971
+ ];
1972
+ function normalizeEmailType(raw, fallback) {
1973
+ const v = String(raw ?? fallback).trim().toUpperCase();
1974
+ return EMAIL_TYPES.includes(v) ? v : fallback;
1975
+ }
1976
+ chunkUSNT2KNT_cjs.__name(normalizeEmailType, "normalizeEmailType");
1977
+ function isLocalSmtpHost(host) {
1978
+ if (!host) return false;
1979
+ const h = host.trim().toLowerCase();
1980
+ return h === "localhost" || h === "127.0.0.1" || h === "::1";
1981
+ }
1982
+ chunkUSNT2KNT_cjs.__name(isLocalSmtpHost, "isLocalSmtpHost");
1983
+ function emailPlugin(config) {
1984
+ return {
1985
+ name: "email",
1986
+ version: "1.0.0",
1987
+ async init(context) {
1988
+ const from = config.from || context.config.SMTP_FROM || "no-reply@example.com";
1989
+ const to = config.to || context.config.SMTP_TO || "info@example.com";
1990
+ const type = normalizeEmailType(context.config.SMTP_TYPE ?? config.type, "SMTP");
1991
+ const portEnv = context.config.SMTP_PORT;
1992
+ const portParsed = portEnv ? parseInt(portEnv, 10) : void 0;
1993
+ const region = config.region ?? context.config.AWS_SES_REGION ?? context.config.AWS_REGION;
1994
+ let host = config.host ?? context.config.SMTP_HOST;
1995
+ if (type === "AWS" && isLocalSmtpHost(host)) {
1996
+ host = void 0;
1997
+ }
1998
+ const merged = {
1999
+ ...config,
2000
+ from,
2001
+ to,
2002
+ type,
2003
+ user: config.user ?? context.config.SMTP_USER,
2004
+ password: config.password ?? context.config.SMTP_PASSWORD ?? context.config.SMTP_PASS,
2005
+ host,
2006
+ port: config.port ?? (Number.isFinite(portParsed) ? portParsed : void 0),
2007
+ secure: config.secure ?? context.config.SMTP_SECURE === "true",
2008
+ region,
2009
+ accessKeyId: config.accessKeyId ?? context.config.AWS_ACCESS_KEY_ID,
2010
+ secretAccessKey: config.secretAccessKey ?? context.config.AWS_SECRET_ACCESS_KEY
2011
+ };
2012
+ if (type === "AWS" && !merged.region) {
2013
+ context.logger.warn("Email plugin skipped: AWS SES requires AWS_SES_REGION or AWS_REGION");
2014
+ return void 0;
2015
+ }
2016
+ if (type === "AWS" && merged.region && merged.user && merged.password && !sesRegionSupportsSmtp(merged.region)) {
2017
+ context.logger.warn(`Email plugin: region ${merged.region} has no SES SMTP endpoint (ENOTFOUND). Set AWS_SES_REGION=ap-south-1 and create SMTP credentials in that SES region.`);
2018
+ }
2019
+ if (type === "AWS" && !(merged.user && merged.password || merged.accessKeyId && merged.secretAccessKey)) {
2020
+ context.logger.warn("Email plugin skipped: AWS SES requires SMTP_USER and SMTP_PASSWORD (SES SMTP) or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (SES API)");
2021
+ return void 0;
2022
+ }
2023
+ if ((type === "SMTP" || type === "GMAIL") && (!merged.user || !merged.password)) {
2024
+ context.logger.warn("Email plugin skipped: SMTP credentials not configured");
2025
+ return void 0;
2026
+ }
2027
+ if (type === "SMTP" && !merged.host) {
2028
+ context.logger.warn("Email plugin skipped: SMTP_TYPE=SMTP requires SMTP_HOST (or use SMTP_TYPE=AWS with AWS_REGION and SES SMTP credentials)");
2029
+ return void 0;
2030
+ }
2031
+ const resolvedHost = type === "AWS" && merged.region ? merged.host || sesSmtpHost(merged.region) : merged.host;
2032
+ context.logger.info("Email plugin initialized", {
2033
+ type,
2034
+ host: resolvedHost,
2035
+ region: merged.region
2036
+ });
2037
+ return new EmailService(merged);
2038
+ }
2039
+ };
2040
+ }
2041
+ chunkUSNT2KNT_cjs.__name(emailPlugin, "emailPlugin");
2042
+
2043
+ // src/lib/whatsapp-trigger-dispatcher.ts
2044
+ var initialized = false;
2045
+ function maskPhone3(raw) {
2046
+ const digits = String(raw ?? "").replace(/\D/g, "");
2047
+ if (digits.length <= 4) return "(none)";
2048
+ return `***${digits.slice(-4)}`;
2049
+ }
2050
+ chunkUSNT2KNT_cjs.__name(maskPhone3, "maskPhone");
2051
+ async function getSettingsGroup(dataSource, entityMap, group) {
2052
+ if (!entityMap.configs) return {};
2053
+ const rows = await dataSource.getRepository(entityMap.configs).find({
2054
+ where: {
2055
+ settings: group,
2056
+ deleted: false
2057
+ }
2058
+ });
2059
+ return Object.fromEntries(rows.map((r) => [
2060
+ r.key,
2061
+ r.value
2062
+ ]));
2063
+ }
2064
+ chunkUSNT2KNT_cjs.__name(getSettingsGroup, "getSettingsGroup");
2065
+ async function isOrderNotificationsEnabled(dataSource, entityMap) {
2066
+ const settings = await getSettingsGroup(dataSource, entityMap, "event_notifications");
2067
+ return settings.enabled !== "false" && settings.enabled !== "0";
2068
+ }
2069
+ chunkUSNT2KNT_cjs.__name(isOrderNotificationsEnabled, "isOrderNotificationsEnabled");
2070
+ async function isTriggerCatalogEnabled(triggerKey, dataSource, entityMap) {
2071
+ if (!entityMap.order_notification_triggers) {
2072
+ console.warn("[order-notifications] order_notification_triggers missing \u2014 run migration 1781230000000-AddOrderNotificationTriggers");
2073
+ return false;
2074
+ }
2075
+ try {
2076
+ const row = await dataSource.getRepository(entityMap.order_notification_triggers).findOne({
2077
+ where: {
2078
+ triggerKey,
2079
+ enabled: true
2080
+ }
2081
+ });
2082
+ if (!row) {
2083
+ console.warn("[order-notifications] trigger disabled or not in DB", {
2084
+ triggerKey
2085
+ });
2086
+ }
2087
+ return Boolean(row);
2088
+ } catch (err) {
2089
+ console.error("[order-notifications] failed to load trigger catalog", {
2090
+ triggerKey,
2091
+ err
2092
+ });
2093
+ return false;
2094
+ }
2095
+ }
2096
+ chunkUSNT2KNT_cjs.__name(isTriggerCatalogEnabled, "isTriggerCatalogEnabled");
2097
+ async function loadBoundWhatsAppTemplate(triggerKey, dataSource, entityMap) {
2098
+ if (!entityMap.whatsapp_trigger_bindings || !entityMap.message_templates) {
2099
+ console.warn("[order-notifications] bindings or message_templates missing from entityMap");
2100
+ return null;
2101
+ }
2102
+ const binding = await dataSource.getRepository(entityMap.whatsapp_trigger_bindings).findOne({
2103
+ where: {
2104
+ triggerKey,
2105
+ enabled: true
2106
+ }
2107
+ });
2108
+ if (!binding) {
2109
+ console.warn("[order-notifications] no whatsapp_trigger_bindings row", {
2110
+ triggerKey
2111
+ });
2112
+ return null;
2113
+ }
2114
+ const templateId = binding.messageTemplateId;
2115
+ if (templateId == null) {
2116
+ console.warn("[order-notifications] binding exists but no template selected", {
2117
+ triggerKey
2118
+ });
2119
+ return null;
2120
+ }
2121
+ const template = await dataSource.getRepository(entityMap.message_templates).findOne({
2122
+ where: {
2123
+ id: templateId,
2124
+ channel: "whatsapp",
2125
+ deleted: false,
2126
+ enabled: true
2127
+ }
2128
+ });
2129
+ if (!template) {
2130
+ console.warn("[order-notifications] bound WhatsApp template not found or disabled", {
2131
+ triggerKey,
2132
+ templateId
2133
+ });
2134
+ return null;
2135
+ }
2136
+ return template;
2137
+ }
2138
+ chunkUSNT2KNT_cjs.__name(loadBoundWhatsAppTemplate, "loadBoundWhatsAppTemplate");
2139
+ function mergeTriggerVariables(payload, rich) {
2140
+ const basic = {
2141
+ orderId: String(payload.orderId ?? ""),
2142
+ orderNumber: payload.orderNumber,
2143
+ customerName: payload.customerName,
2144
+ customerPhone: payload.customerPhone ?? "",
2145
+ total: String(payload.total),
2146
+ orderTotal: String(payload.total),
2147
+ currency: payload.currency,
2148
+ vendorId: String(payload.vendorId ?? ""),
2149
+ ...payload.refundAmount != null ? {
2150
+ refundAmount: String(payload.refundAmount)
2151
+ } : {}
2152
+ };
2153
+ return {
2154
+ ...basic,
2155
+ ...rich ?? {}
2156
+ };
2157
+ }
2158
+ chunkUSNT2KNT_cjs.__name(mergeTriggerVariables, "mergeTriggerVariables");
2159
+ async function sendOrderPlacedEmail(orderId, dataSource, entityMap, getCms, variables, contactEmail) {
2160
+ if (!entityMap.message_templates) return;
2161
+ const templateRepo = dataSource.getRepository(entityMap.message_templates);
2162
+ const getTemplateRow = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async (channel, templateKey) => {
2163
+ const row = await templateRepo.findOne({
2164
+ where: {
2165
+ channel,
2166
+ templateKey,
2167
+ deleted: false
2168
+ }
2169
+ });
2170
+ if (!row) return null;
2171
+ const r = row;
2172
+ return {
2173
+ subject: r.subject,
2174
+ body: r.body,
2175
+ externalTemplateRef: r.externalTemplateRef,
2176
+ name: r.name,
2177
+ language: r.providerMeta?.language ?? null,
2178
+ paramOrder: r.providerMeta?.paramOrder ?? null,
2179
+ enabled: r.enabled
2180
+ };
2181
+ }, "getTemplateRow");
2182
+ const resolved = await chunkSPQFNIYJ_cjs.resolveEventOrderTemplate("email", getTemplateRow, null);
2183
+ if (!resolved?.enabled) {
2184
+ console.warn("[order-notifications] email template disabled or missing for order_placed", {
2185
+ orderId
2186
+ });
2187
+ return;
2188
+ }
2189
+ const [branding, emailSettings] = await Promise.all([
2190
+ getSettingsGroup(dataSource, entityMap, "branding"),
2191
+ getSettingsGroup(dataSource, entityMap, "email")
2192
+ ]);
2193
+ const companyDetails = mergeEmailLayoutCompanyDetails(branding, emailSettings);
2194
+ const subject = chunkOOTLNH63_cjs.applyTemplateVars(resolved.subject ?? "Order confirmed", variables);
2195
+ const bodyHtml = chunkOOTLNH63_cjs.applyTemplateVars(resolved.body, variables);
2196
+ const html = renderLayout({
2197
+ bodyHtml,
2198
+ companyDetails
2199
+ });
2200
+ const cms = await getCms();
2201
+ await chunkXW5ATPRW_cjs.queueEmail(cms, {
2202
+ to: contactEmail,
2203
+ subject,
2204
+ html,
2205
+ text: bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()
2206
+ });
2207
+ console.log("[order-notifications] email queued", {
2208
+ orderId,
2209
+ to: contactEmail
2210
+ });
2211
+ }
2212
+ chunkUSNT2KNT_cjs.__name(sendOrderPlacedEmail, "sendOrderPlacedEmail");
2213
+ async function sendWhatsAppForTrigger(triggerKey, orderId, phone, variables, dataSource, entityMap, getCms) {
2214
+ const template = await loadBoundWhatsAppTemplate(triggerKey, dataSource, entityMap);
2215
+ if (!template) return;
2216
+ const paramOrder = template.providerMeta?.paramOrder?.length ? template.providerMeta.paramOrder : chunkSPQFNIYJ_cjs.EVENT_ORDER_WHATSAPP_PARAM_KEYS;
2217
+ const cms = await getCms();
2218
+ const metaTemplateName = resolveMetaWhatsAppTemplateName({
2219
+ externalTemplateRef: template.externalTemplateRef,
2220
+ name: template.name
2221
+ });
2222
+ if (!metaTemplateName) {
2223
+ console.warn("[order-notifications] bound WhatsApp template has no Meta template name", {
2224
+ triggerKey,
2225
+ templateId: template.id
2226
+ });
2227
+ return;
2228
+ }
2229
+ const sent = await queueWhatsApp(cms, {
2230
+ to: phone.trim(),
2231
+ templateKey: triggerKey,
2232
+ externalTemplateRef: metaTemplateName,
2233
+ templateLanguage: template.providerMeta?.language ?? void 0,
2234
+ body: template.body,
2235
+ variables,
2236
+ templateParamOrder: paramOrder
2237
+ });
2238
+ if (!sent) {
2239
+ console.warn("[order-notifications] WhatsApp send failed", {
2240
+ triggerKey,
2241
+ orderId,
2242
+ hint: "Register whatsappPlugin() + queuePlugin() in getCms(), or set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID"
2243
+ });
2244
+ } else {
2245
+ console.log("[order-notifications] WhatsApp queued/sent", {
2246
+ triggerKey,
2247
+ orderId,
2248
+ phone: maskPhone3(phone)
2249
+ });
2250
+ }
2251
+ }
2252
+ chunkUSNT2KNT_cjs.__name(sendWhatsAppForTrigger, "sendWhatsAppForTrigger");
2253
+ async function handleTrigger(triggerKey, payload, dataSource, entityMap, getCms) {
2254
+ console.log("[order-notifications] received", {
2255
+ triggerKey,
2256
+ orderId: payload.orderId,
2257
+ phone: maskPhone3(payload.customerPhone)
2258
+ });
2259
+ const pluginEnabled = await isOrderNotificationsEnabled(dataSource, entityMap);
2260
+ if (!pluginEnabled) {
2261
+ console.warn("[order-notifications] skip: Plugins \u2192 Order notifications disabled");
2262
+ return;
2263
+ }
2264
+ const triggerEnabled = await isTriggerCatalogEnabled(triggerKey, dataSource, entityMap);
2265
+ if (!triggerEnabled) return;
2266
+ const context = await loadOrderNotificationContexts(payload.orderId, {
2267
+ dataSource,
2268
+ entityMap
2269
+ });
2270
+ const variables = mergeTriggerVariables(payload, context?.variables);
2271
+ const contactEmail = context?.contact.email?.trim() || "";
2272
+ const contactPhone = context?.contact.phone?.trim() || payload.customerPhone?.trim() || "";
2273
+ if (triggerKey === "order_placed" && contactEmail) {
2274
+ await sendOrderPlacedEmail(payload.orderId, dataSource, entityMap, getCms, variables, contactEmail);
2275
+ } else if (triggerKey === "order_placed") {
2276
+ console.warn("[order-notifications] skip email: no customer email", {
2277
+ orderId: payload.orderId
2278
+ });
2279
+ }
2280
+ if (!contactPhone) {
2281
+ console.warn("[order-notifications] skip WhatsApp: no customer phone", {
2282
+ triggerKey,
2283
+ orderId: payload.orderId
2284
+ });
2285
+ return;
2286
+ }
2287
+ await sendWhatsAppForTrigger(triggerKey, payload.orderId, contactPhone, variables, dataSource, entityMap, getCms);
2288
+ }
2289
+ chunkUSNT2KNT_cjs.__name(handleTrigger, "handleTrigger");
2290
+ function initWhatsappTriggerDispatcher(deps) {
2291
+ if (initialized) return;
2292
+ initialized = true;
2293
+ const { dataSource, entityMap, getCms } = deps;
2294
+ chunkUCKN4BBY_cjs.notificationTriggerEmitter.onAnyTrigger((triggerKey, payload) => {
2295
+ void handleTrigger(triggerKey, payload, dataSource, entityMap, getCms).catch((err) => {
2296
+ console.error("[order-notifications]", triggerKey, err);
2297
+ });
2298
+ });
2299
+ console.log("[order-notifications] dispatcher initialized (email + WhatsApp)");
2300
+ }
2301
+ chunkUSNT2KNT_cjs.__name(initWhatsappTriggerDispatcher, "initWhatsappTriggerDispatcher");
2302
+ async function resendOrderNotification(triggerKey, orderId, deps) {
2303
+ if (!deps.entityMap.orders) return {
2304
+ ok: false,
2305
+ error: "orders entity missing"
2306
+ };
2307
+ const pluginEnabled = await isOrderNotificationsEnabled(deps.dataSource, deps.entityMap);
2308
+ if (!pluginEnabled) return {
2309
+ ok: false,
2310
+ error: "Order notifications plugin is disabled"
2311
+ };
2312
+ const triggerEnabled = await isTriggerCatalogEnabled(triggerKey, deps.dataSource, deps.entityMap);
2313
+ if (!triggerEnabled) {
2314
+ return {
2315
+ ok: false,
2316
+ error: `Trigger "${triggerKey}" is disabled or migration 1781230000000 not applied`
2317
+ };
2318
+ }
2319
+ const order = await deps.dataSource.getRepository(deps.entityMap.orders).findOne({
2320
+ where: {
2321
+ id: orderId,
2322
+ deleted: false
2323
+ },
2324
+ relations: [
2325
+ "contact"
2326
+ ]
2327
+ });
2328
+ if (!order) return {
2329
+ ok: false,
2330
+ error: "Order not found"
2331
+ };
2332
+ const o = order;
2333
+ await handleTrigger(triggerKey, {
2334
+ orderId,
2335
+ orderNumber: String(o.orderNumber ?? ""),
2336
+ customerName: o.contact?.name ?? "",
2337
+ customerPhone: o.contact?.phone ?? null,
2338
+ total: o.total ?? 0,
2339
+ currency: String(o.currency ?? "INR"),
2340
+ vendorId: o.vendorId ?? null
2341
+ }, deps.dataSource, deps.entityMap, deps.getCms);
2342
+ return {
2343
+ ok: true
2344
+ };
2345
+ }
2346
+ chunkUSNT2KNT_cjs.__name(resendOrderNotification, "resendOrderNotification");
2347
+
2348
+ exports.CHAT_EMAIL_LOG = CHAT_EMAIL_LOG;
2349
+ exports.EmailService = EmailService;
2350
+ exports.WhatsAppService = WhatsAppService;
2351
+ exports.buildChatbotSystemPromptWithEmailTool = buildChatbotSystemPromptWithEmailTool;
2352
+ exports.buildEventOrderTemplateVariables = buildEventOrderTemplateVariables;
2353
+ exports.buildTranscriptForLeadEmail = buildTranscriptForLeadEmail;
2354
+ exports.detectChatLeadIntent = detectChatLeadIntent;
2355
+ exports.emailPlugin = emailPlugin;
2356
+ exports.emailTemplates = emailTemplates;
2357
+ exports.getCompanyDetailsFromSettings = getCompanyDetailsFromSettings;
2358
+ exports.initWhatsappTriggerDispatcher = initWhatsappTriggerDispatcher;
2359
+ exports.isWhatsAppPluginEnabled = isWhatsAppPluginEnabled;
2360
+ exports.joinRecipientsForSend = joinRecipientsForSend;
2361
+ exports.mergeEmailLayoutCompanyDetails = mergeEmailLayoutCompanyDetails;
2362
+ exports.mergeWhatsAppConfigLayers = mergeWhatsAppConfigLayers;
2363
+ exports.parseEmailRecipientsFromConfig = parseEmailRecipientsFromConfig;
2364
+ exports.parseIntentRecipientEmails = parseIntentRecipientEmails;
2365
+ exports.queueWhatsApp = queueWhatsApp;
2366
+ exports.registerWhatsAppQueueProcessor = registerWhatsAppQueueProcessor;
2367
+ exports.renderEmail = renderEmail;
2368
+ exports.renderLayout = renderLayout;
2369
+ exports.resendOrderNotification = resendOrderNotification;
2370
+ exports.resolveChatEmailToolSettings = resolveChatEmailToolSettings;
2371
+ exports.sendChatLeadEmail = sendChatLeadEmail;
2372
+ exports.serializeEmailRecipients = serializeEmailRecipients;
2373
+ exports.whatsAppConfigured = whatsAppConfigured;