@infuro/cms-core 1.0.61 → 1.0.63

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 (50) hide show
  1. package/dist/admin.cjs +3624 -2642
  2. package/dist/admin.js +2415 -1433
  3. package/dist/api.cjs +41 -37
  4. package/dist/api.js +9 -5
  5. package/dist/chunk-3VZAAQUV.js +106 -0
  6. package/dist/{chunk-UHT4INVW.js → chunk-77YWLP4X.js} +625 -252
  7. package/dist/{chunk-BXYZDMTZ.cjs → chunk-7L556RGL.cjs} +3 -94
  8. package/dist/{chunk-T3HPSF7K.js → chunk-AYWDQFJZ.js} +3 -0
  9. package/dist/{chunk-URN7GS23.js → chunk-BWOITUNI.js} +203 -1062
  10. package/dist/{chunk-CNAHVRRU.cjs → chunk-CJEOH6QC.cjs} +676 -312
  11. package/dist/{chunk-O2642WVS.js → chunk-DTUL3Q5L.js} +17 -3
  12. package/dist/{chunk-YSYX4GUD.cjs → chunk-EWXG4E74.cjs} +213 -1082
  13. package/dist/chunk-GWDI752Q.js +83 -0
  14. package/dist/chunk-H3IVLIPR.cjs +86 -0
  15. package/dist/chunk-JLDHK2QE.cjs +109 -0
  16. package/dist/chunk-KAOHOHCA.js +901 -0
  17. package/dist/{chunk-2KUCQVAQ.js → chunk-MWEK7N3F.js} +2 -91
  18. package/dist/{chunk-V25RDUOU.cjs → chunk-MXABMVF7.cjs} +38 -4
  19. package/dist/chunk-OVTOP42W.js +199 -0
  20. package/dist/{chunk-73WVHINE.cjs → chunk-RHYVNRYG.cjs} +18 -4
  21. package/dist/{chunk-L3525VXI.js → chunk-RXTUSF3R.js} +36 -2
  22. package/dist/{chunk-77I3KS7V.cjs → chunk-UEE4PTTB.cjs} +3 -0
  23. package/dist/chunk-WFMVD567.cjs +209 -0
  24. package/dist/chunk-YVP4NQII.cjs +914 -0
  25. package/dist/{email-queue-6NJY6HNM.cjs → email-queue-VTYL2KFA.cjs} +7 -6
  26. package/dist/{email-queue-OI2HSCGE.js → email-queue-YPRSVG56.js} +3 -2
  27. package/dist/email-service-ATCPJFWG.cjs +28 -0
  28. package/dist/email-service-DPKVQOKP.js +3 -0
  29. package/dist/{emit-order-notification-trigger-TNEZOYEE.cjs → emit-order-notification-trigger-WI4HGMKH.cjs} +4 -4
  30. package/dist/{emit-order-notification-trigger-CZU3V2WE.js → emit-order-notification-trigger-XVG2B5ZF.js} +2 -2
  31. package/dist/{erp-order-invoice-3GXDE443.js → erp-order-invoice-3UGWLICU.js} +2 -1
  32. package/dist/{erp-order-invoice-EYYNR526.cjs → erp-order-invoice-KJYJNWMG.cjs} +6 -5
  33. package/dist/index.cjs +366 -316
  34. package/dist/index.d.cts +61 -21
  35. package/dist/index.d.ts +61 -21
  36. package/dist/index.js +79 -29
  37. package/dist/migrations/1783000000000-AddOrderPendingProcessingCompletedTriggers.ts +56 -0
  38. package/dist/migrations/1783100000000-AddSmsToOrderNotificationBindingsChannelEnum.ts +17 -0
  39. package/dist/migrations/1783200000000-AddOrderAssigneeColumns.ts +30 -0
  40. package/dist/order-assignees-handlers-LKMAGLG6.js +150 -0
  41. package/dist/order-assignees-handlers-NPKD64P6.cjs +152 -0
  42. package/dist/order-completion-otp-handlers-IMMQGHDR.cjs +363 -0
  43. package/dist/order-completion-otp-handlers-WGM7HWG4.js +361 -0
  44. package/dist/order-notification-dispatcher-5TUFCDU7.cjs +35 -0
  45. package/dist/order-notification-dispatcher-JKFQJYGG.js +10 -0
  46. package/dist/sms-notification-templates-handlers-SJLO7JGZ.js +47 -0
  47. package/dist/sms-notification-templates-handlers-YSB3L2PK.cjs +49 -0
  48. package/package.json +1 -1
  49. package/dist/order-notification-dispatcher-KJVGLK5E.cjs +0 -24
  50. package/dist/order-notification-dispatcher-ZSFKEYMP.js +0 -7
@@ -1,12 +1,15 @@
1
1
  'use strict';
2
2
 
3
+ var chunkWFMVD567_cjs = require('./chunk-WFMVD567.cjs');
3
4
  var chunkXQ3QUHWR_cjs = require('./chunk-XQ3QUHWR.cjs');
4
5
  var chunkHY3AXLOI_cjs = require('./chunk-HY3AXLOI.cjs');
5
- var chunkYSYX4GUD_cjs = require('./chunk-YSYX4GUD.cjs');
6
+ var chunkEWXG4E74_cjs = require('./chunk-EWXG4E74.cjs');
7
+ var chunkH3IVLIPR_cjs = require('./chunk-H3IVLIPR.cjs');
6
8
  var chunk7NMT3GBR_cjs = require('./chunk-7NMT3GBR.cjs');
7
- var chunkV25RDUOU_cjs = require('./chunk-V25RDUOU.cjs');
8
- var chunkBXYZDMTZ_cjs = require('./chunk-BXYZDMTZ.cjs');
9
+ var chunkMXABMVF7_cjs = require('./chunk-MXABMVF7.cjs');
10
+ var chunk7L556RGL_cjs = require('./chunk-7L556RGL.cjs');
9
11
  var chunkUPLVMVRX_cjs = require('./chunk-UPLVMVRX.cjs');
12
+ var chunkJLDHK2QE_cjs = require('./chunk-JLDHK2QE.cjs');
10
13
  var chunk3DZRIZOD_cjs = require('./chunk-3DZRIZOD.cjs');
11
14
  var chunkTJ2MIQUT_cjs = require('./chunk-TJ2MIQUT.cjs');
12
15
  var chunk4U6DATGZ_cjs = require('./chunk-4U6DATGZ.cjs');
@@ -1526,9 +1529,15 @@ async function autoExpireOrderIfPaymentTimeExceeded(dataSource, entityMap, order
1526
1529
  if (status !== "pending") return order;
1527
1530
  const meta = typeof order.metadata === "object" && order.metadata ? order.metadata : {};
1528
1531
  const expiresAtStr = meta.paymentExpiresAt ? String(meta.paymentExpiresAt) : null;
1529
- if (!expiresAtStr) return order;
1530
- const expiresMs = new Date(expiresAtStr).getTime();
1531
- if (Number.isNaN(expiresMs) || Date.now() <= expiresMs) return order;
1532
+ let isExpired = false;
1533
+ if (expiresAtStr) {
1534
+ const expiresMs = new Date(expiresAtStr).getTime();
1535
+ if (!Number.isNaN(expiresMs) && Date.now() > expiresMs) isExpired = true;
1536
+ } else if (order.createdAt) {
1537
+ const createdMs = new Date(order.createdAt).getTime();
1538
+ if (!Number.isNaN(createdMs) && Date.now() - createdMs > 10 * 60 * 1e3) isExpired = true;
1539
+ }
1540
+ if (!isExpired) return order;
1532
1541
  try {
1533
1542
  const orderId = Number(order.id);
1534
1543
  if (orderId && entityMap.orders) {
@@ -3557,7 +3566,7 @@ function createCrudHandler(dataSource, entityMap, options) {
3557
3566
  });
3558
3567
  }
3559
3568
  }
3560
- const qb = repo2.createQueryBuilder("order").leftJoinAndSelect("order.contact", "contact").leftJoinAndSelect("order.items", "items").leftJoinAndSelect("items.product", "product").leftJoinAndSelect("product.collection", "collection").leftJoinAndSelect("order.payments", "payments").andWhere("order.deleted = :orderDel", {
3569
+ const qb = repo2.createQueryBuilder("order").leftJoinAndSelect("order.contact", "contact").leftJoinAndSelect("order.items", "items").leftJoinAndSelect("items.product", "product").leftJoinAndSelect("product.collection", "collection").leftJoinAndSelect("order.payments", "payments").leftJoinAndSelect("order.assignedUser", "assignedUser").andWhere("order.deleted = :orderDel", {
3561
3570
  orderDel: false
3562
3571
  }).orderBy(`order.${sortField2}`, sortOrderOrders).skip(skip).take(limit);
3563
3572
  applyVendorScopeToQueryBuilder(qb, "order", scope);
@@ -3615,7 +3624,9 @@ function createCrudHandler(dataSource, entityMap, options) {
3615
3624
  }
3616
3625
  const [rows, total2] = await qb.getManyAndCount();
3617
3626
  const data2 = await Promise.all(rows.map(async (order) => {
3627
+ await autoExpireOrderIfPaymentTimeExceeded(dataSource, entityMap, order);
3618
3628
  const contact = order.contact;
3629
+ const assignedUserObj = order.assignedUser;
3619
3630
  const items = order.items ?? [];
3620
3631
  const orderPayments = order.payments ?? [];
3621
3632
  const parts = [];
@@ -3663,6 +3674,11 @@ function createCrudHandler(dataSource, entityMap, options) {
3663
3674
  email: contact.email,
3664
3675
  phone: contact.phone
3665
3676
  } : null,
3677
+ assignedUser: assignedUserObj ? {
3678
+ id: assignedUserObj.id,
3679
+ name: assignedUserObj.name || assignedUserObj.email,
3680
+ email: assignedUserObj.email
3681
+ } : null,
3666
3682
  itemsSummary,
3667
3683
  paymentStatus: paymentStatus2
3668
3684
  };
@@ -5199,18 +5215,99 @@ function createCrudHandler(dataSource, entityMap, options) {
5199
5215
  }
5200
5216
  await recordDiscountUsage2(dataSource, entityMap, created.id, orderDiscountId, persistBody.contactId, discount);
5201
5217
  }
5218
+ if (entityMap["payments"]) {
5219
+ try {
5220
+ const paymentRepo = dataSource.getRepository(entityMap["payments"]);
5221
+ const initialPayStatus2 = String(persistBody.paymentStatus ?? body.paymentStatus ?? "unpaid").toLowerCase();
5222
+ const isPaid = initialPayStatus2 === "paid" || initialPayStatus2 === "captured";
5223
+ const vId = Number(orderVendorId ?? created?.vendorId ?? 1);
5224
+ const cId = persistBody.contactId ? Number(persistBody.contactId) : null;
5225
+ await paymentRepo.save(paymentRepo.create({
5226
+ vendorId: vId,
5227
+ contactId: cId,
5228
+ orderId: created.id,
5229
+ status: initialPayStatus2,
5230
+ amount: Number(total ?? persistBody.total ?? 0),
5231
+ currency: orderCurrency ?? persistBody.currency ?? "INR",
5232
+ paidAt: isPaid ? /* @__PURE__ */ new Date() : null,
5233
+ method: String(body.paymentMethod ?? "manual")
5234
+ }));
5235
+ } catch (payErr) {
5236
+ console.error("[crud] failed to create initial payment for order", payErr);
5237
+ }
5238
+ }
5202
5239
  const orderIdForNotify = created.id;
5203
- const initialPayStatus = String(persistBody.paymentStatus ?? "unpaid").toLowerCase();
5204
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
5205
- fireOrderNotificationTrigger("order_placed", orderIdForNotify, {
5206
- dataSource,
5207
- entityMap
5208
- });
5209
- if (initialPayStatus === "paid" || initialPayStatus === "captured") {
5210
- fireOrderNotificationTrigger("payment_success", orderIdForNotify, {
5240
+ const finalCreatedStatus = String(created.status ?? createdStatus ?? "pending").toLowerCase();
5241
+ const initialPayStatus = String(persistBody.paymentStatus ?? body.paymentStatus ?? "unpaid").toLowerCase();
5242
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
5243
+ if (finalCreatedStatus === "pending") {
5244
+ if (initialPayStatus === "failed") {
5245
+ fireOrderNotificationTrigger("payment_failed", orderIdForNotify, {
5246
+ dataSource,
5247
+ entityMap
5248
+ });
5249
+ } else {
5250
+ fireOrderNotificationTrigger("order_pending", orderIdForNotify, {
5251
+ dataSource,
5252
+ entityMap
5253
+ });
5254
+ }
5255
+ } else if (finalCreatedStatus === "confirmed") {
5256
+ fireOrderNotificationTrigger("order_placed", orderIdForNotify, {
5257
+ dataSource,
5258
+ entityMap
5259
+ });
5260
+ if (initialPayStatus === "paid" || initialPayStatus === "captured") {
5261
+ fireOrderNotificationTrigger("payment_success", orderIdForNotify, {
5262
+ dataSource,
5263
+ entityMap
5264
+ });
5265
+ } else if (initialPayStatus === "failed") {
5266
+ fireOrderNotificationTrigger("payment_failed", orderIdForNotify, {
5267
+ dataSource,
5268
+ entityMap
5269
+ });
5270
+ }
5271
+ } else if (finalCreatedStatus === "processing") {
5272
+ fireOrderNotificationTrigger("order_processing", orderIdForNotify, {
5273
+ dataSource,
5274
+ entityMap
5275
+ });
5276
+ if (initialPayStatus === "failed") {
5277
+ fireOrderNotificationTrigger("payment_failed", orderIdForNotify, {
5278
+ dataSource,
5279
+ entityMap
5280
+ });
5281
+ }
5282
+ } else if (finalCreatedStatus === "completed") {
5283
+ fireOrderNotificationTrigger("order_completed", orderIdForNotify, {
5211
5284
  dataSource,
5212
5285
  entityMap
5213
5286
  });
5287
+ if (initialPayStatus === "failed") {
5288
+ fireOrderNotificationTrigger("payment_failed", orderIdForNotify, {
5289
+ dataSource,
5290
+ entityMap
5291
+ });
5292
+ }
5293
+ } else if (finalCreatedStatus === "cancelled") {
5294
+ if (initialPayStatus === "failed") {
5295
+ fireOrderNotificationTrigger("payment_failed", orderIdForNotify, {
5296
+ dataSource,
5297
+ entityMap
5298
+ });
5299
+ } else {
5300
+ fireOrderNotificationTrigger("order_cancelled", orderIdForNotify, {
5301
+ dataSource,
5302
+ entityMap
5303
+ });
5304
+ if (initialPayStatus === "paid" || initialPayStatus === "refunded") {
5305
+ fireOrderNotificationTrigger("payment_refund_initiated", orderIdForNotify, {
5306
+ dataSource,
5307
+ entityMap
5308
+ });
5309
+ }
5310
+ }
5214
5311
  }
5215
5312
  });
5216
5313
  }
@@ -5561,8 +5658,7 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
5561
5658
  const scope2 = await resolveScopeById();
5562
5659
  const order = await repo.findOne({
5563
5660
  where: {
5564
- id: Number(id),
5565
- deleted: false
5661
+ id: Number(id)
5566
5662
  },
5567
5663
  relations: [
5568
5664
  "contact",
@@ -5571,7 +5667,8 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
5571
5667
  "items",
5572
5668
  "items.product",
5573
5669
  "items.product.collection",
5574
- "payments"
5670
+ "payments",
5671
+ "assignedUser"
5575
5672
  ]
5576
5673
  });
5577
5674
  if (order) {
@@ -5581,8 +5678,7 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
5581
5678
  if (orderDenied) return orderDenied;
5582
5679
  const relatedOrders = await repo.find({
5583
5680
  where: {
5584
- parentOrderId: Number(id),
5585
- deleted: false
5681
+ parentOrderId: Number(id)
5586
5682
  },
5587
5683
  order: {
5588
5684
  id: "ASC"
@@ -5961,6 +6057,36 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
5961
6057
  lines: []
5962
6058
  } : await calculateOrderTotalsFromLines(dataSource, entityMap, orderLinesNorm, effectiveCurrency, putDiscountId, Number.isFinite(putOrderVendorId) ? putOrderVendorId : null);
5963
6059
  const scalarUpdate = pickColumnUpdates(repo, rawBody);
6060
+ if (rawBody && typeof rawBody === "object" && "assignedUserId" in rawBody && rawBody.assignedUserId !== void 0) {
6061
+ const aId = Number(rawBody.assignedUserId);
6062
+ if (Number.isFinite(aId) && aId > 0) {
6063
+ scalarUpdate.assignedUserId = aId;
6064
+ scalarUpdate.assignedAt = /* @__PURE__ */ new Date();
6065
+ if (!scalarUpdate.status && (orderInvPrev?.status === "confirmed" || orderInvPrev?.status === "pending")) {
6066
+ scalarUpdate.status = "processing";
6067
+ }
6068
+ } else {
6069
+ scalarUpdate.assignedUserId = null;
6070
+ scalarUpdate.assignedAt = null;
6071
+ }
6072
+ }
6073
+ if (scalarUpdate.status === "processing") {
6074
+ const effectiveAssignee = scalarUpdate.assignedUserId !== void 0 ? scalarUpdate.assignedUserId : orderInvPrev?.assignedUserId;
6075
+ if (!effectiveAssignee) {
6076
+ return json({
6077
+ error: "Cannot start processing without assigning a teammate. Please assign a teammate first."
6078
+ }, {
6079
+ status: 400
6080
+ });
6081
+ }
6082
+ }
6083
+ if (scalarUpdate.status === "completed" && orderInvPrev?.status !== "completed" && !rawBody?.__internalBypassOtp) {
6084
+ return json({
6085
+ error: "Direct completion is disabled. Please complete the order via the customer OTP verification flow."
6086
+ }, {
6087
+ status: 400
6088
+ });
6089
+ }
5964
6090
  const nextStatus = typeof scalarUpdate.status === "string" && scalarUpdate.status ? String(scalarUpdate.status) : orderInvPrev?.status ?? "pending";
5965
6091
  if (chunkHY3AXLOI_cjs.orderStatusHoldsStock(nextStatus) && lines.length > 0) {
5966
6092
  const verr = await chunkHY3AXLOI_cjs.validateInventoryForOrderBecomingConfirmed(dataSource, entityMap, orderInvPrev, lines.filter((l) => l.found && l.productId != null).map((l) => ({
@@ -6148,6 +6274,128 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6148
6274
  }
6149
6275
  }
6150
6276
  }
6277
+ if (rawBody && entityMap["payments"]) {
6278
+ try {
6279
+ const bodyPayStatusRaw = rawBody.paymentStatus;
6280
+ if (bodyPayStatusRaw != null && typeof bodyPayStatusRaw === "string") {
6281
+ const payStatus = bodyPayStatusRaw.trim().toLowerCase();
6282
+ const paymentRepo = dataSource.getRepository(entityMap["payments"]);
6283
+ const existingPay = await paymentRepo.findOne({
6284
+ where: {
6285
+ orderId: numericId
6286
+ },
6287
+ order: {
6288
+ id: "DESC"
6289
+ }
6290
+ });
6291
+ const isPaid = payStatus === "paid" || payStatus === "captured";
6292
+ if (existingPay) {
6293
+ await paymentRepo.update(existingPay.id, {
6294
+ status: payStatus,
6295
+ paidAt: isPaid && !existingPay.paidAt ? /* @__PURE__ */ new Date() : existingPay.paidAt
6296
+ });
6297
+ } else {
6298
+ const orderRow = updatedOrder;
6299
+ const orderTotal = Number(orderRow?.total ?? 0);
6300
+ const orderCurrency = String(orderRow?.currency ?? "INR");
6301
+ const vId = Number(orderRow?.vendorId ?? 1);
6302
+ const cId = orderRow?.contactId ? Number(orderRow.contactId) : null;
6303
+ await paymentRepo.save(paymentRepo.create({
6304
+ vendorId: vId,
6305
+ contactId: cId,
6306
+ orderId: numericId,
6307
+ status: payStatus,
6308
+ amount: orderTotal,
6309
+ currency: orderCurrency,
6310
+ paidAt: isPaid ? /* @__PURE__ */ new Date() : null,
6311
+ method: "manual"
6312
+ }));
6313
+ }
6314
+ }
6315
+ } catch (payErr) {
6316
+ console.error("[crud] failed to update/create payment on order update", payErr);
6317
+ }
6318
+ }
6319
+ const statusUpdated = Boolean(scalarUpdate.status || rawBody.status);
6320
+ const paymentUpdated = Boolean(rawBody && typeof rawBody === "object" && rawBody.paymentStatus != null);
6321
+ if (statusUpdated || paymentUpdated) {
6322
+ const newStatus = scalarUpdate.status ? String(scalarUpdate.status).toLowerCase() : rawBody.status ? String(rawBody.status).toLowerCase() : String(updatedOrder.status || "pending").toLowerCase();
6323
+ const payments = Array.isArray(updatedOrder.payments) ? updatedOrder.payments : [];
6324
+ const bodyPayStatus = rawBody && typeof rawBody === "object" && rawBody.paymentStatus != null ? String(rawBody.paymentStatus).toLowerCase() : null;
6325
+ const curPayStatus = bodyPayStatus || String(payments[0]?.status || "unpaid").toLowerCase();
6326
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
6327
+ if (newStatus === "pending") {
6328
+ if (curPayStatus === "failed") {
6329
+ fireOrderNotificationTrigger("payment_failed", updatedOrder.id, {
6330
+ dataSource,
6331
+ entityMap
6332
+ });
6333
+ } else {
6334
+ fireOrderNotificationTrigger("order_pending", updatedOrder.id, {
6335
+ dataSource,
6336
+ entityMap
6337
+ });
6338
+ }
6339
+ } else if (newStatus === "confirmed") {
6340
+ fireOrderNotificationTrigger("order_placed", updatedOrder.id, {
6341
+ dataSource,
6342
+ entityMap
6343
+ });
6344
+ if (curPayStatus === "paid" || curPayStatus === "captured") {
6345
+ fireOrderNotificationTrigger("payment_success", updatedOrder.id, {
6346
+ dataSource,
6347
+ entityMap
6348
+ });
6349
+ } else if (curPayStatus === "failed") {
6350
+ fireOrderNotificationTrigger("payment_failed", updatedOrder.id, {
6351
+ dataSource,
6352
+ entityMap
6353
+ });
6354
+ }
6355
+ } else if (newStatus === "processing") {
6356
+ fireOrderNotificationTrigger("order_processing", updatedOrder.id, {
6357
+ dataSource,
6358
+ entityMap
6359
+ });
6360
+ if (curPayStatus === "failed") {
6361
+ fireOrderNotificationTrigger("payment_failed", updatedOrder.id, {
6362
+ dataSource,
6363
+ entityMap
6364
+ });
6365
+ }
6366
+ } else if (newStatus === "completed") {
6367
+ fireOrderNotificationTrigger("order_completed", updatedOrder.id, {
6368
+ dataSource,
6369
+ entityMap
6370
+ });
6371
+ if (curPayStatus === "failed") {
6372
+ fireOrderNotificationTrigger("payment_failed", updatedOrder.id, {
6373
+ dataSource,
6374
+ entityMap
6375
+ });
6376
+ }
6377
+ } else if (newStatus === "cancelled") {
6378
+ if (curPayStatus === "failed") {
6379
+ fireOrderNotificationTrigger("payment_failed", updatedOrder.id, {
6380
+ dataSource,
6381
+ entityMap
6382
+ });
6383
+ } else {
6384
+ fireOrderNotificationTrigger("order_cancelled", updatedOrder.id, {
6385
+ dataSource,
6386
+ entityMap
6387
+ });
6388
+ if (curPayStatus === "paid" || curPayStatus === "refunded") {
6389
+ fireOrderNotificationTrigger("payment_refund_initiated", updatedOrder.id, {
6390
+ dataSource,
6391
+ entityMap
6392
+ });
6393
+ }
6394
+ }
6395
+ }
6396
+ }).catch(() => {
6397
+ });
6398
+ }
6151
6399
  return json(updatedOrder);
6152
6400
  }
6153
6401
  }
@@ -6624,7 +6872,37 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6624
6872
  if (k in merged) updatePayload[k] = merged[k];
6625
6873
  }
6626
6874
  }
6627
- if (resource === "orders" && orderInvPrev) {
6875
+ if (resource === "orders" && orderInvPrev && rawBody && typeof rawBody === "object") {
6876
+ if ("assignedUserId" in rawBody && rawBody.assignedUserId !== void 0) {
6877
+ const aId = Number(rawBody.assignedUserId);
6878
+ if (Number.isFinite(aId) && aId > 0) {
6879
+ updatePayload.assignedUserId = aId;
6880
+ updatePayload.assignedAt = /* @__PURE__ */ new Date();
6881
+ if (!updatePayload.status && (orderInvPrev.status === "confirmed" || orderInvPrev.status === "pending")) {
6882
+ updatePayload.status = "processing";
6883
+ }
6884
+ } else {
6885
+ updatePayload.assignedUserId = null;
6886
+ updatePayload.assignedAt = null;
6887
+ }
6888
+ }
6889
+ if (updatePayload.status === "processing") {
6890
+ const effectiveAssignee = updatePayload.assignedUserId !== void 0 ? updatePayload.assignedUserId : orderInvPrev?.assignedUserId;
6891
+ if (!effectiveAssignee) {
6892
+ return json({
6893
+ error: "Cannot start processing without assigning a teammate. Please assign a teammate first."
6894
+ }, {
6895
+ status: 400
6896
+ });
6897
+ }
6898
+ }
6899
+ if (updatePayload.status === "completed" && orderInvPrev.status !== "completed" && !rawBody.__internalBypassOtp) {
6900
+ return json({
6901
+ error: "Direct completion is disabled. Please complete the order via the customer OTP verification flow."
6902
+ }, {
6903
+ status: 400
6904
+ });
6905
+ }
6628
6906
  const nextSt = typeof updatePayload.status === "string" && updatePayload.status ? String(updatePayload.status) : orderInvPrev.status;
6629
6907
  if (chunkHY3AXLOI_cjs.orderStatusHoldsStock(nextSt) && orderInvPrev.lines.length > 0) {
6630
6908
  const verr = await chunkHY3AXLOI_cjs.validateInventoryForOrderBecomingConfirmed(dataSource, entityMap, orderInvPrev, orderInvPrev.lines);
@@ -6689,24 +6967,43 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6689
6967
  if (pOrder && Number.isFinite(pOrder)) {
6690
6968
  if (newPayStatus === "paid" || newPayStatus === "captured") {
6691
6969
  if (entityMap.orders) {
6692
- await dataSource.getRepository(entityMap.orders).update(pOrder, {
6693
- status: "confirmed"
6970
+ const ordRepo = dataSource.getRepository(entityMap.orders);
6971
+ const currentOrd = await ordRepo.findOne({
6972
+ where: {
6973
+ id: pOrder
6974
+ }
6694
6975
  });
6976
+ const ordStatus = String(currentOrd?.status || "pending").toLowerCase();
6977
+ if (ordStatus === "pending") {
6978
+ await ordRepo.update(pOrder, {
6979
+ status: "confirmed"
6980
+ });
6981
+ }
6982
+ if (ordStatus === "pending" || ordStatus === "confirmed") {
6983
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
6984
+ fireOrderNotificationTrigger("order_placed", pOrder, {
6985
+ dataSource,
6986
+ entityMap
6987
+ });
6988
+ fireOrderNotificationTrigger("payment_success", pOrder, {
6989
+ dataSource,
6990
+ entityMap
6991
+ });
6992
+ }).catch(() => {
6993
+ });
6994
+ }
6695
6995
  }
6696
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
6697
- fireOrderNotificationTrigger("order_placed", pOrder, {
6698
- dataSource,
6699
- entityMap
6700
- });
6701
- fireOrderNotificationTrigger("payment_success", pOrder, {
6996
+ } else if (newPayStatus === "failed") {
6997
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
6998
+ fireOrderNotificationTrigger("payment_failed", pOrder, {
6702
6999
  dataSource,
6703
7000
  entityMap
6704
7001
  });
6705
7002
  }).catch(() => {
6706
7003
  });
6707
- } else if (newPayStatus === "failed") {
6708
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
6709
- fireOrderNotificationTrigger("payment_failed", pOrder, {
7004
+ } else if (newPayStatus === "refunded") {
7005
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
7006
+ fireOrderNotificationTrigger("payment_refund_initiated", pOrder, {
6710
7007
  dataSource,
6711
7008
  entityMap
6712
7009
  });
@@ -6726,6 +7023,52 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6726
7023
  throw err;
6727
7024
  }
6728
7025
  }
7026
+ if (resource === "orders" && rawBody && entityMap["payments"]) {
7027
+ try {
7028
+ const bodyPayStatusRaw = rawBody.paymentStatus;
7029
+ if (bodyPayStatusRaw != null && typeof bodyPayStatusRaw === "string") {
7030
+ const payStatus = bodyPayStatusRaw.trim().toLowerCase();
7031
+ const paymentRepo = dataSource.getRepository(entityMap["payments"]);
7032
+ const existingPay = await paymentRepo.findOne({
7033
+ where: {
7034
+ orderId: numericId
7035
+ },
7036
+ order: {
7037
+ id: "DESC"
7038
+ }
7039
+ });
7040
+ const isPaid = payStatus === "paid" || payStatus === "captured";
7041
+ if (existingPay) {
7042
+ await paymentRepo.update(existingPay.id, {
7043
+ status: payStatus,
7044
+ paidAt: isPaid && !existingPay.paidAt ? /* @__PURE__ */ new Date() : existingPay.paidAt
7045
+ });
7046
+ } else {
7047
+ const orderRow = await repo.findOne({
7048
+ where: {
7049
+ id: numericId
7050
+ }
7051
+ });
7052
+ const orderTotal = Number(orderRow?.total ?? 0);
7053
+ const orderCurrency = String(orderRow?.currency ?? "INR");
7054
+ const vId = Number(orderRow?.vendorId ?? 1);
7055
+ const cId = orderRow?.contactId ? Number(orderRow.contactId) : null;
7056
+ await paymentRepo.save(paymentRepo.create({
7057
+ vendorId: vId,
7058
+ contactId: cId,
7059
+ orderId: numericId,
7060
+ status: payStatus,
7061
+ amount: orderTotal,
7062
+ currency: orderCurrency,
7063
+ paidAt: isPaid ? /* @__PURE__ */ new Date() : null,
7064
+ method: "manual"
7065
+ }));
7066
+ }
7067
+ }
7068
+ } catch (payErr) {
7069
+ console.error("[crud] failed to update/create payment on order update", payErr);
7070
+ }
7071
+ }
6729
7072
  if (resource === "orders" && rawBody && entityMap["order_addresses"]) {
6730
7073
  const addressRawScalar = String(rawBody["contact.address"] ?? "").trim();
6731
7074
  if (addressRawScalar) {
@@ -6764,17 +7107,105 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6764
7107
  }
6765
7108
  let updated = resource === "orders" ? await repo.findOne({
6766
7109
  where: {
6767
- id: numericId,
6768
- deleted: false
7110
+ id: numericId
6769
7111
  },
6770
7112
  relations: [
6771
- "items"
7113
+ "contact",
7114
+ "billingAddress",
7115
+ "shippingAddress",
7116
+ "items",
7117
+ "items.product",
7118
+ "items.product.collection",
7119
+ "payments"
6772
7120
  ]
6773
7121
  }) : await repo.findOne({
6774
7122
  where: {
6775
7123
  id: numericId
6776
7124
  }
6777
7125
  });
7126
+ if (resource === "orders" && updated) {
7127
+ const ord = updated;
7128
+ const statusUpdated = Boolean(updatePayload.status);
7129
+ const paymentUpdated = Boolean(rawBody && typeof rawBody === "object" && rawBody.paymentStatus != null);
7130
+ if (statusUpdated || paymentUpdated) {
7131
+ const newStatus = updatePayload.status ? String(updatePayload.status).toLowerCase() : String(ord.status || "pending").toLowerCase();
7132
+ const payments = Array.isArray(ord.payments) ? ord.payments : [];
7133
+ const bodyPayStatus = rawBody && typeof rawBody === "object" && rawBody.paymentStatus != null ? String(rawBody.paymentStatus).toLowerCase() : null;
7134
+ const curPayStatus = bodyPayStatus || String(payments[0]?.status || "unpaid").toLowerCase();
7135
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
7136
+ if (newStatus === "pending") {
7137
+ if (curPayStatus === "failed") {
7138
+ fireOrderNotificationTrigger("payment_failed", ord.id, {
7139
+ dataSource,
7140
+ entityMap
7141
+ });
7142
+ } else {
7143
+ fireOrderNotificationTrigger("order_pending", ord.id, {
7144
+ dataSource,
7145
+ entityMap
7146
+ });
7147
+ }
7148
+ } else if (newStatus === "confirmed") {
7149
+ fireOrderNotificationTrigger("order_placed", ord.id, {
7150
+ dataSource,
7151
+ entityMap
7152
+ });
7153
+ if (curPayStatus === "paid" || curPayStatus === "captured") {
7154
+ fireOrderNotificationTrigger("payment_success", ord.id, {
7155
+ dataSource,
7156
+ entityMap
7157
+ });
7158
+ } else if (curPayStatus === "failed") {
7159
+ fireOrderNotificationTrigger("payment_failed", ord.id, {
7160
+ dataSource,
7161
+ entityMap
7162
+ });
7163
+ }
7164
+ } else if (newStatus === "processing") {
7165
+ fireOrderNotificationTrigger("order_processing", ord.id, {
7166
+ dataSource,
7167
+ entityMap
7168
+ });
7169
+ if (curPayStatus === "failed") {
7170
+ fireOrderNotificationTrigger("payment_failed", ord.id, {
7171
+ dataSource,
7172
+ entityMap
7173
+ });
7174
+ }
7175
+ } else if (newStatus === "completed") {
7176
+ fireOrderNotificationTrigger("order_completed", ord.id, {
7177
+ dataSource,
7178
+ entityMap
7179
+ });
7180
+ if (curPayStatus === "failed") {
7181
+ fireOrderNotificationTrigger("payment_failed", ord.id, {
7182
+ dataSource,
7183
+ entityMap
7184
+ });
7185
+ }
7186
+ } else if (newStatus === "cancelled") {
7187
+ if (curPayStatus === "failed") {
7188
+ fireOrderNotificationTrigger("payment_failed", ord.id, {
7189
+ dataSource,
7190
+ entityMap
7191
+ });
7192
+ } else {
7193
+ fireOrderNotificationTrigger("order_cancelled", ord.id, {
7194
+ dataSource,
7195
+ entityMap
7196
+ });
7197
+ if (curPayStatus === "paid" || curPayStatus === "refunded") {
7198
+ fireOrderNotificationTrigger("payment_refund_initiated", ord.id, {
7199
+ dataSource,
7200
+ entityMap
7201
+ });
7202
+ }
7203
+ }
7204
+ }
7205
+ }).catch(() => {
7206
+ });
7207
+ }
7208
+ }
6778
7209
  if (resource === "orders" && orderInvPrev && updated) {
6779
7210
  const invErr = await chunkHY3AXLOI_cjs.reconcileOrderInventoryBetweenSnapshots(dataSource, entityMap, orderInvPrev, chunkHY3AXLOI_cjs.orderInventorySnapshotFromRow(updated));
6780
7211
  if (invErr) return json({
@@ -9820,7 +10251,7 @@ function createFormSubmissionHandler(config) {
9820
10251
  label: f.label && String(f.label).trim() || `Field ${f.id}`,
9821
10252
  value: formatSubmissionFieldValue(data[String(f.id)])
9822
10253
  }));
9823
- await chunkV25RDUOU_cjs.queueEmail(cms, {
10254
+ await chunkMXABMVF7_cjs.queueEmail(cms, {
9824
10255
  to,
9825
10256
  templateName: "formSubmission",
9826
10257
  ctx: {
@@ -9874,7 +10305,7 @@ function createUsersApiHandlers(config) {
9874
10305
  try {
9875
10306
  const cms = await getCms();
9876
10307
  const companyDetails = getCompanyDetails ? await getCompanyDetails() : {};
9877
- await chunkV25RDUOU_cjs.queueEmail(cms, {
10308
+ await chunkMXABMVF7_cjs.queueEmail(cms, {
9878
10309
  to: toEmail,
9879
10310
  templateName: "invite",
9880
10311
  ctx: {
@@ -11147,7 +11578,7 @@ function createChatHandlers(config) {
11147
11578
  const notifyEmailAgent = await findLlmAgentByScope(dataSource, entityMap, LLM_AGENT_SCOPE_EMAIL_INTENT_CHATBOT, {
11148
11579
  enabledOnly: false
11149
11580
  });
11150
- const emailTool = chunkYSYX4GUD_cjs.resolveChatEmailToolSettings(llmSettings, {
11581
+ const emailTool = chunkEWXG4E74_cjs.resolveChatEmailToolSettings(llmSettings, {
11151
11582
  chatbotValidationRules: agentRow?.validationRules ?? null,
11152
11583
  notifyAgent: notifyEmailAgent ? {
11153
11584
  systemInstruction: notifyEmailAgent.systemInstruction,
@@ -11157,7 +11588,7 @@ function createChatHandlers(config) {
11157
11588
  const emailPlugin2 = cms.getPlugin("email");
11158
11589
  const convLeadSent = conv.leadEmailSentAt;
11159
11590
  const chatAgentFn = llm.chatAgent?.bind(llm);
11160
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline check", {
11591
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline check", {
11161
11592
  conversationId,
11162
11593
  enabled: emailTool.enabled,
11163
11594
  intentCount: emailTool.intents.length,
@@ -11171,27 +11602,27 @@ function createChatHandlers(config) {
11171
11602
  mergedPromptIncludesNotify: Boolean(notifyEmailAgent?.systemInstruction?.trim())
11172
11603
  });
11173
11604
  if (!emailTool.enabled) {
11174
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11605
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11175
11606
  conversationId,
11176
11607
  reason: "email_tool_disabled"
11177
11608
  });
11178
11609
  } else if (emailTool.intents.length === 0) {
11179
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11610
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11180
11611
  conversationId,
11181
11612
  reason: "no_intents_configured"
11182
11613
  });
11183
11614
  } else if (!emailPlugin2) {
11184
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11615
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11185
11616
  conversationId,
11186
11617
  reason: "email_plugin_missing"
11187
11618
  });
11188
11619
  } else if (!chatAgentFn) {
11189
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11620
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11190
11621
  conversationId,
11191
11622
  reason: "llm_chat_agent_unavailable"
11192
11623
  });
11193
11624
  } else if (convLeadSent) {
11194
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11625
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11195
11626
  conversationId,
11196
11627
  reason: "lead_email_already_sent",
11197
11628
  leadEmailSentAt: convLeadSent
@@ -11204,7 +11635,7 @@ function createChatHandlers(config) {
11204
11635
  }
11205
11636
  });
11206
11637
  if (!contactRow) {
11207
- console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11638
+ console.warn(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11208
11639
  conversationId,
11209
11640
  reason: "contact_not_found",
11210
11641
  contactId
@@ -11212,7 +11643,7 @@ function createChatHandlers(config) {
11212
11643
  } else {
11213
11644
  const c = contactRow;
11214
11645
  try {
11215
- const intent = await chunkYSYX4GUD_cjs.detectChatLeadIntent({
11646
+ const intent = await chunkEWXG4E74_cjs.detectChatLeadIntent({
11216
11647
  chatAgent: chatAgentFn
11217
11648
  }, {
11218
11649
  settings: emailTool,
@@ -11226,15 +11657,15 @@ function createChatHandlers(config) {
11226
11657
  model: agentRow?.model?.trim() || notifyEmailAgent?.model?.trim() || void 0
11227
11658
  });
11228
11659
  if (!intent.intent || !intent.emailTo) {
11229
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "no email sent", {
11660
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "no email sent", {
11230
11661
  conversationId,
11231
11662
  reason: intent.intent ? "missing_email_to" : "no_intent_match",
11232
11663
  intentLabel: intent.intentLabel,
11233
11664
  classifierReason: intent.reason
11234
11665
  });
11235
11666
  } else {
11236
- const intentRecipients = chunkYSYX4GUD_cjs.parseIntentRecipientEmails(intent.emailTo);
11237
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "intent matched \u2014 sending", {
11667
+ const intentRecipients = chunkEWXG4E74_cjs.parseIntentRecipientEmails(intent.emailTo);
11668
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "intent matched \u2014 sending", {
11238
11669
  conversationId,
11239
11670
  intent: intent.intent,
11240
11671
  emailTo: intent.emailTo,
@@ -11243,8 +11674,8 @@ function createChatHandlers(config) {
11243
11674
  });
11244
11675
  const emailSettings = await loadSettingsGroupMap(dataSource, entityMap, "email");
11245
11676
  const brandingSettings = await loadSettingsGroupMap(dataSource, entityMap, "branding");
11246
- const companyDetails = chunkBXYZDMTZ_cjs.mergeEmailLayoutCompanyDetails(brandingSettings, emailSettings);
11247
- const leadResult = await chunkYSYX4GUD_cjs.sendChatLeadEmail(cms, emailSettings, brandingSettings, {
11677
+ const companyDetails = chunkJLDHK2QE_cjs.mergeEmailLayoutCompanyDetails(brandingSettings, emailSettings);
11678
+ const leadResult = await chunkEWXG4E74_cjs.sendChatLeadEmail(cms, emailSettings, brandingSettings, {
11248
11679
  contactName: String(c.name ?? "").trim() || "Visitor",
11249
11680
  contactEmail: String(c.email ?? "").trim(),
11250
11681
  contactPhone: c.phone ?? null,
@@ -11252,7 +11683,7 @@ function createChatHandlers(config) {
11252
11683
  latestMessage: message,
11253
11684
  intentCode: intent.intent,
11254
11685
  intentReason: intent.intentLabel || intent.reason,
11255
- transcript: chunkYSYX4GUD_cjs.buildTranscriptForLeadEmail(history, message),
11686
+ transcript: chunkEWXG4E74_cjs.buildTranscriptForLeadEmail(history, message),
11256
11687
  companyDetails,
11257
11688
  recipients: intentRecipients.length > 0 ? intentRecipients : void 0
11258
11689
  });
@@ -11260,13 +11691,13 @@ function createChatHandlers(config) {
11260
11691
  await convRepo().update(conversationId, {
11261
11692
  leadEmailSentAt: /* @__PURE__ */ new Date()
11262
11693
  });
11263
- console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "lead email recorded", {
11694
+ console.info(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "lead email recorded", {
11264
11695
  conversationId,
11265
11696
  sent: true,
11266
11697
  recipients: leadResult.recipients
11267
11698
  });
11268
11699
  } else {
11269
- console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "lead email not sent", {
11700
+ console.warn(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "lead email not sent", {
11270
11701
  conversationId,
11271
11702
  sent: false,
11272
11703
  error: leadResult.error ?? "unknown",
@@ -11275,7 +11706,7 @@ function createChatHandlers(config) {
11275
11706
  }
11276
11707
  }
11277
11708
  } catch (intentErr) {
11278
- console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline error", {
11709
+ console.warn(chunkEWXG4E74_cjs.CHAT_EMAIL_LOG, "pipeline error", {
11279
11710
  conversationId,
11280
11711
  error: intentErr instanceof Error ? intentErr.message : String(intentErr)
11281
11712
  });
@@ -11292,7 +11723,7 @@ function createChatHandlers(config) {
11292
11723
  });
11293
11724
  if (agentRow && llm.chatAgent) {
11294
11725
  const fromAgent = llmAgentToChatAgentOptions(agentRow);
11295
- const systemPrompt = chunkYSYX4GUD_cjs.buildChatbotSystemPromptWithEmailTool(fromAgent.systemPrompt, parsedValidation.guardrailsForPrompt, emailTool);
11726
+ const systemPrompt = chunkEWXG4E74_cjs.buildChatbotSystemPromptWithEmailTool(fromAgent.systemPrompt, parsedValidation.guardrailsForPrompt, emailTool);
11296
11727
  const res = await llm.chatAgent({
11297
11728
  ...fromAgent,
11298
11729
  systemPrompt: systemPrompt || void 0,
@@ -11313,7 +11744,7 @@ ${contextParts.join("\n\n")}` : "";
11313
11744
  agentRow.systemInstruction?.trim(),
11314
11745
  ragSystem
11315
11746
  ].filter(Boolean).join("\n\n");
11316
- systemContent = chunkYSYX4GUD_cjs.buildChatbotSystemPromptWithEmailTool(mergedBase || defaultSystem, parsedValidation.guardrailsForPrompt, emailTool) || defaultSystem;
11747
+ systemContent = chunkEWXG4E74_cjs.buildChatbotSystemPromptWithEmailTool(mergedBase || defaultSystem, parsedValidation.guardrailsForPrompt, emailTool) || defaultSystem;
11317
11748
  } else {
11318
11749
  systemContent = ragSystem || defaultSystem;
11319
11750
  }
@@ -12568,7 +12999,7 @@ function createDeviceTokensHandlers(config) {
12568
12999
  const title = body.title?.trim() || "Test Push Notification";
12569
13000
  const msgBody = body.body?.trim() || "Firebase Push Notification setup is working!";
12570
13001
  if (!token || token === "validate" || token === "validate_only") {
12571
- const valRes = await chunkYSYX4GUD_cjs.validateFcmCredentials(dataSource, entityMap);
13002
+ const valRes = await chunkEWXG4E74_cjs.validateFcmCredentials(dataSource, entityMap);
12572
13003
  if (!valRes.success) {
12573
13004
  return json({
12574
13005
  success: false,
@@ -12585,7 +13016,7 @@ function createDeviceTokensHandlers(config) {
12585
13016
  clientEmail: valRes.clientEmail
12586
13017
  });
12587
13018
  }
12588
- const res = await chunkYSYX4GUD_cjs.sendFcmPushNotification(dataSource, entityMap, {
13019
+ const res = await chunkEWXG4E74_cjs.sendFcmPushNotification(dataSource, entityMap, {
12589
13020
  token,
12590
13021
  title,
12591
13022
  body: msgBody,
@@ -13579,8 +14010,8 @@ async function sendVendorOnboardEmails(input, deps) {
13579
14010
  getSuperAdminEmails(deps),
13580
14011
  getVendorEmails(deps)
13581
14012
  ]);
13582
- const companyDetails = chunkBXYZDMTZ_cjs.mergeEmailLayoutCompanyDetails(branding, emailSettings);
13583
- const configuredNotify = chunkYSYX4GUD_cjs.parseEmailRecipientsFromConfig(emailSettings.salesTeamEmails ?? emailSettings.salesTeamEmail);
14013
+ const companyDetails = chunkJLDHK2QE_cjs.mergeEmailLayoutCompanyDetails(branding, emailSettings);
14014
+ const configuredNotify = chunkEWXG4E74_cjs.parseEmailRecipientsFromConfig(emailSettings.salesTeamEmails ?? emailSettings.salesTeamEmail);
13584
14015
  const ownerEmail = input.ownerEmail?.trim() || "";
13585
14016
  const ownerEmailLower = ownerEmail.toLowerCase();
13586
14017
  const sendToOwner = input.sendToOwner !== false;
@@ -13590,7 +14021,7 @@ async function sendVendorOnboardEmails(input, deps) {
13590
14021
  ];
13591
14022
  const notifyEmails = Array.from(new Set(combined.map((e) => e.trim().toLowerCase()).filter((e) => e && e !== ownerEmailLower && !vendorEmailSet.has(e))));
13592
14023
  const cms = await deps.getCms();
13593
- await chunkV25RDUOU_cjs.queueVendorOnboardEmails(cms, {
14024
+ await chunkMXABMVF7_cjs.queueVendorOnboardEmails(cms, {
13594
14025
  vendorName: input.vendorName,
13595
14026
  vendorSlug: input.vendorSlug,
13596
14027
  ownerName: input.ownerName,
@@ -18256,6 +18687,9 @@ exports.Order = class Order {
18256
18687
  customerContact;
18257
18688
  billingAddress;
18258
18689
  shippingAddress;
18690
+ assignedUserId;
18691
+ assignedAt;
18692
+ assignedUser;
18259
18693
  items;
18260
18694
  payments;
18261
18695
  };
@@ -18468,6 +18902,29 @@ _ts_decorate21([
18468
18902
  }),
18469
18903
  _ts_metadata21("design:type", Object)
18470
18904
  ], exports.Order.prototype, "shippingAddress", void 0);
18905
+ _ts_decorate21([
18906
+ typeorm.Column("int", {
18907
+ nullable: true
18908
+ }),
18909
+ _ts_metadata21("design:type", Object)
18910
+ ], exports.Order.prototype, "assignedUserId", void 0);
18911
+ _ts_decorate21([
18912
+ typeorm.Column({
18913
+ type: "timestamp",
18914
+ nullable: true
18915
+ }),
18916
+ _ts_metadata21("design:type", Object)
18917
+ ], exports.Order.prototype, "assignedAt", void 0);
18918
+ _ts_decorate21([
18919
+ typeorm.ManyToOne(() => exports.User, {
18920
+ nullable: true,
18921
+ onDelete: "SET NULL"
18922
+ }),
18923
+ typeorm.JoinColumn({
18924
+ name: "assignedUserId"
18925
+ }),
18926
+ _ts_metadata21("design:type", Object)
18927
+ ], exports.Order.prototype, "assignedUser", void 0);
18471
18928
  _ts_decorate21([
18472
18929
  typeorm.OneToMany("OrderItem", "order"),
18473
18930
  _ts_metadata21("design:type", Array)
@@ -24499,6 +24956,7 @@ var NotificationChannel = /* @__PURE__ */ (function(NotificationChannel2) {
24499
24956
  NotificationChannel2["WHATSAPP"] = "whatsapp";
24500
24957
  NotificationChannel2["EMAIL"] = "email";
24501
24958
  NotificationChannel2["MOBILE"] = "mobile";
24959
+ NotificationChannel2["SMS"] = "sms";
24502
24960
  return NotificationChannel2;
24503
24961
  })({});
24504
24962
  var NotificationAudienceType = /* @__PURE__ */ (function(NotificationAudienceType2) {
@@ -28153,21 +28611,37 @@ function whatsappPlugin(config = {}) {
28153
28611
  async init(context) {
28154
28612
  const env = context.config;
28155
28613
  const { getWhatsAppSettings, getMessageTemplateRow, ...staticRest } = config;
28614
+ let settingsLoader = getWhatsAppSettings;
28615
+ if (!settingsLoader && context.dataSource) {
28616
+ settingsLoader = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async () => {
28617
+ try {
28618
+ const ds = context.dataSource;
28619
+ const repo = ds.getRepository("configs");
28620
+ const rows = await repo.find({
28621
+ where: {
28622
+ settings: "whatsapp",
28623
+ deleted: false
28624
+ }
28625
+ });
28626
+ return Object.fromEntries(rows.map((r) => [
28627
+ r.key,
28628
+ r.value
28629
+ ]));
28630
+ } catch {
28631
+ return {};
28632
+ }
28633
+ }, "settingsLoader");
28634
+ }
28156
28635
  let db = {};
28157
28636
  try {
28158
- db = await getWhatsAppSettings?.() ?? {};
28637
+ db = await settingsLoader?.() ?? {};
28159
28638
  } catch {
28160
28639
  }
28161
- if (!chunkYSYX4GUD_cjs.isWhatsAppPluginEnabled(db)) {
28640
+ if (!chunkEWXG4E74_cjs.isWhatsAppPluginEnabled(db)) {
28162
28641
  context.logger.warn("WhatsApp plugin skipped: disabled in Plugins \u2192 WhatsApp");
28163
28642
  return null;
28164
28643
  }
28165
- const merged = chunkYSYX4GUD_cjs.mergeWhatsAppConfigLayers(env, db, staticRest);
28166
- if (!getWhatsAppSettings && !chunkYSYX4GUD_cjs.whatsAppConfigured(merged)) {
28167
- context.logger.warn("WhatsApp plugin skipped: set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID, or pass getWhatsAppSettings");
28168
- return null;
28169
- }
28170
- const svc = new chunkYSYX4GUD_cjs.WhatsAppService(env, staticRest, getWhatsAppSettings, getMessageTemplateRow);
28644
+ const svc = new chunkEWXG4E74_cjs.WhatsAppService(env, staticRest, settingsLoader, getMessageTemplateRow);
28171
28645
  return {
28172
28646
  send: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((opts) => svc.send(opts), "send")
28173
28647
  };
@@ -28240,11 +28714,11 @@ function createMessageTemplateRowLoader(dataSource, entityMap) {
28240
28714
  }
28241
28715
  chunkUSNT2KNT_cjs.__name(createMessageTemplateRowLoader, "createMessageTemplateRowLoader");
28242
28716
  function registerMessagingQueueProcessors(cms, entityMap) {
28243
- chunkV25RDUOU_cjs.registerEmailQueueProcessor(cms, {
28717
+ chunkMXABMVF7_cjs.registerEmailQueueProcessor(cms, {
28244
28718
  getDataSource: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async () => cms.dataSource, "getDataSource"),
28245
28719
  entityMap
28246
28720
  });
28247
- chunkYSYX4GUD_cjs.registerWhatsAppQueueProcessor(cms);
28721
+ chunkH3IVLIPR_cjs.registerWhatsAppQueueProcessor(cms);
28248
28722
  }
28249
28723
  chunkUSNT2KNT_cjs.__name(registerMessagingQueueProcessors, "registerMessagingQueueProcessors");
28250
28724
  async function ensureMessagingPluginsOnCms(base, options) {
@@ -28273,7 +28747,7 @@ async function ensureMessagingPluginsOnCms(base, options) {
28273
28747
  }
28274
28748
  if (!cms.getPlugin("email")) {
28275
28749
  try {
28276
- const instance = await chunkYSYX4GUD_cjs.emailPlugin({
28750
+ const instance = await chunkEWXG4E74_cjs.emailPlugin({
28277
28751
  type: "SMTP",
28278
28752
  from: config.SMTP_FROM ?? "no-reply@localhost",
28279
28753
  to: config.SMTP_TO ?? ""
@@ -28314,7 +28788,7 @@ function messagingPlugins(options) {
28314
28788
  const config = options.config ?? (typeof process !== "undefined" ? process.env : {});
28315
28789
  return [
28316
28790
  queuePlugin(),
28317
- chunkYSYX4GUD_cjs.emailPlugin({
28791
+ chunkEWXG4E74_cjs.emailPlugin({
28318
28792
  type: "SMTP",
28319
28793
  from: config.SMTP_FROM ?? "no-reply@localhost",
28320
28794
  to: config.SMTP_TO ?? ""
@@ -28448,7 +28922,7 @@ function createCmsApiHandler(config) {
28448
28922
  } : void 0;
28449
28923
  const entityMap = withLlmKnowledgeEntityFallbacks(rawEntityMap);
28450
28924
  if (getCms) {
28451
- chunkYSYX4GUD_cjs.initWhatsappTriggerDispatcher({
28925
+ chunkEWXG4E74_cjs.initWhatsappTriggerDispatcher({
28452
28926
  dataSource,
28453
28927
  entityMap,
28454
28928
  getCms
@@ -28541,7 +29015,7 @@ function createCmsApiHandler(config) {
28541
29015
  companyDetails
28542
29016
  };
28543
29017
  if (queue) {
28544
- const { queueEmail: queueEmail2 } = await import('./email-queue-6NJY6HNM.cjs');
29018
+ const { queueEmail: queueEmail2 } = await import('./email-queue-VTYL2KFA.cjs');
28545
29019
  await queueEmail2(cms, {
28546
29020
  to: opts.to,
28547
29021
  templateName: "passwordReset",
@@ -29841,7 +30315,7 @@ function createCmsApiHandler(config) {
29841
30315
  const pe = await requireEntityPermissionEffective(req, "orders", "read");
29842
30316
  if (pe) return pe;
29843
30317
  const cms = await getCms();
29844
- const { streamOrderInvoicePdf: streamOrderInvoicePdf2 } = await import('./erp-order-invoice-EYYNR526.cjs');
30318
+ const { streamOrderInvoicePdf: streamOrderInvoicePdf2 } = await import('./erp-order-invoice-KJYJNWMG.cjs');
29845
30319
  const oid = Number(path2[1]);
29846
30320
  if (!Number.isFinite(oid)) return config.json({
29847
30321
  error: "Invalid id"
@@ -29990,6 +30464,11 @@ function createCmsApiHandler(config) {
29990
30464
  });
29991
30465
  }
29992
30466
  }
30467
+ if (path2[0] === "sms-notification-templates" && path2.length === 1 && m === "GET") {
30468
+ const { createSmsNotificationTemplatesHandlers } = await import('./sms-notification-templates-handlers-YSB3L2PK.cjs');
30469
+ const handlers = createSmsNotificationTemplatesHandlers(dataSource, entityMap);
30470
+ return handlers.GET(req);
30471
+ }
29993
30472
  if (path2[0] === "orders" && path2[1] === "calculate" && path2.length === 2 && m === "POST") {
29994
30473
  const a = await config.requireAuth(req);
29995
30474
  if (a) return a;
@@ -30218,7 +30697,7 @@ function createCmsApiHandler(config) {
30218
30697
  status: 400
30219
30698
  });
30220
30699
  }
30221
- const { resendOrderNotification } = await import('./order-notification-dispatcher-KJVGLK5E.cjs');
30700
+ const { resendOrderNotification } = await import('./order-notification-dispatcher-5TUFCDU7.cjs');
30222
30701
  const result = await resendOrderNotification(triggerKey, orderId, {
30223
30702
  dataSource,
30224
30703
  entityMap,
@@ -30317,25 +30796,20 @@ function createCmsApiHandler(config) {
30317
30796
  status: "cancelled"
30318
30797
  });
30319
30798
  const fireOrderCancelledNotification = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((refundAmount) => {
30320
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
30799
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
30321
30800
  fireOrderNotificationTrigger("order_cancelled", orderId, {
30322
30801
  dataSource,
30323
30802
  entityMap
30324
30803
  }, refundAmount != null && refundAmount > 0 ? {
30325
30804
  refundAmount
30326
30805
  } : void 0);
30327
- if (paymentStatus === "paid" || paymentStatus === "captured") {
30806
+ if (paymentStatus === "paid" || paymentStatus === "captured" || paymentStatus === "refunded") {
30328
30807
  fireOrderNotificationTrigger("payment_refund_initiated", orderId, {
30329
30808
  dataSource,
30330
30809
  entityMap
30331
30810
  }, refundAmount != null && refundAmount > 0 ? {
30332
30811
  refundAmount
30333
30812
  } : void 0);
30334
- } else {
30335
- fireOrderNotificationTrigger("payment_failed", orderId, {
30336
- dataSource,
30337
- entityMap
30338
- });
30339
30813
  }
30340
30814
  });
30341
30815
  }, "fireOrderCancelledNotification");
@@ -30556,6 +31030,66 @@ function createCmsApiHandler(config) {
30556
31030
  finalRefund: 0
30557
31031
  });
30558
31032
  }
31033
+ if (path2[0] === "orders" && path2.length === 4 && path2[2] === "completion-otp" && path2[3] === "channels" && m === "GET" && getCms) {
31034
+ const a = await config.requireAuth(req);
31035
+ if (a) return a;
31036
+ const pe = await requireEntityPermissionEffective(req, "orders", "read");
31037
+ if (pe) return pe;
31038
+ const orderId = Number(path2[1]);
31039
+ if (!Number.isFinite(orderId)) return config.json({
31040
+ error: "Invalid order ID"
31041
+ }, {
31042
+ status: 400
31043
+ });
31044
+ const { createOrderCompletionOtpHandlers } = await import('./order-completion-otp-handlers-IMMQGHDR.cjs');
31045
+ const handlers = createOrderCompletionOtpHandlers(dataSource, entityMap, getCms);
31046
+ return handlers.getChannels(req, orderId);
31047
+ }
31048
+ if (path2[0] === "orders" && path2.length === 4 && path2[2] === "completion-otp" && path2[3] === "send" && m === "POST" && getCms) {
31049
+ const a = await config.requireAuth(req);
31050
+ if (a) return a;
31051
+ const pe = await requireEntityPermissionEffective(req, "orders", "update");
31052
+ if (pe) return pe;
31053
+ const orderId = Number(path2[1]);
31054
+ if (!Number.isFinite(orderId)) return config.json({
31055
+ error: "Invalid order ID"
31056
+ }, {
31057
+ status: 400
31058
+ });
31059
+ const { createOrderCompletionOtpHandlers } = await import('./order-completion-otp-handlers-IMMQGHDR.cjs');
31060
+ const handlers = createOrderCompletionOtpHandlers(dataSource, entityMap, getCms);
31061
+ return handlers.sendOtp(req, orderId);
31062
+ }
31063
+ if (path2[0] === "orders" && path2.length === 4 && path2[2] === "completion-otp" && path2[3] === "verify" && m === "POST" && getCms) {
31064
+ const a = await config.requireAuth(req);
31065
+ if (a) return a;
31066
+ const pe = await requireEntityPermissionEffective(req, "orders", "update");
31067
+ if (pe) return pe;
31068
+ const orderId = Number(path2[1]);
31069
+ if (!Number.isFinite(orderId)) return config.json({
31070
+ error: "Invalid order ID"
31071
+ }, {
31072
+ status: 400
31073
+ });
31074
+ const { createOrderCompletionOtpHandlers } = await import('./order-completion-otp-handlers-IMMQGHDR.cjs');
31075
+ const handlers = createOrderCompletionOtpHandlers(dataSource, entityMap, getCms);
31076
+ return handlers.verifyOtp(req, orderId);
31077
+ }
31078
+ if (path2[0] === "orders" && path2.length === 3 && path2[2] === "eligible-assignees" && m === "GET") {
31079
+ const a = await config.requireAuth(req);
31080
+ if (a) return a;
31081
+ const pe = await requireEntityPermissionEffective(req, "orders", "read");
31082
+ if (pe) return pe;
31083
+ const orderId = Number(path2[1]);
31084
+ if (!Number.isFinite(orderId)) return config.json({
31085
+ error: "Invalid order ID"
31086
+ }, {
31087
+ status: 400
31088
+ });
31089
+ const { createOrderAssigneesHandlers } = await import('./order-assignees-handlers-NPKD64P6.cjs');
31090
+ const handlers = createOrderAssigneesHandlers(dataSource, entityMap, getHydratedSessionUser);
31091
+ return handlers.listEligibleAssignees(req, orderId);
31092
+ }
30559
31093
  if (path2[0] === "refund-policies") {
30560
31094
  if (path2.length === 1) {
30561
31095
  if (m === "GET") {
@@ -30985,12 +31519,12 @@ async function refreshOrderFromErp(cms, dataSource, entityMap, submission, order
30985
31519
  const r1 = await submission.postErpReadAction("get-order-status", {
30986
31520
  platformOrderId: refId
30987
31521
  });
30988
- const d1 = r1.ok ? chunkBXYZDMTZ_cjs.unwrapErpReadData(r1.json) : null;
31522
+ const d1 = r1.ok ? chunk7L556RGL_cjs.unwrapErpReadData(r1.json) : null;
30989
31523
  if (d1) {
30990
31524
  const mapped = mapErpSaleStatusToOrderStatus(typeof d1.status === "string" ? d1.status : typeof d1.orderStatus === "string" ? d1.orderStatus : typeof d1.state === "string" ? d1.state : void 0);
30991
31525
  if (mapped) newStatus = mapped;
30992
- fulfillment = chunkBXYZDMTZ_cjs.mapErpPayloadToFulfillment(d1);
30993
- const refs = chunkBXYZDMTZ_cjs.extractChildOrderRefsFromSalePayload(d1);
31526
+ fulfillment = chunk7L556RGL_cjs.mapErpPayloadToFulfillment(d1);
31527
+ const refs = chunk7L556RGL_cjs.extractChildOrderRefsFromSalePayload(d1);
30994
31528
  if (refs.length) {
30995
31529
  await ensureChildOrdersFromRefs(orderRepo, order, refs, order.contactId, String(order.currency || "INR"));
30996
31530
  }
@@ -30998,16 +31532,16 @@ async function refreshOrderFromErp(cms, dataSource, entityMap, submission, order
30998
31532
  const r2 = await submission.postErpReadAction("get-fulfillment-status", {
30999
31533
  platformOrderId: refId
31000
31534
  });
31001
- const d2 = r2.ok ? chunkBXYZDMTZ_cjs.unwrapErpReadData(r2.json) : null;
31535
+ const d2 = r2.ok ? chunk7L556RGL_cjs.unwrapErpReadData(r2.json) : null;
31002
31536
  if (d2) {
31003
- fulfillment = deepMergeFulfillment(fulfillment, chunkBXYZDMTZ_cjs.mapErpPayloadToFulfillment(d2));
31537
+ fulfillment = deepMergeFulfillment(fulfillment, chunk7L556RGL_cjs.mapErpPayloadToFulfillment(d2));
31004
31538
  }
31005
31539
  const r3 = await submission.postErpReadAction("get-invoice", {
31006
31540
  platformOrderId: refId
31007
31541
  });
31008
- const d3 = r3.ok ? chunkBXYZDMTZ_cjs.unwrapErpReadData(r3.json) : null;
31542
+ const d3 = r3.ok ? chunk7L556RGL_cjs.unwrapErpReadData(r3.json) : null;
31009
31543
  if (d3) {
31010
- invoiceNumber = chunkBXYZDMTZ_cjs.mapErpPayloadToInvoiceNumber(d3);
31544
+ invoiceNumber = chunk7L556RGL_cjs.mapErpPayloadToInvoiceNumber(d3);
31011
31545
  invoiceId = pickInvoiceId(d3);
31012
31546
  }
31013
31547
  const oid = order.id;
@@ -31043,10 +31577,10 @@ async function refreshOrderFromErp(cms, dataSource, entityMap, submission, order
31043
31577
  const r = await submission.postErpReadAction("get-return-status", {
31044
31578
  platformReturnId
31045
31579
  });
31046
- const d = r.ok ? chunkBXYZDMTZ_cjs.unwrapErpReadData(r.json) : null;
31580
+ const d = r.ok ? chunk7L556RGL_cjs.unwrapErpReadData(r.json) : null;
31047
31581
  if (!d) return;
31048
31582
  const mapped = mapErpSaleStatusToOrderStatus(typeof d.status === "string" ? d.status : typeof d.returnStatus === "string" ? d.returnStatus : void 0);
31049
- const fulfillment = chunkBXYZDMTZ_cjs.mapErpPayloadToFulfillment(d);
31583
+ const fulfillment = chunk7L556RGL_cjs.mapErpPayloadToFulfillment(d);
31050
31584
  const patch = {};
31051
31585
  if (fulfillment !== void 0) patch.fulfillment = fulfillment;
31052
31586
  const nextMeta = Object.keys(patch).length ? mergeOrderMetadataPatch(meta, patch) : meta;
@@ -31072,63 +31606,6 @@ async function tryRefreshOrderFromErpForStorefront(cms, dataSource, entityMap, o
31072
31606
  }
31073
31607
  chunkUSNT2KNT_cjs.__name(tryRefreshOrderFromErpForStorefront, "tryRefreshOrderFromErpForStorefront");
31074
31608
 
31075
- // src/plugins/sms/sms-queue.ts
31076
- var SMS_QUEUE_NAME = "sms";
31077
- function registerSmsQueueProcessor(cms) {
31078
- const queue = cms.getPlugin("queue");
31079
- const sms = cms.getPlugin("sms");
31080
- if (!queue || !sms || typeof sms.send !== "function") return;
31081
- queue.registerProcessor(SMS_QUEUE_NAME, async (data) => {
31082
- const payload = data;
31083
- if (!payload.to) return;
31084
- if (payload.templateKey?.trim()) {
31085
- await sms.send({
31086
- to: payload.to,
31087
- templateKey: payload.templateKey.trim(),
31088
- variables: payload.variables,
31089
- otpCode: payload.otpCode
31090
- });
31091
- return;
31092
- }
31093
- if (!payload.body?.trim()) return;
31094
- await sms.send({
31095
- to: payload.to,
31096
- body: payload.body,
31097
- otpCode: payload.otpCode,
31098
- variables: payload.variables
31099
- });
31100
- });
31101
- }
31102
- chunkUSNT2KNT_cjs.__name(registerSmsQueueProcessor, "registerSmsQueueProcessor");
31103
- async function queueSms(cms, payload) {
31104
- const queue = cms.getPlugin("queue");
31105
- const sms = cms.getPlugin("sms");
31106
- if (queue) {
31107
- await queue.add(SMS_QUEUE_NAME, payload);
31108
- return;
31109
- }
31110
- if (sms && typeof sms.send === "function") {
31111
- if (payload.templateKey?.trim()) {
31112
- await sms.send({
31113
- to: payload.to,
31114
- templateKey: payload.templateKey.trim(),
31115
- variables: payload.variables,
31116
- otpCode: payload.otpCode
31117
- });
31118
- return;
31119
- }
31120
- if (payload.body?.trim()) {
31121
- await sms.send({
31122
- to: payload.to,
31123
- body: payload.body,
31124
- otpCode: payload.otpCode,
31125
- variables: payload.variables
31126
- });
31127
- }
31128
- }
31129
- }
31130
- chunkUSNT2KNT_cjs.__name(queueSms, "queueSms");
31131
-
31132
31609
  // src/lib/storefront-product-pricing.ts
31133
31610
  function eventPricingFromRow(row) {
31134
31611
  const defaultCurrency = normalizeCurrencyCode(String(row?.defaultCurrency ?? "INR")) || "INR";
@@ -31197,143 +31674,6 @@ async function buildPricesForSupportedCurrencies(dataSource, entityMap, basePric
31197
31674
  return rows;
31198
31675
  }
31199
31676
  chunkUSNT2KNT_cjs.__name(buildPricesForSupportedCurrencies, "buildPricesForSupportedCurrencies");
31200
- var OTP_TTL_MS = 10 * 60 * 1e3;
31201
- var MAX_SENDS_PER_HOUR = 5;
31202
- var MAX_VERIFY_ATTEMPTS = 8;
31203
- function getPepper(explicit) {
31204
- return (explicit || process.env.OTP_PEPPER || process.env.NEXTAUTH_SECRET || "dev-otp-pepper").trim();
31205
- }
31206
- chunkUSNT2KNT_cjs.__name(getPepper, "getPepper");
31207
- function hashOtpCode(code, purpose, identifier, pepper) {
31208
- return crypto2.createHmac("sha256", getPepper(pepper)).update(`${purpose}|${identifier}|${code}`).digest("hex");
31209
- }
31210
- chunkUSNT2KNT_cjs.__name(hashOtpCode, "hashOtpCode");
31211
- function verifyOtpCodeHash(code, storedHash, purpose, identifier, pepper) {
31212
- const h = hashOtpCode(code, purpose, identifier, pepper);
31213
- try {
31214
- return crypto2.timingSafeEqual(Buffer.from(h, "utf8"), Buffer.from(storedHash, "utf8"));
31215
- } catch {
31216
- return false;
31217
- }
31218
- }
31219
- chunkUSNT2KNT_cjs.__name(verifyOtpCodeHash, "verifyOtpCodeHash");
31220
- function generateNumericOtp(length = 6) {
31221
- const max = 10 ** length;
31222
- return crypto2.randomInt(0, max).toString().padStart(length, "0");
31223
- }
31224
- chunkUSNT2KNT_cjs.__name(generateNumericOtp, "generateNumericOtp");
31225
- function normalizePhoneE164(raw, defaultCountryCode) {
31226
- const t = raw.trim();
31227
- const digitsOnly = t.replace(/\D/g, "");
31228
- if (digitsOnly.length < 10) return null;
31229
- if (t.startsWith("+")) return `+${digitsOnly}`;
31230
- const cc = (defaultCountryCode || process.env.DEFAULT_PHONE_COUNTRY_CODE || "91").replace(/\D/g, "");
31231
- if (digitsOnly.length > 10) return `+${digitsOnly}`;
31232
- return `+${cc}${digitsOnly}`;
31233
- }
31234
- chunkUSNT2KNT_cjs.__name(normalizePhoneE164, "normalizePhoneE164");
31235
- async function countRecentOtpSends(dataSource, entityMap, purpose, identifier, since) {
31236
- const repo = dataSource.getRepository(entityMap.otp_challenges);
31237
- return repo.count({
31238
- where: {
31239
- purpose,
31240
- identifier,
31241
- createdAt: typeorm.MoreThan(since)
31242
- }
31243
- });
31244
- }
31245
- chunkUSNT2KNT_cjs.__name(countRecentOtpSends, "countRecentOtpSends");
31246
- async function createOtpChallenge(dataSource, entityMap, input) {
31247
- const { purpose, channel, identifier, code, pepper } = input;
31248
- const since = new Date(Date.now() - 60 * 60 * 1e3);
31249
- const recent = await countRecentOtpSends(dataSource, entityMap, purpose, identifier, since);
31250
- if (recent >= MAX_SENDS_PER_HOUR) {
31251
- return {
31252
- ok: false,
31253
- error: "Too many codes sent. Try again later.",
31254
- status: 429
31255
- };
31256
- }
31257
- const repo = dataSource.getRepository(entityMap.otp_challenges);
31258
- await repo.delete({
31259
- purpose,
31260
- identifier,
31261
- consumedAt: typeorm.IsNull()
31262
- });
31263
- const expiresAt = new Date(Date.now() + OTP_TTL_MS);
31264
- const codeHash = hashOtpCode(code, purpose, identifier, pepper);
31265
- await repo.save(repo.create({
31266
- purpose,
31267
- channel,
31268
- identifier,
31269
- codeHash,
31270
- expiresAt,
31271
- attempts: 0,
31272
- consumedAt: null
31273
- }));
31274
- return {
31275
- ok: true
31276
- };
31277
- }
31278
- chunkUSNT2KNT_cjs.__name(createOtpChallenge, "createOtpChallenge");
31279
- async function verifyAndConsumeOtpChallenge(dataSource, entityMap, input) {
31280
- const { purpose, identifier, code, pepper } = input;
31281
- const repo = dataSource.getRepository(entityMap.otp_challenges);
31282
- const row = await repo.findOne({
31283
- where: {
31284
- purpose,
31285
- identifier,
31286
- consumedAt: typeorm.IsNull()
31287
- },
31288
- order: {
31289
- id: "DESC"
31290
- }
31291
- });
31292
- if (!row) {
31293
- return {
31294
- ok: false,
31295
- error: "Invalid or expired code",
31296
- status: 400
31297
- };
31298
- }
31299
- const r = row;
31300
- if (new Date(r.expiresAt) < /* @__PURE__ */ new Date()) {
31301
- await repo.delete(row.id);
31302
- return {
31303
- ok: false,
31304
- error: "Invalid or expired code",
31305
- status: 400
31306
- };
31307
- }
31308
- const attempts = r.attempts || 0;
31309
- if (attempts >= MAX_VERIFY_ATTEMPTS) {
31310
- await repo.delete(row.id);
31311
- return {
31312
- ok: false,
31313
- error: "Too many attempts",
31314
- status: 400
31315
- };
31316
- }
31317
- const valid = verifyOtpCodeHash(code, r.codeHash, purpose, identifier, pepper);
31318
- if (!valid) {
31319
- await repo.update(row.id, {
31320
- attempts: attempts + 1
31321
- });
31322
- return {
31323
- ok: false,
31324
- error: "Invalid or expired code",
31325
- status: 400
31326
- };
31327
- }
31328
- await repo.update(row.id, {
31329
- consumedAt: /* @__PURE__ */ new Date(),
31330
- attempts: attempts + 1
31331
- });
31332
- return {
31333
- ok: true
31334
- };
31335
- }
31336
- chunkUSNT2KNT_cjs.__name(verifyAndConsumeOtpChallenge, "verifyAndConsumeOtpChallenge");
31337
31677
 
31338
31678
  // src/api/storefront-handlers.ts
31339
31679
  var GUEST_COOKIE = "guest_id";
@@ -31363,7 +31703,7 @@ function createStorefrontApiHandler(config) {
31363
31703
  const otpPepper = config.otpPepper;
31364
31704
  const defaultPhoneCc = config.defaultPhoneCountryCode;
31365
31705
  function fireOrderPlacedNotification(orderId, isPaid) {
31366
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
31706
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
31367
31707
  fireOrderNotificationTrigger("order_placed", orderId, {
31368
31708
  dataSource,
31369
31709
  entityMap
@@ -31434,9 +31774,21 @@ function createStorefrontApiHandler(config) {
31434
31774
  },
31435
31775
  select: [
31436
31776
  "id",
31437
- "vendorId"
31777
+ "vendorId",
31778
+ "eventId"
31438
31779
  ]
31439
31780
  });
31781
+ const comboEventId = Number(combo?.eventId);
31782
+ if (Number.isInteger(comboEventId) && comboEventId > 0 && entityMap.events) {
31783
+ const evRows = await dataSource.query(`SELECT "vendorId" FROM events WHERE id = $1 AND deleted = false LIMIT 1`, [
31784
+ comboEventId
31785
+ ]);
31786
+ const evVid = Number(evRows[0]?.vendorId);
31787
+ if (Number.isInteger(evVid) && evVid > 0) {
31788
+ comboVendorCache.set(comboId, evVid);
31789
+ return evVid;
31790
+ }
31791
+ }
31440
31792
  const vid = Number(combo?.vendorId);
31441
31793
  if (Number.isInteger(vid) && vid > 0) {
31442
31794
  comboVendorCache.set(comboId, vid);
@@ -31456,9 +31808,30 @@ function createStorefrontApiHandler(config) {
31456
31808
  }
31457
31809
  const p = it.product;
31458
31810
  if (!p || p.deleted || p.status !== "available") continue;
31459
- const vid = Number(p.vendorId);
31811
+ let vid = Number(p.vendorId);
31812
+ if (!Number.isInteger(vid) || vid <= 0) {
31813
+ const prodId = Number(p.id);
31814
+ if (Number.isInteger(prodId) && prodId > 0 && entityMap.event_products) {
31815
+ const epRows = await dataSource.query(`SELECT e."vendorId" FROM event_products ep
31816
+ JOIN events e ON e.id = ep."eventId"
31817
+ WHERE ep."productId" = $1 AND e.deleted = false LIMIT 1`, [
31818
+ prodId
31819
+ ]);
31820
+ const evVid = Number(epRows[0]?.vendorId);
31821
+ if (Number.isInteger(evVid) && evVid > 0) vid = evVid;
31822
+ }
31823
+ }
31460
31824
  if (Number.isInteger(vid) && vid > 0) vendorIds.add(vid);
31461
31825
  }
31826
+ if (vendorIds.size > 1) {
31827
+ const nonDefault = [
31828
+ ...vendorIds
31829
+ ].filter((id) => id !== 1);
31830
+ if (nonDefault.length === 1) {
31831
+ vendorIds.clear();
31832
+ vendorIds.add(nonDefault[0]);
31833
+ }
31834
+ }
31462
31835
  if (vendorIds.size === 0) return {
31463
31836
  error: "Cart has no valid products",
31464
31837
  status: 400
@@ -32919,7 +33292,7 @@ function createStorefrontApiHandler(config) {
32919
33292
  status: 403
32920
33293
  });
32921
33294
  }
32922
- const p = normalizePhoneE164(phoneIn, defaultPhoneCc);
33295
+ const p = chunkWFMVD567_cjs.normalizePhoneE164(phoneIn, defaultPhoneCc);
32923
33296
  if (!p) return json({
32924
33297
  error: "Invalid phone"
32925
33298
  }, {
@@ -32972,7 +33345,7 @@ function createStorefrontApiHandler(config) {
32972
33345
  }, {
32973
33346
  status: 401
32974
33347
  });
32975
- const p = normalizePhoneE164(phoneIn, defaultPhoneCc);
33348
+ const p = chunkWFMVD567_cjs.normalizePhoneE164(phoneIn, defaultPhoneCc);
32976
33349
  if (!p) return json({
32977
33350
  error: "Valid phone required"
32978
33351
  }, {
@@ -32996,8 +33369,8 @@ function createStorefrontApiHandler(config) {
32996
33369
  });
32997
33370
  }
32998
33371
  }
32999
- const code = generateNumericOtp(6);
33000
- const created = await createOtpChallenge(dataSource, entityMap, {
33372
+ const code = chunkWFMVD567_cjs.generateNumericOtp(6);
33373
+ const created = await chunkWFMVD567_cjs.createOtpChallenge(dataSource, entityMap, {
33001
33374
  purpose,
33002
33375
  channel,
33003
33376
  identifier,
@@ -33023,7 +33396,7 @@ function createStorefrontApiHandler(config) {
33023
33396
  status: 503
33024
33397
  });
33025
33398
  const companyDetails = getCompanyDetails ? await getCompanyDetails() : {};
33026
- await chunkV25RDUOU_cjs.queueEmail(cms, {
33399
+ await chunkMXABMVF7_cjs.queueEmail(cms, {
33027
33400
  to: identifier,
33028
33401
  templateName: "otp",
33029
33402
  ctx: {
@@ -33038,7 +33411,7 @@ function createStorefrontApiHandler(config) {
33038
33411
  status: 503
33039
33412
  });
33040
33413
  const templateKey = purpose === "verify_phone" ? "auth.otp_verify_phone" : "auth.otp_login";
33041
- await queueSms(cms, {
33414
+ await chunkWFMVD567_cjs.queueSms(cms, {
33042
33415
  to: identifier,
33043
33416
  templateKey,
33044
33417
  variables: {
@@ -33071,7 +33444,7 @@ function createStorefrontApiHandler(config) {
33071
33444
  }, {
33072
33445
  status: 400
33073
33446
  });
33074
- const v = await verifyAndConsumeOtpChallenge(dataSource, entityMap, {
33447
+ const v = await chunkWFMVD567_cjs.verifyAndConsumeOtpChallenge(dataSource, entityMap, {
33075
33448
  purpose: "verify_email",
33076
33449
  identifier: email,
33077
33450
  code,
@@ -33121,13 +33494,13 @@ function createStorefrontApiHandler(config) {
33121
33494
  const b = await req.json().catch(() => ({}));
33122
33495
  const phoneRaw = typeof b.phone === "string" ? b.phone.trim() : "";
33123
33496
  const code = typeof b.code === "string" ? b.code.trim() : "";
33124
- const phone = normalizePhoneE164(phoneRaw, defaultPhoneCc);
33497
+ const phone = chunkWFMVD567_cjs.normalizePhoneE164(phoneRaw, defaultPhoneCc);
33125
33498
  if (!phone || !code) return json({
33126
33499
  error: "phone and code required"
33127
33500
  }, {
33128
33501
  status: 400
33129
33502
  });
33130
- const v = await verifyAndConsumeOtpChallenge(dataSource, entityMap, {
33503
+ const v = await chunkWFMVD567_cjs.verifyAndConsumeOtpChallenge(dataSource, entityMap, {
33131
33504
  purpose: "verify_phone",
33132
33505
  identifier: phone,
33133
33506
  code,
@@ -33248,7 +33621,7 @@ function createStorefrontApiHandler(config) {
33248
33621
  const companyDetails = getCompanyDetails ? await getCompanyDetails() : {};
33249
33622
  const base = (publicSiteUrl || "").replace(/\/$/, "").trim() || "http://localhost:3000";
33250
33623
  const verifyEmailUrl = `${base}/verify-email?token=${encodeURIComponent(rawToken)}`;
33251
- await chunkV25RDUOU_cjs.queueEmail(cms, {
33624
+ await chunkMXABMVF7_cjs.queueEmail(cms, {
33252
33625
  to: email,
33253
33626
  templateName: "signup",
33254
33627
  ctx: {
@@ -34060,7 +34433,7 @@ function createStorefrontApiHandler(config) {
34060
34433
  status: 400
34061
34434
  });
34062
34435
  const cms = await getCms();
34063
- return chunkBXYZDMTZ_cjs.streamOrderInvoicePdf(cms, dataSource, entityMap, orderId, {
34436
+ return chunk7L556RGL_cjs.streamOrderInvoicePdf(cms, dataSource, entityMap, orderId, {
34064
34437
  ownerContactId: contact.id
34065
34438
  });
34066
34439
  }
@@ -34267,7 +34640,7 @@ function createStorefrontApiHandler(config) {
34267
34640
  } catch {
34268
34641
  }
34269
34642
  try {
34270
- void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
34643
+ void import('./emit-order-notification-trigger-WI4HGMKH.cjs').then(({ fireOrderNotificationTrigger }) => {
34271
34644
  fireOrderNotificationTrigger("order_cancelled", orderId, {
34272
34645
  dataSource,
34273
34646
  entityMap
@@ -34341,7 +34714,6 @@ exports.completeUserInviteAccept = completeUserInviteAccept;
34341
34714
  exports.consumeAppliedDiscountUsages = consumeAppliedDiscountUsages;
34342
34715
  exports.contactIsVendorCustomer = contactIsVendorCustomer;
34343
34716
  exports.countDiscountOrdersForContact = countDiscountOrdersForContact;
34344
- exports.countRecentOtpSends = countRecentOtpSends;
34345
34717
  exports.createAnalyticsHandlers = createAnalyticsHandlers;
34346
34718
  exports.createBlogBySlugHandler = createBlogBySlugHandler;
34347
34719
  exports.createChangePasswordHandler = createChangePasswordHandler;
@@ -34360,7 +34732,6 @@ exports.createJobScheduleHandlers = createJobScheduleHandlers;
34360
34732
  exports.createLlmAgentKnowledgeHandlers = createLlmAgentKnowledgeHandlers;
34361
34733
  exports.createMediaZipExtractHandler = createMediaZipExtractHandler;
34362
34734
  exports.createMessageTemplateRowLoader = createMessageTemplateRowLoader;
34363
- exports.createOtpChallenge = createOtpChallenge;
34364
34735
  exports.createSetPasswordHandler = createSetPasswordHandler;
34365
34736
  exports.createSettingsApiHandlers = createSettingsApiHandlers;
34366
34737
  exports.createSocialMediaHandlers = createSocialMediaHandlers;
@@ -34383,13 +34754,11 @@ exports.findActiveRefundPolicyForVendor = findActiveRefundPolicyForVendor;
34383
34754
  exports.findUserByInviteToken = findUserByInviteToken;
34384
34755
  exports.findVendorByInviteToken = findVendorByInviteToken;
34385
34756
  exports.formatTierRange = formatTierRange;
34386
- exports.generateNumericOtp = generateNumericOtp;
34387
34757
  exports.getPublicSettingsGroup = getPublicSettingsGroup;
34388
34758
  exports.getRequireEventApproval = getRequireEventApproval;
34389
34759
  exports.getRequireProductApproval = getRequireProductApproval;
34390
34760
  exports.getRssArticleSummaryFromItem = getRssArticleSummaryFromItem;
34391
34761
  exports.getVendorCatalogCreateFlags = getVendorCatalogCreateFlags;
34392
- exports.hashOtpCode = hashOtpCode;
34393
34762
  exports.hydrateVendorSessionUser = hydrateVendorSessionUser;
34394
34763
  exports.invalidateEventsCache = invalidateEventsCache;
34395
34764
  exports.invalidateMultiVendorCache = invalidateMultiVendorCache;
@@ -34410,7 +34779,6 @@ exports.metaPostPageFeed = metaPostPageFeed;
34410
34779
  exports.metaPostPagePhoto = metaPostPagePhoto;
34411
34780
  exports.metaResolvePageAccessToken = metaResolvePageAccessToken;
34412
34781
  exports.newUserInviteToken = newUserInviteToken;
34413
- exports.normalizePhoneE164 = normalizePhoneE164;
34414
34782
  exports.normalizeRefundTiers = normalizeRefundTiers;
34415
34783
  exports.overlayCmsPlugins = overlayCmsPlugins;
34416
34784
  exports.parseBlogGeneratorAgentContent = parseBlogGeneratorAgentContent;
@@ -34421,11 +34789,9 @@ exports.pgBossScheduleNameForId = pgBossScheduleNameForId;
34421
34789
  exports.queueErpCreateContactIfEnabled = queueErpCreateContactIfEnabled;
34422
34790
  exports.queueJobScheduleNow = queueJobScheduleNow;
34423
34791
  exports.queuePlugin = queuePlugin;
34424
- exports.queueSms = queueSms;
34425
34792
  exports.recordDiscountUsage = recordDiscountUsage;
34426
34793
  exports.registerJobRunnerWorker = registerJobRunnerWorker;
34427
34794
  exports.registerMessagingQueueProcessors = registerMessagingQueueProcessors;
34428
- exports.registerSmsQueueProcessor = registerSmsQueueProcessor;
34429
34795
  exports.relativePathFromMediaParentId = relativePathFromMediaParentId;
34430
34796
  exports.resolveBlogCategoryIdByName = resolveBlogCategoryIdByName;
34431
34797
  exports.resolveSettingsEncryptionKey = resolveSettingsEncryptionKey;
@@ -34440,7 +34806,5 @@ exports.validateRefundTiers = validateRefundTiers;
34440
34806
  exports.validateScheduleInput = validateScheduleInput;
34441
34807
  exports.validateUserMessageAgainstAgentRules = validateUserMessageAgainstAgentRules;
34442
34808
  exports.validateUserMessageAgainstStructuredRules = validateUserMessageAgainstStructuredRules;
34443
- exports.verifyAndConsumeOtpChallenge = verifyAndConsumeOtpChallenge;
34444
- exports.verifyOtpCodeHash = verifyOtpCodeHash;
34445
34809
  exports.whatsappPlugin = whatsappPlugin;
34446
34810
  exports.wrapGetCmsWithMessaging = wrapGetCmsWithMessaging;