@infuro/cms-core 1.0.46 → 1.0.47

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 (58) hide show
  1. package/dist/admin.cjs +3420 -2702
  2. package/dist/admin.d.cts +18 -4
  3. package/dist/admin.d.ts +18 -4
  4. package/dist/admin.js +2328 -1612
  5. package/dist/api.cjs +37 -38
  6. package/dist/api.d.cts +9 -3
  7. package/dist/api.d.ts +9 -3
  8. package/dist/api.js +5 -6
  9. package/dist/auth.cjs +55 -51
  10. package/dist/auth.d.cts +5 -3
  11. package/dist/auth.d.ts +5 -3
  12. package/dist/auth.js +3 -3
  13. package/dist/{chunk-KFFB6EMZ.js → chunk-2HU5R2JE.js} +2 -0
  14. package/dist/chunk-2IAXTKQN.cjs +19 -0
  15. package/dist/{chunk-SPQFNIYJ.cjs → chunk-4PMK3RNA.cjs} +2 -0
  16. package/dist/{chunk-X6UQFV4X.cjs → chunk-77NUXO6A.cjs} +14 -12
  17. package/dist/chunk-EIZKW2PF.js +13 -0
  18. package/dist/{chunk-X47PBV4I.js → chunk-JE22VP6S.js} +1 -0
  19. package/dist/{chunk-DN65KDIA.js → chunk-JIWUVQ6B.js} +14 -13
  20. package/dist/{chunk-HT5DI3XW.cjs → chunk-KOTXDSQB.cjs} +1 -0
  21. package/dist/{chunk-TCSGFAWB.cjs → chunk-LMJ7RKPF.cjs} +1188 -3
  22. package/dist/{chunk-FBKDMRQL.cjs → chunk-Q3HQEM4R.cjs} +6 -6
  23. package/dist/{chunk-NBY4NVTY.cjs → chunk-VUQFARRT.cjs} +7 -7
  24. package/dist/{chunk-UKC3HYXI.js → chunk-W42UZLQO.js} +1377 -559
  25. package/dist/{chunk-UDVLFVEC.cjs → chunk-XUCKZPML.cjs} +1448 -630
  26. package/dist/{chunk-57O3HZPG.js → chunk-YC4NUZCS.js} +1 -1
  27. package/dist/{chunk-CRYKVJTO.js → chunk-YXH2UUEZ.js} +1179 -3
  28. package/dist/{chunk-SF2XKMCI.js → chunk-ZF2RQWXB.js} +1 -1
  29. package/dist/{emit-order-notification-trigger-IVLWKKJL.js → emit-order-notification-trigger-6XX7LSC4.js} +1 -1
  30. package/dist/{emit-order-notification-trigger-D2N3KFHL.cjs → emit-order-notification-trigger-NASG7ZEO.cjs} +3 -3
  31. package/dist/{event-order-defaults-EMWBIGL3.cjs → event-order-defaults-7Z3UZOEH.cjs} +9 -9
  32. package/dist/{event-order-defaults-SDRNAZHC.js → event-order-defaults-XQ3IDPD7.js} +1 -1
  33. package/dist/hooks.cjs +43 -0
  34. package/dist/hooks.d.cts +10 -1
  35. package/dist/hooks.d.ts +10 -1
  36. package/dist/hooks.js +39 -1
  37. package/dist/index.cjs +414 -310
  38. package/dist/index.d.cts +51 -17
  39. package/dist/index.d.ts +51 -17
  40. package/dist/index.js +114 -12
  41. package/dist/migrations/1782200000000-VendorTeamProfiles.ts +233 -0
  42. package/dist/migrations/1782300000000-AddTypeToOrderNotificationBindings.ts +75 -0
  43. package/dist/{order-notification-dispatcher-ZJZB2HUN.js → order-notification-dispatcher-6WNG24NY.js} +1 -2
  44. package/dist/{order-notification-dispatcher-SBQAMM5V.cjs → order-notification-dispatcher-6XSU3AR7.cjs} +3 -4
  45. package/dist/{rbac-debug-db-2SGNLANF.js → rbac-debug-db-6EMIVMGF.js} +1 -1
  46. package/dist/{rbac-debug-db-4Z6A425H.cjs → rbac-debug-db-6PWTLBEL.cjs} +2 -2
  47. package/dist/theme.cjs +6 -1
  48. package/dist/theme.d.cts +4 -1
  49. package/dist/theme.d.ts +4 -1
  50. package/dist/theme.js +3 -1
  51. package/package.json +1 -1
  52. package/src/admin/admin.css +7 -0
  53. package/dist/chunk-7PMHZRF3.cjs +0 -872
  54. package/dist/chunk-CQHXW4TR.js +0 -107
  55. package/dist/chunk-GUSHM5HN.js +0 -862
  56. package/dist/chunk-XMRMZ6NQ.cjs +0 -109
  57. package/dist/send-order-placed-emails-B5ZVJT7T.cjs +0 -15
  58. package/dist/send-order-placed-emails-WPI37KRZ.js +0 -6
@@ -1,10 +1,639 @@
1
+ import { notificationTriggerEmitter } from './chunk-HCIRL37O.js';
1
2
  import { queueEmail } from './chunk-L3525VXI.js';
2
3
  import { mergeEmailLayoutCompanyDetails } from './chunk-2KUCQVAQ.js';
4
+ import { applyTemplateVars } from './chunk-CRFV5WJK.js';
3
5
  import { __name } from './chunk-SHUYVCID.js';
4
6
  import { SESClient, SendRawEmailCommand, SendEmailCommand } from '@aws-sdk/client-ses';
5
7
  import { createRequire } from 'module';
6
8
  import nodemailer from 'nodemailer';
7
9
 
10
+ // src/lib/event-order-template-context.ts
11
+ function resolvePublicSiteUrl() {
12
+ if (typeof process !== "undefined") {
13
+ const u = (process.env.CMS_PUBLIC_URL || process.env.NEXT_PUBLIC_SITE_URL || "").trim();
14
+ if (u) return u.replace(/\/+$/, "");
15
+ const v = (process.env.VERCEL_URL || "").trim();
16
+ if (v) return v.startsWith("http") ? v.replace(/\/+$/, "") : `https://${v.replace(/\/+$/, "")}`;
17
+ }
18
+ return "";
19
+ }
20
+ __name(resolvePublicSiteUrl, "resolvePublicSiteUrl");
21
+ function buildOrderTrackUrl(qrToken, siteUrl, orderNumber) {
22
+ const token = qrToken?.trim() || orderNumber?.trim();
23
+ if (!token) return "";
24
+ const base = (siteUrl ?? resolvePublicSiteUrl()).replace(/\/+$/, "");
25
+ if (!base) return `/track/${token}`;
26
+ return `${base}/track/${token}`;
27
+ }
28
+ __name(buildOrderTrackUrl, "buildOrderTrackUrl");
29
+ function buildOrderQrImageUrl(trackUrl, size = 200, fallbackData) {
30
+ const data = trackUrl.trim() || fallbackData?.trim() || "";
31
+ if (!data) return "";
32
+ return `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(data)}`;
33
+ }
34
+ __name(buildOrderQrImageUrl, "buildOrderQrImageUrl");
35
+ function formatOrderDetailsText(input) {
36
+ const { orderNumber, total, currency, lines } = input;
37
+ const header = `Order: ${orderNumber}
38
+ Total: ${total} ${currency}`;
39
+ if (!lines.length) return header;
40
+ const items = lines.map((line) => `- ${line.name} \xD7 ${line.quantity} (${line.total} ${line.currency})`).join("\n");
41
+ return `${header}
42
+
43
+ Items:
44
+ ${items}`;
45
+ }
46
+ __name(formatOrderDetailsText, "formatOrderDetailsText");
47
+ function formatOrderDetailsHtml(input) {
48
+ const text = formatOrderDetailsText(input);
49
+ const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
50
+ return `<pre style="font-family:inherit;white-space:pre-wrap;margin:0">${escaped}</pre>`;
51
+ }
52
+ __name(formatOrderDetailsHtml, "formatOrderDetailsHtml");
53
+ function buildEventOrderTemplateVariables(input) {
54
+ const { event, order, contact, productNames, vendorName = "", orderLines = [], siteUrl } = input;
55
+ const trackUrl = buildOrderTrackUrl(order.qrToken, siteUrl, order.orderNumber);
56
+ const qrImageUrl = buildOrderQrImageUrl(trackUrl, 200, order.orderNumber);
57
+ const ticketQr = qrImageUrl ? `<img src="${qrImageUrl}" alt="Ticket QR Code" width="200" height="200" style="display:block;margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;" />` : "";
58
+ const baseSite = (siteUrl ?? resolvePublicSiteUrl()).replace(/\/+$/, "");
59
+ const invoiceNumber = `INV-${order.orderNumber ?? ""}`;
60
+ const invoiceUrl = baseSite ? `${baseSite}/api/orders/${order.orderNumber ?? ""}/invoice` : `/api/orders/${order.orderNumber ?? ""}/invoice`;
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 ?? productNames ?? "",
69
+ vendorName: vendorName.trim(),
70
+ eventSlug: event.slug ?? "",
71
+ venue: event.venue ?? "",
72
+ startDate: formatEventDate(event.startDate),
73
+ orderNumber: String(order.orderNumber ?? ""),
74
+ orderTotal: String(order.total ?? ""),
75
+ currency: String(order.currency ?? "INR"),
76
+ customerName: contact.name?.trim() || contact.email?.split("@")[0] || "Guest",
77
+ customerEmail: contact.email?.trim() || "",
78
+ customerPhone: contact.phone?.trim() || "",
79
+ productNames,
80
+ trackUrl,
81
+ qrImageUrl,
82
+ ticketQr,
83
+ invoiceNumber,
84
+ invoiceUrl,
85
+ orderDetails: formatOrderDetailsText(orderDetailsPayload),
86
+ orderDetailsHtml: formatOrderDetailsHtml(orderDetailsPayload)
87
+ };
88
+ }
89
+ __name(buildEventOrderTemplateVariables, "buildEventOrderTemplateVariables");
90
+ function formatEventDate(d) {
91
+ if (!d) return "";
92
+ try {
93
+ return new Date(d).toLocaleString(void 0, {
94
+ dateStyle: "medium",
95
+ timeStyle: "short"
96
+ });
97
+ } catch {
98
+ return String(d);
99
+ }
100
+ }
101
+ __name(formatEventDate, "formatEventDate");
102
+
103
+ // src/lib/order-notification-context.ts
104
+ async function loadOrderLines(dataSource, entityMap, orderId, currency) {
105
+ if (!entityMap.order_items) return [];
106
+ const itemRows = await dataSource.getRepository(entityMap.order_items).find({
107
+ where: {
108
+ orderId
109
+ },
110
+ relations: [
111
+ "product"
112
+ ],
113
+ order: {
114
+ id: "ASC"
115
+ }
116
+ });
117
+ return itemRows.map((item) => {
118
+ const row = item;
119
+ const name = row.product?.name || row.product?.title || `Product #${row.productId}`;
120
+ return {
121
+ name: String(name),
122
+ quantity: Number(row.quantity) || 1,
123
+ total: row.total,
124
+ currency
125
+ };
126
+ });
127
+ }
128
+ __name(loadOrderLines, "loadOrderLines");
129
+ async function loadPrimaryEvent(dataSource, entityMap, itemRows) {
130
+ if (!entityMap.event_products || !entityMap.events) {
131
+ return {
132
+ productNames: []
133
+ };
134
+ }
135
+ const epRepo = dataSource.getRepository(entityMap.event_products);
136
+ const eventRepo = dataSource.getRepository(entityMap.events);
137
+ const eventMap = /* @__PURE__ */ new Map();
138
+ for (const item of itemRows) {
139
+ const productId = item.productId;
140
+ const productName = item.product?.name || item.product?.title || `Product #${productId}`;
141
+ const eps = await epRepo.find({
142
+ where: {
143
+ productId,
144
+ isActive: true
145
+ }
146
+ });
147
+ for (const ep of eps) {
148
+ const eventId = ep.eventId;
149
+ const existing = eventMap.get(eventId);
150
+ if (existing) {
151
+ if (!existing.productNames.includes(String(productName))) {
152
+ existing.productNames.push(String(productName));
153
+ }
154
+ } else {
155
+ const event = await eventRepo.findOne({
156
+ where: {
157
+ id: eventId,
158
+ deleted: false
159
+ }
160
+ });
161
+ if (event) {
162
+ eventMap.set(eventId, {
163
+ event,
164
+ productNames: [
165
+ String(productName)
166
+ ]
167
+ });
168
+ }
169
+ }
170
+ }
171
+ }
172
+ const first = eventMap.values().next().value;
173
+ if (!first) return {
174
+ productNames: []
175
+ };
176
+ return {
177
+ event: first.event,
178
+ productNames: first.productNames
179
+ };
180
+ }
181
+ __name(loadPrimaryEvent, "loadPrimaryEvent");
182
+ async function isFeatureGroupEnabled(dataSource, entityMap, group) {
183
+ if (!entityMap.configs) return true;
184
+ try {
185
+ const rows = await dataSource.getRepository(entityMap.configs).find({
186
+ where: {
187
+ settings: group,
188
+ deleted: false
189
+ }
190
+ });
191
+ const settings = Object.fromEntries(rows.map((r) => [
192
+ r.key,
193
+ r.value
194
+ ]));
195
+ return settings.enabled !== "false" && settings.enabled !== "0";
196
+ } catch {
197
+ return true;
198
+ }
199
+ }
200
+ __name(isFeatureGroupEnabled, "isFeatureGroupEnabled");
201
+ async function loadOrderNotificationContexts(orderId, deps) {
202
+ if (!deps.entityMap.orders) return null;
203
+ const order = await deps.dataSource.getRepository(deps.entityMap.orders).findOne({
204
+ where: {
205
+ id: orderId,
206
+ deleted: false
207
+ },
208
+ relations: [
209
+ "contact"
210
+ ]
211
+ });
212
+ if (!order) return null;
213
+ const o = order;
214
+ const meta = o.metadata && typeof o.metadata === "object" && !Array.isArray(o.metadata) ? o.metadata : {};
215
+ const metaBuyerEmail = typeof meta.buyerEmail === "string" && meta.buyerEmail.includes("@") ? meta.buyerEmail.trim() : null;
216
+ const metaCheckoutEmail = typeof meta.checkoutEmail === "string" && meta.checkoutEmail.includes("@") ? meta.checkoutEmail.trim() : null;
217
+ const metaBuyerName = typeof meta.buyerName === "string" && meta.buyerName.trim() ? meta.buyerName.trim() : null;
218
+ const rawContact = o.contact ?? {};
219
+ const contact = {
220
+ name: metaBuyerName || rawContact.name,
221
+ email: metaBuyerEmail || metaCheckoutEmail || rawContact.email,
222
+ phone: rawContact.phone
223
+ };
224
+ const currency = String(o.currency ?? "INR");
225
+ const siteUrl = resolvePublicSiteUrl();
226
+ const itemRows = await deps.dataSource.getRepository(deps.entityMap.order_items).find({
227
+ where: {
228
+ orderId
229
+ },
230
+ relations: [
231
+ "product"
232
+ ],
233
+ order: {
234
+ id: "ASC"
235
+ }
236
+ });
237
+ const orderLines = await loadOrderLines(deps.dataSource, deps.entityMap, orderId, currency);
238
+ const { event, productNames: eventProductNames } = await loadPrimaryEvent(deps.dataSource, deps.entityMap, itemRows);
239
+ const allProductNames = orderLines.map((line) => line.name);
240
+ const productNames = eventProductNames.length > 0 ? eventProductNames.join(", ") : allProductNames.join(", ");
241
+ const [multiVendorEnabled, eventsEnabled] = await Promise.all([
242
+ isFeatureGroupEnabled(deps.dataSource, deps.entityMap, "multi_vendor"),
243
+ isFeatureGroupEnabled(deps.dataSource, deps.entityMap, "events")
244
+ ]);
245
+ let vendorName = "";
246
+ if (multiVendorEnabled) {
247
+ const vendorId = o.vendorId ?? event?.vendorId;
248
+ if (vendorId && deps.entityMap.vendors) {
249
+ try {
250
+ const vRow = await deps.dataSource.getRepository(deps.entityMap.vendors).findOne({
251
+ where: {
252
+ id: vendorId
253
+ }
254
+ });
255
+ if (vRow) {
256
+ const v = vRow;
257
+ vendorName = String(v.storeName?.trim() || v.name?.trim() || v.companyName?.trim() || "");
258
+ }
259
+ } catch {
260
+ }
261
+ }
262
+ }
263
+ const effectiveEvent = eventsEnabled ? event : void 0;
264
+ const variables = effectiveEvent ? buildEventOrderTemplateVariables({
265
+ event: effectiveEvent,
266
+ order: {
267
+ orderNumber: o.orderNumber,
268
+ total: o.total,
269
+ currency,
270
+ qrToken: o.qrToken
271
+ },
272
+ contact,
273
+ productNames,
274
+ vendorName,
275
+ orderLines,
276
+ siteUrl
277
+ }) : buildEventOrderTemplateVariables({
278
+ event: {
279
+ name: eventsEnabled ? productNames || "Your order" : "",
280
+ slug: "",
281
+ venue: "",
282
+ startDate: null
283
+ },
284
+ order: {
285
+ orderNumber: o.orderNumber,
286
+ total: o.total,
287
+ currency,
288
+ qrToken: o.qrToken
289
+ },
290
+ contact,
291
+ productNames,
292
+ vendorName,
293
+ orderLines,
294
+ siteUrl
295
+ });
296
+ return {
297
+ order: {
298
+ id: o.id,
299
+ orderNumber: String(o.orderNumber ?? ""),
300
+ total: o.total,
301
+ currency,
302
+ qrToken: o.qrToken
303
+ },
304
+ contact,
305
+ orderLines,
306
+ productNames,
307
+ event,
308
+ variables
309
+ };
310
+ }
311
+ __name(loadOrderNotificationContexts, "loadOrderNotificationContexts");
312
+
313
+ // src/plugins/whatsapp/whatsapp-queue.ts
314
+ var WHATSAPP_QUEUE_NAME = "whatsapp";
315
+ function maskPhone(raw) {
316
+ const digits = raw.replace(/\D/g, "");
317
+ if (digits.length <= 4) return "****";
318
+ return `${"*".repeat(Math.max(0, digits.length - 4))}${digits.slice(-4)}`;
319
+ }
320
+ __name(maskPhone, "maskPhone");
321
+ function registerWhatsAppQueueProcessor(cms) {
322
+ const queue = cms.getPlugin("queue");
323
+ const whatsapp = cms.getPlugin("whatsapp");
324
+ if (!queue) {
325
+ console.warn("[whatsapp] queue processor not registered: queue plugin missing");
326
+ return;
327
+ }
328
+ if (!whatsapp || typeof whatsapp.send !== "function") {
329
+ console.warn("[whatsapp] queue processor not registered: whatsapp plugin missing or not configured");
330
+ return;
331
+ }
332
+ queue.registerProcessor(WHATSAPP_QUEUE_NAME, async (data) => {
333
+ const payload = data;
334
+ if (!payload.to) {
335
+ console.warn("[whatsapp] queue job skipped: missing recipient");
336
+ return;
337
+ }
338
+ console.log("[whatsapp] queue job processing", {
339
+ to: maskPhone(payload.to),
340
+ templateKey: payload.templateKey ?? null,
341
+ externalTemplateRef: payload.externalTemplateRef ?? null
342
+ });
343
+ try {
344
+ const ok = await whatsapp.send(payload);
345
+ if (ok) {
346
+ console.log("[whatsapp] queue job completed", {
347
+ to: maskPhone(payload.to),
348
+ sent: true
349
+ });
350
+ } else {
351
+ console.warn("[whatsapp] queue job completed without delivery", {
352
+ to: maskPhone(payload.to),
353
+ sent: false
354
+ });
355
+ }
356
+ } catch (err) {
357
+ console.error("[whatsapp] queue job failed", {
358
+ to: maskPhone(payload.to),
359
+ error: err instanceof Error ? err.message : String(err)
360
+ });
361
+ }
362
+ });
363
+ console.log("[whatsapp] queue processor registered", {
364
+ queue: WHATSAPP_QUEUE_NAME
365
+ });
366
+ }
367
+ __name(registerWhatsAppQueueProcessor, "registerWhatsAppQueueProcessor");
368
+ async function queueWhatsApp(cms, payload) {
369
+ const queue = cms.getPlugin("queue");
370
+ if (queue) {
371
+ console.log("[whatsapp] enqueue", {
372
+ to: maskPhone(payload.to),
373
+ templateKey: payload.templateKey ?? null,
374
+ externalTemplateRef: payload.externalTemplateRef ?? null
375
+ });
376
+ await queue.add(WHATSAPP_QUEUE_NAME, payload);
377
+ return true;
378
+ }
379
+ const whatsapp = cms.getPlugin("whatsapp");
380
+ if (whatsapp && typeof whatsapp.send === "function") {
381
+ console.log("[whatsapp] no queue plugin \u2014 sending immediately", {
382
+ to: maskPhone(payload.to)
383
+ });
384
+ return whatsapp.send(payload);
385
+ }
386
+ console.warn("[whatsapp] send skipped: neither queue nor whatsapp plugin available", {
387
+ to: maskPhone(payload.to)
388
+ });
389
+ return false;
390
+ }
391
+ __name(queueWhatsApp, "queueWhatsApp");
392
+
393
+ // src/plugins/whatsapp/whatsapp-service.ts
394
+ function norm(v) {
395
+ const t = v?.trim();
396
+ return t || void 0;
397
+ }
398
+ __name(norm, "norm");
399
+ function pick(plugin, db, env, ...keys) {
400
+ for (const key of keys) {
401
+ const pk = key;
402
+ if (pk in plugin && plugin[pk] !== void 0 && String(plugin[pk]).trim() !== "") {
403
+ const v = norm(String(plugin[pk]));
404
+ if (v) return v;
405
+ }
406
+ if (norm(db[key])) return norm(db[key]);
407
+ if (norm(env[key])) return norm(env[key]);
408
+ }
409
+ return void 0;
410
+ }
411
+ __name(pick, "pick");
412
+ function mergeWhatsAppConfigLayers(env, db, plugin) {
413
+ return {
414
+ accessToken: pick(plugin, db, env, "accessToken", "WHATSAPP_ACCESS_TOKEN"),
415
+ phoneNumberId: pick(plugin, db, env, "phoneNumberId", "WHATSAPP_PHONE_NUMBER_ID"),
416
+ apiVersion: pick(plugin, db, env, "apiVersion", "WHATSAPP_API_VERSION") ?? "v21.0"
417
+ };
418
+ }
419
+ __name(mergeWhatsAppConfigLayers, "mergeWhatsAppConfigLayers");
420
+ function isWhatsAppPluginEnabled(db) {
421
+ const v = (db.enabled ?? "true").toLowerCase();
422
+ return v !== "false" && v !== "0";
423
+ }
424
+ __name(isWhatsAppPluginEnabled, "isWhatsAppPluginEnabled");
425
+ function whatsAppConfigured(config) {
426
+ return Boolean(config.accessToken?.trim() && config.phoneNumberId?.trim());
427
+ }
428
+ __name(whatsAppConfigured, "whatsAppConfigured");
429
+ function normalizeWhatsAppRecipient(to) {
430
+ const digits = to.replace(/\D/g, "");
431
+ return digits;
432
+ }
433
+ __name(normalizeWhatsAppRecipient, "normalizeWhatsAppRecipient");
434
+ function resolveMetaWhatsAppTemplateName(opts) {
435
+ const ref = opts.externalTemplateRef?.trim();
436
+ const rowName = opts.name?.trim();
437
+ if (ref && !/^\d+$/.test(ref)) return ref;
438
+ if (rowName) return rowName;
439
+ return ref || void 0;
440
+ }
441
+ __name(resolveMetaWhatsAppTemplateName, "resolveMetaWhatsAppTemplateName");
442
+ function maskPhone2(digits) {
443
+ if (digits.length <= 4) return "****";
444
+ return `${"*".repeat(Math.max(0, digits.length - 4))}${digits.slice(-4)}`;
445
+ }
446
+ __name(maskPhone2, "maskPhone");
447
+ function logWhatsApp(level, message, extra) {
448
+ const line = extra ? `${message} ${JSON.stringify(extra)}` : message;
449
+ if (level === "info") console.log(`[whatsapp] ${line}`);
450
+ else if (level === "warn") console.warn(`[whatsapp] ${line}`);
451
+ else console.error(`[whatsapp] ${line}`);
452
+ }
453
+ __name(logWhatsApp, "logWhatsApp");
454
+ var WhatsAppService = class {
455
+ static {
456
+ __name(this, "WhatsAppService");
457
+ }
458
+ getWhatsAppSettings;
459
+ config;
460
+ getMessageTemplateRow;
461
+ constructor(env, plugin = {}, getWhatsAppSettings, getMessageTemplateRow) {
462
+ this.getWhatsAppSettings = getWhatsAppSettings;
463
+ this.getMessageTemplateRow = getMessageTemplateRow;
464
+ this.config = mergeWhatsAppConfigLayers(env, {}, plugin);
465
+ }
466
+ async mergedConfig() {
467
+ let db = {};
468
+ try {
469
+ db = await this.getWhatsAppSettings?.() ?? {};
470
+ } catch {
471
+ }
472
+ return mergeWhatsAppConfigLayers((typeof process !== "undefined" ? process.env : {}) ?? {}, db, this.config);
473
+ }
474
+ async send(opts) {
475
+ const cfg = await this.mergedConfig();
476
+ if (!whatsAppConfigured(cfg)) {
477
+ logWhatsApp("warn", "send skipped: not configured (Plugins \u2192 WhatsApp or WHATSAPP_ACCESS_TOKEN + WHATSAPP_PHONE_NUMBER_ID)");
478
+ return false;
479
+ }
480
+ const to = normalizeWhatsAppRecipient(opts.to);
481
+ if (!to) {
482
+ logWhatsApp("warn", "send skipped: invalid recipient", {
483
+ rawTo: opts.to
484
+ });
485
+ return false;
486
+ }
487
+ logWhatsApp("info", "send started", {
488
+ to: maskPhone2(to),
489
+ templateKey: opts.templateKey ?? null,
490
+ externalTemplateRef: opts.externalTemplateRef ?? null,
491
+ phoneNumberId: cfg.phoneNumberId
492
+ });
493
+ let templateName = resolveMetaWhatsAppTemplateName({
494
+ externalTemplateRef: opts.externalTemplateRef
495
+ });
496
+ let templateLanguage = opts.templateLanguage?.trim();
497
+ let body = opts.body?.trim() ?? "";
498
+ const variables = opts.variables ?? {};
499
+ if (opts.templateKey?.trim() && this.getMessageTemplateRow) {
500
+ const { resolveEventOrderTemplate, EVENT_ORDER_TEMPLATE_KEY } = await import('./event-order-defaults-XQ3IDPD7.js');
501
+ if (opts.templateKey.trim() === EVENT_ORDER_TEMPLATE_KEY) {
502
+ const resolved = await resolveEventOrderTemplate("whatsapp", async (ch, key) => {
503
+ const row = await this.getMessageTemplateRow(ch, key);
504
+ if (!row) return null;
505
+ return {
506
+ subject: null,
507
+ body: row.body,
508
+ externalTemplateRef: row.externalTemplateRef,
509
+ enabled: row.enabled
510
+ };
511
+ });
512
+ if (resolved && !resolved.enabled) {
513
+ logWhatsApp("warn", "send skipped: template disabled in message_templates", {
514
+ templateKey: opts.templateKey
515
+ });
516
+ return false;
517
+ }
518
+ if (resolved) {
519
+ body = resolved.body;
520
+ if (resolved.externalTemplateRef) templateName = resolved.externalTemplateRef;
521
+ }
522
+ }
523
+ }
524
+ const { applyTemplateVars: applyTemplateVars2 } = await import('./interpolate-WDUWDF3I.js');
525
+ if (body) body = applyTemplateVars2(body, variables);
526
+ if (templateName) {
527
+ const paramValues = opts.templateParamOrder?.length ? opts.templateParamOrder.map((key) => String(variables[key] ?? "").slice(0, 1024)) : Object.keys(variables).length ? Object.values(variables) : body ? [
528
+ body
529
+ ] : [];
530
+ logWhatsApp("info", "sending template message", {
531
+ to: maskPhone2(to),
532
+ templateName,
533
+ paramCount: paramValues.length,
534
+ paramOrder: opts.templateParamOrder ?? null
535
+ });
536
+ return this.sendTemplateMessage(cfg, to, templateName, paramValues, templateLanguage);
537
+ }
538
+ if (!body) {
539
+ logWhatsApp("warn", "send skipped: no template name and empty body", {
540
+ to: maskPhone2(to)
541
+ });
542
+ return false;
543
+ }
544
+ logWhatsApp("info", "sending text message", {
545
+ to: maskPhone2(to),
546
+ bodyLength: body.length
547
+ });
548
+ return this.sendTextMessage(cfg, to, body);
549
+ }
550
+ async sendTextMessage(cfg, to, body) {
551
+ const url = `https://graph.facebook.com/${cfg.apiVersion}/${cfg.phoneNumberId}/messages`;
552
+ const res = await fetch(url, {
553
+ method: "POST",
554
+ headers: {
555
+ Authorization: `Bearer ${cfg.accessToken}`,
556
+ "Content-Type": "application/json"
557
+ },
558
+ body: JSON.stringify({
559
+ messaging_product: "whatsapp",
560
+ to,
561
+ type: "text",
562
+ text: {
563
+ body
564
+ }
565
+ })
566
+ });
567
+ if (!res.ok) {
568
+ const errText = await res.text().catch(() => "");
569
+ logWhatsApp("error", "text send failed", {
570
+ status: res.status,
571
+ to: maskPhone2(to),
572
+ error: errText
573
+ });
574
+ return false;
575
+ }
576
+ const data = await res.json().catch(() => ({}));
577
+ logWhatsApp("info", "text send succeeded", {
578
+ to: maskPhone2(to),
579
+ messageId: data.messages?.[0]?.id ?? null
580
+ });
581
+ return true;
582
+ }
583
+ async sendTemplateMessage(cfg, to, templateName, paramValues, templateLanguage) {
584
+ const components = paramValues.length > 0 ? [
585
+ {
586
+ type: "body",
587
+ parameters: paramValues.map((text) => ({
588
+ type: "text",
589
+ text: String(text).slice(0, 1024)
590
+ }))
591
+ }
592
+ ] : void 0;
593
+ const url = `https://graph.facebook.com/${cfg.apiVersion}/${cfg.phoneNumberId}/messages`;
594
+ const payload = {
595
+ messaging_product: "whatsapp",
596
+ to,
597
+ type: "template",
598
+ template: {
599
+ name: templateName,
600
+ language: {
601
+ code: templateLanguage?.trim() || "en"
602
+ },
603
+ ...components ? {
604
+ components
605
+ } : {}
606
+ }
607
+ };
608
+ const res = await fetch(url, {
609
+ method: "POST",
610
+ headers: {
611
+ Authorization: `Bearer ${cfg.accessToken}`,
612
+ "Content-Type": "application/json"
613
+ },
614
+ body: JSON.stringify(payload)
615
+ });
616
+ if (!res.ok) {
617
+ const errText = await res.text().catch(() => "");
618
+ logWhatsApp("error", "template send failed", {
619
+ status: res.status,
620
+ to: maskPhone2(to),
621
+ templateName,
622
+ paramCount: paramValues.length,
623
+ error: errText
624
+ });
625
+ return false;
626
+ }
627
+ const data = await res.json().catch(() => ({}));
628
+ logWhatsApp("info", "template send succeeded", {
629
+ to: maskPhone2(to),
630
+ templateName,
631
+ messageId: data.messages?.[0]?.id ?? null
632
+ });
633
+ return true;
634
+ }
635
+ };
636
+
8
637
  // src/plugins/email/templates/layout.ts
9
638
  function escapeHtml(s) {
10
639
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -567,6 +1196,19 @@ ${slugNote}
567
1196
  `Owner / invitee: ${ownerName?.trim() || "\u2014"} (${ownerEmail})`,
568
1197
  `Activation: ${activation === "invite" ? "Invitation" : "Password set"}`
569
1198
  ].filter(Boolean).join("\n");
1199
+ } else if (kind === "team_invite" && activation === "membership" && inviteLink) {
1200
+ subject = `You're invited to ${storeLabel}`;
1201
+ bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
1202
+ <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>. You already have an account \u2014 accept below to join this store. You will not need to set a new password.</p>
1203
+ ${primaryCtaButton(inviteLink, "Accept invitation")}
1204
+ <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>`;
1205
+ text = [
1206
+ ownerName?.trim() ? `Hello ${ownerName.trim()},` : "Hello,",
1207
+ "",
1208
+ `You have been invited to join ${storeLabel}.`,
1209
+ "Open this link to accept (no new password required):",
1210
+ inviteLink
1211
+ ].join("\n");
570
1212
  } else if (kind === "team_invite" && activation === "invite" && inviteLink) {
571
1213
  subject = `You're invited to ${storeLabel}`;
572
1214
  bodyHtml = `<p style="margin:0 0 12px 0;font-size:15px;line-height:1.5;color:#333;">${greeting}</p>
@@ -665,6 +1307,8 @@ function renderEmail(templateName, ctx, options) {
665
1307
  return render12(ctx);
666
1308
  }
667
1309
  __name(renderEmail, "renderEmail");
1310
+
1311
+ // src/plugins/email/email-service.ts
668
1312
  var require2 = createRequire(import.meta.url);
669
1313
  var MailComposer = require2("nodemailer/lib/mail-composer");
670
1314
  var SES_REGIONS_WITHOUT_SMTP = /* @__PURE__ */ new Set([
@@ -1031,8 +1675,8 @@ function resolveChatEmailToolSettings(configMap, sources) {
1031
1675
  __name(resolveChatEmailToolSettings, "resolveChatEmailToolSettings");
1032
1676
  function intentByKey(intents, key) {
1033
1677
  if (!key) return null;
1034
- const norm = normalizeIntentKey(key);
1035
- return intents.find((i) => i.intent === norm) ?? null;
1678
+ const norm2 = normalizeIntentKey(key);
1679
+ return intents.find((i) => i.intent === norm2) ?? null;
1036
1680
  }
1037
1681
  __name(intentByKey, "intentByKey");
1038
1682
  function buildIntentTableForPrompt(intents) {
@@ -1418,4 +2062,536 @@ function emailPlugin(config) {
1418
2062
  }
1419
2063
  __name(emailPlugin, "emailPlugin");
1420
2064
 
1421
- export { CHAT_EMAIL_LOG, EmailService, buildChatbotSystemPromptWithEmailTool, buildTranscriptForLeadEmail, detectChatLeadIntent, emailPlugin, emailTemplates, joinRecipientsForSend, parseEmailRecipientsFromConfig, parseIntentRecipientEmails, renderEmail, renderLayout, resolveChatEmailToolSettings, sendChatLeadEmail, serializeEmailRecipients };
2065
+ // src/lib/order-notification-dispatcher.ts
2066
+ var initialized = false;
2067
+ function maskPhone3(raw) {
2068
+ const digits = String(raw ?? "").replace(/\D/g, "");
2069
+ if (digits.length <= 4) return "(none)";
2070
+ return `***${digits.slice(-4)}`;
2071
+ }
2072
+ __name(maskPhone3, "maskPhone");
2073
+ async function getSettingsGroup(dataSource, entityMap, group) {
2074
+ if (!entityMap.configs) return {};
2075
+ const rows = await dataSource.getRepository(entityMap.configs).find({
2076
+ where: {
2077
+ settings: group,
2078
+ deleted: false
2079
+ }
2080
+ });
2081
+ return Object.fromEntries(rows.map((r) => [
2082
+ r.key,
2083
+ r.value
2084
+ ]));
2085
+ }
2086
+ __name(getSettingsGroup, "getSettingsGroup");
2087
+ async function isEmailNotificationsEnabled(dataSource, entityMap) {
2088
+ const settings = await getSettingsGroup(dataSource, entityMap, "event_notifications");
2089
+ if (settings.enabled === "false" || settings.enabled === "0") return false;
2090
+ return settings.email_enabled !== "false" && settings.email_enabled !== "0";
2091
+ }
2092
+ __name(isEmailNotificationsEnabled, "isEmailNotificationsEnabled");
2093
+ async function isWhatsappNotificationsEnabled(dataSource, entityMap) {
2094
+ const settings = await getSettingsGroup(dataSource, entityMap, "event_notifications");
2095
+ if (settings.enabled === "false" || settings.enabled === "0") return false;
2096
+ return settings.whatsapp_enabled !== "false" && settings.whatsapp_enabled !== "0";
2097
+ }
2098
+ __name(isWhatsappNotificationsEnabled, "isWhatsappNotificationsEnabled");
2099
+ async function isTriggerCatalogEnabled(triggerKey, dataSource, entityMap) {
2100
+ if (!entityMap.order_notification_triggers) {
2101
+ console.warn("[order-notifications] order_notification_triggers missing \u2014 run migration 1781230000000-AddOrderNotificationTriggers");
2102
+ return false;
2103
+ }
2104
+ try {
2105
+ const row = await dataSource.getRepository(entityMap.order_notification_triggers).findOne({
2106
+ where: {
2107
+ triggerKey,
2108
+ enabled: true
2109
+ }
2110
+ });
2111
+ if (!row) {
2112
+ console.warn("[order-notifications] trigger disabled or not in DB", {
2113
+ triggerKey
2114
+ });
2115
+ }
2116
+ return Boolean(row);
2117
+ } catch (err) {
2118
+ console.error("[order-notifications] failed to load trigger catalog", {
2119
+ triggerKey,
2120
+ err
2121
+ });
2122
+ return false;
2123
+ }
2124
+ }
2125
+ __name(isTriggerCatalogEnabled, "isTriggerCatalogEnabled");
2126
+ async function loadBoundTemplate(triggerKey, channel, audienceType = "customers", dataSource, entityMap) {
2127
+ if (!entityMap.order_notification_bindings || !entityMap.message_templates) {
2128
+ console.warn("[order-notifications] order_notification_bindings or message_templates missing from entityMap");
2129
+ return null;
2130
+ }
2131
+ const bindingRepo = dataSource.getRepository(entityMap.order_notification_bindings);
2132
+ let binding = await bindingRepo.findOne({
2133
+ where: {
2134
+ triggerKey,
2135
+ channel,
2136
+ type: audienceType,
2137
+ enabled: true
2138
+ }
2139
+ });
2140
+ if (!binding && audienceType === "customers") {
2141
+ binding = await bindingRepo.findOne({
2142
+ where: {
2143
+ triggerKey,
2144
+ channel,
2145
+ enabled: true
2146
+ }
2147
+ });
2148
+ }
2149
+ if (!binding) {
2150
+ console.warn("[order-notifications] no order_notification_bindings row", {
2151
+ triggerKey,
2152
+ channel,
2153
+ audienceType
2154
+ });
2155
+ return null;
2156
+ }
2157
+ const templateId = binding.messageTemplateId;
2158
+ if (templateId == null) {
2159
+ console.warn("[order-notifications] binding exists but no template selected", {
2160
+ triggerKey,
2161
+ channel,
2162
+ audienceType
2163
+ });
2164
+ return null;
2165
+ }
2166
+ const template = await dataSource.getRepository(entityMap.message_templates).findOne({
2167
+ where: {
2168
+ id: templateId,
2169
+ channel,
2170
+ deleted: false,
2171
+ enabled: true
2172
+ }
2173
+ });
2174
+ if (!template) {
2175
+ console.warn("[order-notifications] bound template not found or disabled", {
2176
+ triggerKey,
2177
+ channel,
2178
+ audienceType,
2179
+ templateId
2180
+ });
2181
+ return null;
2182
+ }
2183
+ return template;
2184
+ }
2185
+ __name(loadBoundTemplate, "loadBoundTemplate");
2186
+ function mergeTriggerVariables(payload, rich) {
2187
+ const basic = {
2188
+ orderId: String(payload.orderId ?? ""),
2189
+ orderNumber: payload.orderNumber,
2190
+ customerName: payload.customerName,
2191
+ customerPhone: payload.customerPhone ?? "",
2192
+ total: String(payload.total),
2193
+ orderTotal: String(payload.total),
2194
+ currency: payload.currency,
2195
+ vendorId: String(payload.vendorId ?? ""),
2196
+ ...payload.refundAmount != null ? {
2197
+ refundAmount: String(payload.refundAmount)
2198
+ } : {}
2199
+ };
2200
+ return {
2201
+ ...basic,
2202
+ ...rich ?? {}
2203
+ };
2204
+ }
2205
+ __name(mergeTriggerVariables, "mergeTriggerVariables");
2206
+ async function isAudienceEmailEnabled(dataSource, entityMap, audience) {
2207
+ const settings = await getSettingsGroup(dataSource, entityMap, "event_notifications");
2208
+ if (settings.enabled === "false" || settings.enabled === "0") return false;
2209
+ if (settings.email_enabled === "false" || settings.email_enabled === "0") return false;
2210
+ const key = `email_${audience}_enabled`;
2211
+ return settings[key] !== "false" && settings[key] !== "0";
2212
+ }
2213
+ __name(isAudienceEmailEnabled, "isAudienceEmailEnabled");
2214
+ async function getOrderVendorEmails(orderId, orderVendorId, dataSource, entityMap) {
2215
+ const emails = /* @__PURE__ */ new Set();
2216
+ if (!entityMap.vendors) return [];
2217
+ const vendorRepo = dataSource.getRepository(entityMap.vendors);
2218
+ if (orderVendorId) {
2219
+ try {
2220
+ const v = await vendorRepo.findOne({
2221
+ where: {
2222
+ id: orderVendorId
2223
+ }
2224
+ });
2225
+ if (v) {
2226
+ const row = v;
2227
+ if (row.email?.trim()) emails.add(row.email.trim());
2228
+ if (row.supportEmail?.trim()) emails.add(row.supportEmail.trim());
2229
+ }
2230
+ } catch {
2231
+ }
2232
+ }
2233
+ if (entityMap.order_items) {
2234
+ try {
2235
+ const items = await dataSource.getRepository(entityMap.order_items).find({
2236
+ where: {
2237
+ orderId
2238
+ },
2239
+ relations: [
2240
+ "product"
2241
+ ]
2242
+ });
2243
+ for (const item of items) {
2244
+ const row = item;
2245
+ const vId = row.product?.vendorId;
2246
+ if (vId && vId !== orderVendorId) {
2247
+ const v = await vendorRepo.findOne({
2248
+ where: {
2249
+ id: vId
2250
+ }
2251
+ });
2252
+ if (v) {
2253
+ const vRow = v;
2254
+ if (vRow.email?.trim()) emails.add(vRow.email.trim());
2255
+ if (vRow.supportEmail?.trim()) emails.add(vRow.supportEmail.trim());
2256
+ }
2257
+ }
2258
+ }
2259
+ } catch {
2260
+ }
2261
+ }
2262
+ return Array.from(emails);
2263
+ }
2264
+ __name(getOrderVendorEmails, "getOrderVendorEmails");
2265
+ async function getAdminRecipientEmails(dataSource, entityMap) {
2266
+ const emails = /* @__PURE__ */ new Set();
2267
+ const emailSettings = await getSettingsGroup(dataSource, entityMap, "email");
2268
+ const rawRecipients = [
2269
+ emailSettings.salesTeamEmails,
2270
+ emailSettings.salesTeamEmail,
2271
+ emailSettings.fulfilmentTeamEmails,
2272
+ emailSettings.fulfilmentTeamEmail,
2273
+ emailSettings.adminEmail
2274
+ ];
2275
+ for (const raw of rawRecipients) {
2276
+ if (!raw) continue;
2277
+ const parts = String(raw).split(/[,;]/);
2278
+ for (const p of parts) {
2279
+ const trimmed = p.trim();
2280
+ if (trimmed && trimmed.includes("@")) emails.add(trimmed.toLowerCase());
2281
+ }
2282
+ }
2283
+ if (entityMap.users) {
2284
+ try {
2285
+ const userRepo = dataSource.getRepository(entityMap.users);
2286
+ const adminUsers = await userRepo.find({
2287
+ where: [
2288
+ {
2289
+ groupId: 1,
2290
+ blocked: false
2291
+ },
2292
+ {
2293
+ adminAccess: true,
2294
+ blocked: false
2295
+ }
2296
+ ]
2297
+ });
2298
+ for (const u of adminUsers) {
2299
+ const em = u.email?.trim().toLowerCase();
2300
+ if (em && em.includes("@")) {
2301
+ emails.add(em);
2302
+ }
2303
+ }
2304
+ } catch {
2305
+ }
2306
+ }
2307
+ try {
2308
+ const rows = await dataSource.query(`SELECT DISTINCT LOWER(TRIM(email)) AS email
2309
+ FROM users
2310
+ WHERE ("groupId" = 1 OR "adminAccess" = true)
2311
+ AND COALESCE(blocked, false) = false
2312
+ AND COALESCE(deleted, false) = false
2313
+ AND "deletedAt" IS NULL`);
2314
+ for (const r of rows) {
2315
+ const em = r.email?.trim().toLowerCase();
2316
+ if (em && em.includes("@")) {
2317
+ emails.add(em);
2318
+ }
2319
+ }
2320
+ } catch {
2321
+ }
2322
+ return Array.from(emails);
2323
+ }
2324
+ __name(getAdminRecipientEmails, "getAdminRecipientEmails");
2325
+ function formatBodyForEmailHtml(body) {
2326
+ if (!body) return "";
2327
+ if (/^\s*<(html|body|table|section)[\s>]/i.test(body.trim())) {
2328
+ return body;
2329
+ }
2330
+ const withBreaks = body.replace(/\r\n/g, "\n").replace(/\n/g, "<br />");
2331
+ return `<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; font-size: 15px; line-height: 1.6; color: #1f2937;">${withBreaks}</div>`;
2332
+ }
2333
+ __name(formatBodyForEmailHtml, "formatBodyForEmailHtml");
2334
+ async function sendEmailForTrigger(triggerKey, orderId, audienceType, variables, contactEmail, dataSource, entityMap, getCms) {
2335
+ const template = await loadBoundTemplate(triggerKey, "email", audienceType, dataSource, entityMap);
2336
+ if (!template) return;
2337
+ const [branding, emailSettings] = await Promise.all([
2338
+ getSettingsGroup(dataSource, entityMap, "branding"),
2339
+ getSettingsGroup(dataSource, entityMap, "email")
2340
+ ]);
2341
+ const companyDetails = mergeEmailLayoutCompanyDetails(branding, emailSettings);
2342
+ const subject = applyTemplateVars(template.subject ?? "Order update", variables);
2343
+ const rawBody = applyTemplateVars(template.body, variables);
2344
+ const bodyHtml = formatBodyForEmailHtml(rawBody);
2345
+ const html = renderLayout({
2346
+ bodyHtml,
2347
+ companyDetails
2348
+ });
2349
+ const cms = await getCms();
2350
+ const isCustomer = audienceType === "customers";
2351
+ await queueEmail(cms, {
2352
+ to: contactEmail,
2353
+ subject,
2354
+ html,
2355
+ text: rawBody.replace(/<[^>]+>/g, "").trim(),
2356
+ ...isCustomer ? {
2357
+ orderId,
2358
+ attachInvoice: true
2359
+ } : {}
2360
+ });
2361
+ console.log("[order-notifications] email queued", {
2362
+ triggerKey,
2363
+ audienceType,
2364
+ orderId,
2365
+ to: contactEmail,
2366
+ attachInvoice: isCustomer
2367
+ });
2368
+ }
2369
+ __name(sendEmailForTrigger, "sendEmailForTrigger");
2370
+ async function sendWhatsAppForTrigger(triggerKey, orderId, phone, variables, dataSource, entityMap, getCms) {
2371
+ const template = await loadBoundTemplate(triggerKey, "whatsapp", "customers", dataSource, entityMap);
2372
+ if (!template) return;
2373
+ const paramOrder = template.providerMeta?.paramOrder ?? [];
2374
+ if (paramOrder.length === 0) {
2375
+ console.warn("[order-notifications] WhatsApp template has no paramOrder set \u2014 variables may send blank/wrong", {
2376
+ triggerKey
2377
+ });
2378
+ }
2379
+ const cms = await getCms();
2380
+ const metaTemplateName = resolveMetaWhatsAppTemplateName({
2381
+ externalTemplateRef: template.externalTemplateRef,
2382
+ name: template.name
2383
+ });
2384
+ if (!metaTemplateName) {
2385
+ console.warn("[order-notifications] bound WhatsApp template has no Meta template name", {
2386
+ triggerKey,
2387
+ templateId: template.id
2388
+ });
2389
+ return;
2390
+ }
2391
+ const sent = await queueWhatsApp(cms, {
2392
+ to: phone.trim(),
2393
+ templateKey: triggerKey,
2394
+ externalTemplateRef: metaTemplateName,
2395
+ templateLanguage: template.providerMeta?.language ?? void 0,
2396
+ body: template.body,
2397
+ variables,
2398
+ templateParamOrder: paramOrder
2399
+ });
2400
+ if (!sent) {
2401
+ console.warn("[order-notifications] WhatsApp send failed", {
2402
+ triggerKey,
2403
+ orderId,
2404
+ hint: "Register whatsappPlugin() + queuePlugin() in getCms(), or set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID"
2405
+ });
2406
+ } else {
2407
+ console.log("[order-notifications] WhatsApp queued/sent", {
2408
+ triggerKey,
2409
+ orderId,
2410
+ phone: maskPhone3(phone)
2411
+ });
2412
+ }
2413
+ }
2414
+ __name(sendWhatsAppForTrigger, "sendWhatsAppForTrigger");
2415
+ async function isOrderPaymentConfirmed(orderId, dataSource, entityMap) {
2416
+ if (!entityMap.orders) return true;
2417
+ try {
2418
+ const orderRepo = dataSource.getRepository(entityMap.orders);
2419
+ const order = await orderRepo.findOne({
2420
+ where: {
2421
+ id: orderId
2422
+ }
2423
+ });
2424
+ if (!order) return false;
2425
+ const o = order;
2426
+ const status = String(o.status ?? "").toLowerCase().trim();
2427
+ const total = Number(o.total ?? 0);
2428
+ if (total <= 0) return true;
2429
+ const confirmedStatuses = [
2430
+ "confirmed",
2431
+ "completed",
2432
+ "processing",
2433
+ "paid",
2434
+ "fulfilled",
2435
+ "shipped"
2436
+ ];
2437
+ if (confirmedStatuses.includes(status)) {
2438
+ return true;
2439
+ }
2440
+ if (entityMap.payments) {
2441
+ const paymentRepo = dataSource.getRepository(entityMap.payments);
2442
+ const payment = await paymentRepo.findOne({
2443
+ where: {
2444
+ orderId
2445
+ }
2446
+ });
2447
+ if (payment) {
2448
+ const pStatus = String(payment.status ?? "").toLowerCase().trim();
2449
+ if (pStatus === "paid" || pStatus === "captured" || pStatus === "completed") {
2450
+ return true;
2451
+ }
2452
+ }
2453
+ }
2454
+ return false;
2455
+ } catch (err) {
2456
+ console.error("[order-notifications] failed to check order payment confirmation", err);
2457
+ return false;
2458
+ }
2459
+ }
2460
+ __name(isOrderPaymentConfirmed, "isOrderPaymentConfirmed");
2461
+ async function handleTrigger(triggerKey, payload, dataSource, entityMap, getCms) {
2462
+ console.log("[order-notifications] received", {
2463
+ triggerKey,
2464
+ orderId: payload.orderId,
2465
+ phone: maskPhone3(payload.customerPhone)
2466
+ });
2467
+ if (triggerKey === "order_placed") {
2468
+ const isConfirmed = await isOrderPaymentConfirmed(payload.orderId, dataSource, entityMap);
2469
+ if (!isConfirmed) {
2470
+ console.log("[order-notifications] skip order_placed: order payment not confirmed yet", {
2471
+ orderId: payload.orderId
2472
+ });
2473
+ return;
2474
+ }
2475
+ }
2476
+ const [emailChannelEnabled, whatsappChannelEnabled] = await Promise.all([
2477
+ isEmailNotificationsEnabled(dataSource, entityMap),
2478
+ isWhatsappNotificationsEnabled(dataSource, entityMap)
2479
+ ]);
2480
+ if (!emailChannelEnabled && !whatsappChannelEnabled) {
2481
+ console.warn("[order-notifications] skip: Both Email and WhatsApp notifications are disabled");
2482
+ return;
2483
+ }
2484
+ const triggerEnabled = await isTriggerCatalogEnabled(triggerKey, dataSource, entityMap);
2485
+ if (!triggerEnabled) return;
2486
+ const context = await loadOrderNotificationContexts(payload.orderId, {
2487
+ dataSource,
2488
+ entityMap
2489
+ });
2490
+ const variables = mergeTriggerVariables(payload, context?.variables);
2491
+ const contactEmail = context?.contact.email?.trim() || "";
2492
+ const contactPhone = context?.contact.phone?.trim() || payload.customerPhone?.trim() || "";
2493
+ if (emailChannelEnabled) {
2494
+ const [customerEnabled, vendorEnabled, adminEnabled] = await Promise.all([
2495
+ isAudienceEmailEnabled(dataSource, entityMap, "customer"),
2496
+ isAudienceEmailEnabled(dataSource, entityMap, "vendor"),
2497
+ isAudienceEmailEnabled(dataSource, entityMap, "admin")
2498
+ ]);
2499
+ if (customerEnabled && contactEmail) {
2500
+ await sendEmailForTrigger(triggerKey, payload.orderId, "customers", variables, contactEmail, dataSource, entityMap, getCms);
2501
+ }
2502
+ if (vendorEnabled) {
2503
+ const multiVendorSettings = await getSettingsGroup(dataSource, entityMap, "multi_vendor");
2504
+ if (multiVendorSettings.enabled !== "false" && multiVendorSettings.enabled !== "0") {
2505
+ const vendorEmails = await getOrderVendorEmails(payload.orderId, payload.vendorId, dataSource, entityMap);
2506
+ for (const vEmail of vendorEmails) {
2507
+ await sendEmailForTrigger(triggerKey, payload.orderId, "vendors", variables, vEmail, dataSource, entityMap, getCms);
2508
+ }
2509
+ }
2510
+ }
2511
+ if (adminEnabled) {
2512
+ const adminEmails = await getAdminRecipientEmails(dataSource, entityMap);
2513
+ for (const aEmail of adminEmails) {
2514
+ await sendEmailForTrigger(triggerKey, payload.orderId, "admin", variables, aEmail, dataSource, entityMap, getCms);
2515
+ }
2516
+ }
2517
+ } else {
2518
+ console.log("[order-notifications] skip email: Email notifications channel is disabled");
2519
+ }
2520
+ if (whatsappChannelEnabled) {
2521
+ if (contactPhone) {
2522
+ await sendWhatsAppForTrigger(triggerKey, payload.orderId, contactPhone, variables, dataSource, entityMap, getCms);
2523
+ } else {
2524
+ console.warn("[order-notifications] skip WhatsApp: no customer phone", {
2525
+ triggerKey,
2526
+ orderId: payload.orderId
2527
+ });
2528
+ }
2529
+ } else {
2530
+ console.log("[order-notifications] skip WhatsApp: WhatsApp notifications channel is disabled");
2531
+ }
2532
+ }
2533
+ __name(handleTrigger, "handleTrigger");
2534
+ function initWhatsappTriggerDispatcher(deps) {
2535
+ if (initialized) return;
2536
+ initialized = true;
2537
+ const { dataSource, entityMap, getCms } = deps;
2538
+ notificationTriggerEmitter.onAnyTrigger((triggerKey, payload) => {
2539
+ void handleTrigger(triggerKey, payload, dataSource, entityMap, getCms).catch((err) => {
2540
+ console.error("[order-notifications]", triggerKey, err);
2541
+ });
2542
+ });
2543
+ console.log("[order-notifications] dispatcher initialized (email + WhatsApp, unified via order_notification_bindings)");
2544
+ }
2545
+ __name(initWhatsappTriggerDispatcher, "initWhatsappTriggerDispatcher");
2546
+ async function resendOrderNotification(triggerKey, orderId, deps) {
2547
+ if (!deps.entityMap.orders) return {
2548
+ ok: false,
2549
+ error: "orders entity missing"
2550
+ };
2551
+ const [emailEnabled, whatsappEnabled] = await Promise.all([
2552
+ isEmailNotificationsEnabled(deps.dataSource, deps.entityMap),
2553
+ isWhatsappNotificationsEnabled(deps.dataSource, deps.entityMap)
2554
+ ]);
2555
+ if (!emailEnabled && !whatsappEnabled) {
2556
+ return {
2557
+ ok: false,
2558
+ error: "Both Email and WhatsApp notifications are disabled"
2559
+ };
2560
+ }
2561
+ const triggerEnabled = await isTriggerCatalogEnabled(triggerKey, deps.dataSource, deps.entityMap);
2562
+ if (!triggerEnabled) {
2563
+ return {
2564
+ ok: false,
2565
+ error: `Trigger "${triggerKey}" is disabled or migration 1781230000000 not applied`
2566
+ };
2567
+ }
2568
+ const order = await deps.dataSource.getRepository(deps.entityMap.orders).findOne({
2569
+ where: {
2570
+ id: orderId,
2571
+ deleted: false
2572
+ },
2573
+ relations: [
2574
+ "contact"
2575
+ ]
2576
+ });
2577
+ if (!order) return {
2578
+ ok: false,
2579
+ error: "Order not found"
2580
+ };
2581
+ const o = order;
2582
+ await handleTrigger(triggerKey, {
2583
+ orderId,
2584
+ orderNumber: String(o.orderNumber ?? ""),
2585
+ customerName: o.contact?.name ?? "",
2586
+ customerPhone: o.contact?.phone ?? null,
2587
+ total: o.total ?? 0,
2588
+ currency: String(o.currency ?? "INR"),
2589
+ vendorId: o.vendorId ?? null
2590
+ }, deps.dataSource, deps.entityMap, deps.getCms);
2591
+ return {
2592
+ ok: true
2593
+ };
2594
+ }
2595
+ __name(resendOrderNotification, "resendOrderNotification");
2596
+
2597
+ export { CHAT_EMAIL_LOG, EmailService, WhatsAppService, buildChatbotSystemPromptWithEmailTool, buildEventOrderTemplateVariables, buildTranscriptForLeadEmail, detectChatLeadIntent, emailPlugin, emailTemplates, initWhatsappTriggerDispatcher, isWhatsAppPluginEnabled, joinRecipientsForSend, mergeWhatsAppConfigLayers, parseEmailRecipientsFromConfig, parseIntentRecipientEmails, queueWhatsApp, registerWhatsAppQueueProcessor, renderEmail, renderLayout, resendOrderNotification, resolveChatEmailToolSettings, sendChatLeadEmail, serializeEmailRecipients, whatsAppConfigured };