@infuro/cms-core 1.0.59 → 1.0.61

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 (33) hide show
  1. package/dist/admin.cjs +1020 -83
  2. package/dist/admin.js +1021 -84
  3. package/dist/api.cjs +38 -38
  4. package/dist/api.js +5 -5
  5. package/dist/auth.cjs +51 -51
  6. package/dist/auth.js +3 -3
  7. package/dist/{chunk-3EOM4V2M.cjs → chunk-4U6DATGZ.cjs} +7 -7
  8. package/dist/{chunk-BNKZNLEX.js → chunk-6DBDJ4VD.js} +2 -2
  9. package/dist/{chunk-UQWZUZ5X.cjs → chunk-73WVHINE.cjs} +30 -6
  10. package/dist/{chunk-UCKN4BBY.cjs → chunk-77I3KS7V.cjs} +4 -1
  11. package/dist/{chunk-MCCA7WLQ.cjs → chunk-CNAHVRRU.cjs} +533 -167
  12. package/dist/{chunk-77NUXO6A.cjs → chunk-J7FMZK66.cjs} +10 -2
  13. package/dist/{chunk-BC22I7C7.cjs → chunk-KM2I6AFP.cjs} +9 -9
  14. package/dist/{chunk-JIWUVQ6B.js → chunk-MVHDC3XF.js} +10 -2
  15. package/dist/{chunk-RK5ETF2I.js → chunk-NR44CK5E.js} +1 -1
  16. package/dist/{chunk-MXIWUFBP.js → chunk-O2642WVS.js} +28 -4
  17. package/dist/{chunk-HCIRL37O.js → chunk-T3HPSF7K.js} +4 -1
  18. package/dist/{chunk-BTUEUA5H.js → chunk-UHT4INVW.js} +453 -87
  19. package/dist/{chunk-HYW3MUXT.js → chunk-URN7GS23.js} +30 -16
  20. package/dist/{chunk-HXLC56ZK.cjs → chunk-YSYX4GUD.cjs} +32 -18
  21. package/dist/{emit-order-notification-trigger-HZQPPSFB.js → emit-order-notification-trigger-CZU3V2WE.js} +2 -2
  22. package/dist/{emit-order-notification-trigger-NR3VN6C6.cjs → emit-order-notification-trigger-TNEZOYEE.cjs} +4 -4
  23. package/dist/index.cjs +614 -333
  24. package/dist/index.d.cts +31 -0
  25. package/dist/index.d.ts +31 -0
  26. package/dist/index.js +329 -48
  27. package/dist/migrations/1782800000000-AddPaymentSuccessFailedRefundTriggers.ts +32 -0
  28. package/dist/migrations/1782900000000-AddEnableTurnstileToForms.ts +29 -0
  29. package/dist/{order-notification-dispatcher-2FCZFZUD.cjs → order-notification-dispatcher-KJVGLK5E.cjs} +5 -5
  30. package/dist/{order-notification-dispatcher-64WDCHHG.js → order-notification-dispatcher-ZSFKEYMP.js} +2 -2
  31. package/dist/{rbac-debug-db-6EMIVMGF.js → rbac-debug-db-5R6XFPSV.js} +1 -1
  32. package/dist/{rbac-debug-db-6PWTLBEL.cjs → rbac-debug-db-JKK2MCWF.cjs} +2 -2
  33. package/package.json +1 -1
@@ -2,16 +2,16 @@
2
2
 
3
3
  var chunkXQ3QUHWR_cjs = require('./chunk-XQ3QUHWR.cjs');
4
4
  var chunkHY3AXLOI_cjs = require('./chunk-HY3AXLOI.cjs');
5
- var chunkHXLC56ZK_cjs = require('./chunk-HXLC56ZK.cjs');
5
+ var chunkYSYX4GUD_cjs = require('./chunk-YSYX4GUD.cjs');
6
6
  var chunk7NMT3GBR_cjs = require('./chunk-7NMT3GBR.cjs');
7
7
  var chunkV25RDUOU_cjs = require('./chunk-V25RDUOU.cjs');
8
8
  var chunkBXYZDMTZ_cjs = require('./chunk-BXYZDMTZ.cjs');
9
9
  var chunkUPLVMVRX_cjs = require('./chunk-UPLVMVRX.cjs');
10
10
  var chunk3DZRIZOD_cjs = require('./chunk-3DZRIZOD.cjs');
11
11
  var chunkTJ2MIQUT_cjs = require('./chunk-TJ2MIQUT.cjs');
12
- var chunk3EOM4V2M_cjs = require('./chunk-3EOM4V2M.cjs');
12
+ var chunk4U6DATGZ_cjs = require('./chunk-4U6DATGZ.cjs');
13
13
  var chunkOY2YTBMP_cjs = require('./chunk-OY2YTBMP.cjs');
14
- var chunk77NUXO6A_cjs = require('./chunk-77NUXO6A.cjs');
14
+ var chunkJ7FMZK66_cjs = require('./chunk-J7FMZK66.cjs');
15
15
  var chunkD5FBNKQM_cjs = require('./chunk-D5FBNKQM.cjs');
16
16
  var chunkUSNT2KNT_cjs = require('./chunk-USNT2KNT.cjs');
17
17
  var typeorm = require('typeorm');
@@ -120,7 +120,7 @@ async function loadUserVendorContext(dataSource, userId, preferredVendorId) {
120
120
  `, [
121
121
  primary.vendorRoleId
122
122
  ]);
123
- vendorEntityPerms = chunk77NUXO6A_cjs.permissionRowsToRecord(permRows);
123
+ vendorEntityPerms = chunkJ7FMZK66_cjs.permissionRowsToRecord(permRows);
124
124
  } catch (err) {
125
125
  if (!isMissingVendorRoleSchemaError(err)) throw err;
126
126
  }
@@ -227,7 +227,7 @@ async function hydrateVendorSessionUser(dataSource, user) {
227
227
  ]);
228
228
  const resolvedId = Number(byEmailRows[0]?.id);
229
229
  if (!Number.isFinite(resolvedId)) {
230
- chunk77NUXO6A_cjs.logRbac("hydrateVendorSessionUser: unable to resolve numeric user id", {
230
+ chunkJ7FMZK66_cjs.logRbac("hydrateVendorSessionUser: unable to resolve numeric user id", {
231
231
  email: user.email,
232
232
  rawSessionId: user.id ?? null
233
233
  });
@@ -247,7 +247,7 @@ async function hydrateVendorSessionUser(dataSource, user) {
247
247
  const groupName = rows[0]?.groupName ?? user.groupName ?? null;
248
248
  const groupId = rows[0]?.groupId ?? user.groupId ?? void 0;
249
249
  const adminAccess = rows[0]?.adminAccess ?? user.adminAccess;
250
- const isRBACAdmin = user.isRBACAdmin ?? chunk77NUXO6A_cjs.isSuperAdmin({
250
+ const isRBACAdmin = user.isRBACAdmin ?? chunkJ7FMZK66_cjs.isSuperAdmin({
251
251
  groupId,
252
252
  groupName,
253
253
  isRBACAdmin: user.isRBACAdmin
@@ -260,7 +260,7 @@ async function hydrateVendorSessionUser(dataSource, user) {
260
260
  };
261
261
  if (multiVendorEnabled) {
262
262
  ctx = await loadUserVendorContext(dataSource, id, user.activeVendorId);
263
- flags = chunk77NUXO6A_cjs.vendorPortalFlagsFromUser({
263
+ flags = chunkJ7FMZK66_cjs.vendorPortalFlagsFromUser({
264
264
  email: user.email,
265
265
  isRBACAdmin,
266
266
  groupName,
@@ -295,7 +295,7 @@ async function hydrateVendorSessionUser(dataSource, user) {
295
295
  isVendorPortal: flags.isVendorPortal,
296
296
  isVendorOwner: flags.isVendorOwner
297
297
  };
298
- chunk77NUXO6A_cjs.logRbac("hydrateVendorSessionUser", {
298
+ chunkJ7FMZK66_cjs.logRbac("hydrateVendorSessionUser", {
299
299
  email: user.email,
300
300
  userId: id,
301
301
  groupName,
@@ -908,7 +908,7 @@ function repoHasVendorIdColumn(repo) {
908
908
  }
909
909
  chunkUSNT2KNT_cjs.__name(repoHasVendorIdColumn, "repoHasVendorIdColumn");
910
910
  function resourceUsesVendorScope(resource) {
911
- return resource === "vendors" || chunk77NUXO6A_cjs.VENDOR_SCOPED_STORE_ENTITIES.has(resource);
911
+ return resource === "vendors" || chunkJ7FMZK66_cjs.VENDOR_SCOPED_STORE_ENTITIES.has(resource);
912
912
  }
913
913
  chunkUSNT2KNT_cjs.__name(resourceUsesVendorScope, "resourceUsesVendorScope");
914
914
  function mergeWhereClause(where, extra) {
@@ -1398,7 +1398,7 @@ async function ensureVendorCustomersForOrder(dataSource, entityMap, vendorIds, c
1398
1398
  }
1399
1399
  let customerId = null;
1400
1400
  if (entityMap.customer) {
1401
- const ensured = await chunk3EOM4V2M_cjs.ensureCustomerRecord(dataSource, entityMap.customer, {
1401
+ const ensured = await chunk4U6DATGZ_cjs.ensureCustomerRecord(dataSource, entityMap.customer, {
1402
1402
  name,
1403
1403
  email,
1404
1404
  phone,
@@ -2454,13 +2454,46 @@ function discountCompare(cartValue, op, ruleValue) {
2454
2454
  }
2455
2455
  }
2456
2456
  chunkUSNT2KNT_cjs.__name(discountCompare, "discountCompare");
2457
- function discountEvaluateRule(rule, cartLines, cartTotal) {
2458
- if (rule.conditionType === "group") return discountEvaluateGroup(rule, cartLines, cartTotal);
2457
+ async function getExchangeRate(dataSource, entityMap, fromCurrency, toCurrency) {
2458
+ const from = (fromCurrency || "INR").trim().toUpperCase();
2459
+ const to = (toCurrency || "INR").trim().toUpperCase();
2460
+ if (from === to) return 1;
2461
+ if (entityMap["currency_exchange"]) {
2462
+ try {
2463
+ const exchangeRepo = dataSource.getRepository(entityMap["currency_exchange"]);
2464
+ const direct = await exchangeRepo.findOne({
2465
+ where: {
2466
+ fromCurrency: from,
2467
+ toCurrency: to
2468
+ }
2469
+ });
2470
+ if (direct && Number(direct.rate) > 0) {
2471
+ return Number(direct.rate);
2472
+ }
2473
+ const inverse = await exchangeRepo.findOne({
2474
+ where: {
2475
+ fromCurrency: to,
2476
+ toCurrency: from
2477
+ }
2478
+ });
2479
+ if (inverse && Number(inverse.rate) > 0) {
2480
+ return 1 / Number(inverse.rate);
2481
+ }
2482
+ } catch {
2483
+ }
2484
+ }
2485
+ return 1;
2486
+ }
2487
+ chunkUSNT2KNT_cjs.__name(getExchangeRate, "getExchangeRate");
2488
+ function discountEvaluateRule(rule, cartLines, cartTotal, exchangeRate = 1) {
2489
+ if (rule.conditionType === "group") return discountEvaluateGroup(rule, cartLines, cartTotal, exchangeRate);
2459
2490
  if (rule.type === "reward") return true;
2460
- const ruleValue = discountExtractValue(rule.value);
2491
+ const rawRuleValue = discountExtractValue(rule.value);
2461
2492
  switch (rule.type) {
2462
- case "minAmount":
2463
- return discountCompare(cartTotal, rule.comparisonOperator, ruleValue);
2493
+ case "minAmount": {
2494
+ const convertedValue = typeof rawRuleValue === "number" ? rawRuleValue * exchangeRate : !isNaN(Number(rawRuleValue)) ? Number(rawRuleValue) * exchangeRate : rawRuleValue;
2495
+ return discountCompare(cartTotal, rule.comparisonOperator, convertedValue);
2496
+ }
2464
2497
  case "quantity": {
2465
2498
  if (rule.subType === "productId" && rule.value?.productId) {
2466
2499
  const targetProductId = Number(rule.value.productId);
@@ -2469,11 +2502,11 @@ function discountEvaluateRule(rule, cartLines, cartTotal) {
2469
2502
  return discountCompare(productQty, rule.comparisonOperator, requiredQty);
2470
2503
  }
2471
2504
  const totalQty = cartLines.reduce((s, l) => s + l.quantity, 0);
2472
- return discountCompare(totalQty, rule.comparisonOperator, ruleValue);
2505
+ return discountCompare(totalQty, rule.comparisonOperator, rawRuleValue);
2473
2506
  }
2474
2507
  case "product":
2475
2508
  if (rule.subType === "productId") {
2476
- return cartLines.some((l) => discountCompare(l.productId, rule.comparisonOperator, ruleValue));
2509
+ return cartLines.some((l) => discountCompare(l.productId, rule.comparisonOperator, rawRuleValue));
2477
2510
  }
2478
2511
  return false;
2479
2512
  // These require external context (user session, payment method, time) —
@@ -2497,11 +2530,11 @@ function discountEvaluateRule(rule, cartLines, cartTotal) {
2497
2530
  }
2498
2531
  }
2499
2532
  chunkUSNT2KNT_cjs.__name(discountEvaluateRule, "discountEvaluateRule");
2500
- function discountEvaluateGroup(group, cartLines, cartTotal) {
2533
+ function discountEvaluateGroup(group, cartLines, cartTotal, exchangeRate = 1) {
2501
2534
  if (!group.children?.length) return true;
2502
2535
  const op = (group.conditionOperator ?? "and").toLowerCase();
2503
- if (op === "and") return group.children.every((child) => discountEvaluateRule(child, cartLines, cartTotal));
2504
- if (op === "or") return group.children.some((child) => discountEvaluateRule(child, cartLines, cartTotal));
2536
+ if (op === "and") return group.children.every((child) => discountEvaluateRule(child, cartLines, cartTotal, exchangeRate));
2537
+ if (op === "or") return group.children.some((child) => discountEvaluateRule(child, cartLines, cartTotal, exchangeRate));
2505
2538
  return true;
2506
2539
  }
2507
2540
  chunkUSNT2KNT_cjs.__name(discountEvaluateGroup, "discountEvaluateGroup");
@@ -2548,19 +2581,19 @@ function discountExtractBuyProductId(nodes) {
2548
2581
  return null;
2549
2582
  }
2550
2583
  chunkUSNT2KNT_cjs.__name(discountExtractBuyProductId, "discountExtractBuyProductId");
2551
- function discountBuildUniversalResult(discount, cartLines) {
2584
+ function discountBuildUniversalResult(discount, cartLines, effectiveValue) {
2552
2585
  return {
2553
2586
  rewardLines: cartLines.map((l) => ({
2554
2587
  productId: l.productId,
2555
2588
  quantity: l.quantity,
2556
- discountRate: Number(discount.value),
2589
+ discountRate: effectiveValue,
2557
2590
  discountType: discount.discountType
2558
2591
  })),
2559
2592
  conditionsMet: true
2560
2593
  };
2561
2594
  }
2562
2595
  chunkUSNT2KNT_cjs.__name(discountBuildUniversalResult, "discountBuildUniversalResult");
2563
- function evaluateDiscount(discount, cartLines) {
2596
+ function evaluateDiscount(discount, cartLines, exchangeRate = 1) {
2564
2597
  const empty = {
2565
2598
  rewardLines: [],
2566
2599
  conditionsMet: false
@@ -2584,16 +2617,17 @@ function evaluateDiscount(discount, cartLines) {
2584
2617
  reason: "discount usage limit reached"
2585
2618
  };
2586
2619
  }
2620
+ const effectiveValue = discount.discountType === "FLAT" ? Number(discount.value) * exchangeRate : Number(discount.value);
2587
2621
  const cartTotal = cartLines.reduce((s, l) => s + l.subtotal, 0);
2588
2622
  const tree = discountBuildTree(discount.rules ?? []);
2589
- if (tree.length === 0) return discountBuildUniversalResult(discount, cartLines);
2590
- const conditionsMet = tree.every((node) => discountEvaluateRule(node, cartLines, cartTotal));
2623
+ if (tree.length === 0) return discountBuildUniversalResult(discount, cartLines, effectiveValue);
2624
+ const conditionsMet = tree.every((node) => discountEvaluateRule(node, cartLines, cartTotal, exchangeRate));
2591
2625
  if (!conditionsMet) return {
2592
2626
  ...empty,
2593
2627
  reason: "conditions not met"
2594
2628
  };
2595
2629
  const rewardRules = discountCollectRewardRules(tree);
2596
- if (rewardRules.length === 0) return discountBuildUniversalResult(discount, cartLines);
2630
+ if (rewardRules.length === 0) return discountBuildUniversalResult(discount, cartLines, effectiveValue);
2597
2631
  const requiredBuyQty = discountExtractRequiredBuyQty(tree);
2598
2632
  const buyProductId = discountExtractBuyProductId(tree);
2599
2633
  let dealMultiplier = 1;
@@ -2611,7 +2645,7 @@ function evaluateDiscount(discount, cartLines) {
2611
2645
  rewardLines.push({
2612
2646
  productId: rewardProductId,
2613
2647
  quantity: dealMultiplier,
2614
- discountRate: Number(discount.value),
2648
+ discountRate: effectiveValue,
2615
2649
  discountType: discount.discountType
2616
2650
  });
2617
2651
  } else {
@@ -2620,7 +2654,7 @@ function evaluateDiscount(discount, cartLines) {
2620
2654
  rewardLines.push({
2621
2655
  productId: rewardProductId,
2622
2656
  quantity: rewardQty,
2623
- discountRate: Number(discount.value),
2657
+ discountRate: effectiveValue,
2624
2658
  discountType: discount.discountType
2625
2659
  });
2626
2660
  }
@@ -2631,8 +2665,9 @@ function evaluateDiscount(discount, cartLines) {
2631
2665
  };
2632
2666
  }
2633
2667
  chunkUSNT2KNT_cjs.__name(evaluateDiscount, "evaluateDiscount");
2634
- function applyDiscountToOrderLines(lines, evalResult, maxDiscountAmount) {
2668
+ function applyDiscountToOrderLines(lines, evalResult, maxDiscountAmount, exchangeRate = 1) {
2635
2669
  if (!evalResult.conditionsMet || evalResult.rewardLines.length === 0) return 0;
2670
+ const effectiveMaxDiscountAmount = maxDiscountAmount != null ? Number(maxDiscountAmount) * exchangeRate : null;
2636
2671
  let totalDiscountApplied = 0;
2637
2672
  for (const reward of evalResult.rewardLines) {
2638
2673
  const line = lines.find((l) => l.productId === reward.productId);
@@ -2649,8 +2684,8 @@ function applyDiscountToOrderLines(lines, evalResult, maxDiscountAmount) {
2649
2684
  line.subtotal = line.unitPrice * line.quantity;
2650
2685
  line.total = Math.max(0, line.subtotal - (line.discount ?? 0));
2651
2686
  }
2652
- if (maxDiscountAmount != null && totalDiscountApplied > maxDiscountAmount) {
2653
- const excess = totalDiscountApplied - maxDiscountAmount;
2687
+ if (effectiveMaxDiscountAmount != null && totalDiscountApplied > effectiveMaxDiscountAmount) {
2688
+ const excess = totalDiscountApplied - effectiveMaxDiscountAmount;
2654
2689
  for (let i = evalResult.rewardLines.length - 1; i >= 0; i--) {
2655
2690
  const reward = evalResult.rewardLines[i];
2656
2691
  const line = lines.find((l) => l.productId === reward.productId);
@@ -2660,7 +2695,7 @@ function applyDiscountToOrderLines(lines, evalResult, maxDiscountAmount) {
2660
2695
  line.total = Math.max(0, line.total + rollback);
2661
2696
  if (rollback > 0) break;
2662
2697
  }
2663
- totalDiscountApplied = maxDiscountAmount;
2698
+ totalDiscountApplied = effectiveMaxDiscountAmount;
2664
2699
  }
2665
2700
  return totalDiscountApplied;
2666
2701
  }
@@ -2766,7 +2801,9 @@ async function validateCoupon(dataSource, entityMap, couponCode, orderLines, cur
2766
2801
  unitPrice: l.unitPrice,
2767
2802
  subtotal: l.subtotal
2768
2803
  }));
2769
- const evalResult = evaluateDiscount(discountForEval, cartLines);
2804
+ const dCurrency = d.currency || "INR";
2805
+ const exchangeRate = await getExchangeRate(dataSource, entityMap, dCurrency, currency);
2806
+ const evalResult = evaluateDiscount(discountForEval, cartLines, exchangeRate);
2770
2807
  if (!evalResult.conditionsMet) {
2771
2808
  return {
2772
2809
  valid: false,
@@ -2776,7 +2813,7 @@ async function validateCoupon(dataSource, entityMap, couponCode, orderLines, cur
2776
2813
  const clonedLines = lines.map((l) => ({
2777
2814
  ...l
2778
2815
  }));
2779
- const calculatedDiscount = applyDiscountToOrderLines(clonedLines, evalResult, d.maxDiscountAmount);
2816
+ const calculatedDiscount = applyDiscountToOrderLines(clonedLines, evalResult, d.maxDiscountAmount, exchangeRate);
2780
2817
  const rewardProductIds = evalResult.rewardLines.map((r) => r.productId);
2781
2818
  return {
2782
2819
  valid: true,
@@ -3061,9 +3098,11 @@ async function calculateOrderTotalsFromLines(dataSource, entityMap, lineInputs,
3061
3098
  unitPrice: l.unitPrice,
3062
3099
  subtotal: l.subtotal
3063
3100
  }));
3064
- const evalResult = evaluateDiscount(discountForEval, cartLines);
3101
+ const dCurrency = discountRow.currency || "INR";
3102
+ const exchangeRate2 = await getExchangeRate(dataSource, entityMap, dCurrency, currency);
3103
+ const evalResult = evaluateDiscount(discountForEval, cartLines, exchangeRate2);
3065
3104
  if (evalResult.conditionsMet) {
3066
- const totalDiscountApplied = applyDiscountToOrderLines(lines, evalResult, discountRow.maxDiscountAmount);
3105
+ const totalDiscountApplied = applyDiscountToOrderLines(lines, evalResult, discountRow.maxDiscountAmount, exchangeRate2);
3067
3106
  orderDiscount += totalDiscountApplied;
3068
3107
  }
3069
3108
  }
@@ -3176,9 +3215,25 @@ async function calculateOrderTotals(dataSource, entityMap, itemsSummary, discoun
3176
3215
  unitPrice: l.unitPrice,
3177
3216
  subtotal: l.subtotal
3178
3217
  }));
3179
- const evalResult = evaluateDiscount(discountForEval, cartLines);
3218
+ const dCurrency = discountRow.currency || "INR";
3219
+ let storeCurrency = "INR";
3220
+ if (entityMap["configs"]) {
3221
+ try {
3222
+ const configRepo = dataSource.getRepository(entityMap["configs"]);
3223
+ const curr = await configRepo.findOne({
3224
+ where: {
3225
+ settings: "store",
3226
+ key: "currency"
3227
+ }
3228
+ });
3229
+ storeCurrency = curr?.value?.toUpperCase() ?? "INR";
3230
+ } catch {
3231
+ }
3232
+ }
3233
+ const exchangeRate = await getExchangeRate(dataSource, entityMap, dCurrency, storeCurrency);
3234
+ const evalResult = evaluateDiscount(discountForEval, cartLines, exchangeRate);
3180
3235
  if (evalResult.conditionsMet) {
3181
- const totalDiscountApplied = applyDiscountToOrderLines(lines, evalResult, discountRow.maxDiscountAmount);
3236
+ const totalDiscountApplied = applyDiscountToOrderLines(lines, evalResult, discountRow.maxDiscountAmount, exchangeRate);
3182
3237
  for (const line of lines) {
3183
3238
  if (!line.found || line.taxRate === 0) continue;
3184
3239
  const discountedAmount = line.subtotal - (line.discount ?? 0);
@@ -3801,14 +3856,14 @@ function createCrudHandler(dataSource, entityMap, options) {
3801
3856
  if (Number.isFinite(n)) productWhere[key] = n;
3802
3857
  }
3803
3858
  }
3804
- const idsParam = searchParams.get("ids")?.trim();
3805
- if (idsParam) {
3806
- const ids = idsParam.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
3859
+ const idsParam2 = searchParams.get("ids")?.trim();
3860
+ if (idsParam2) {
3861
+ const ids = idsParam2.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
3807
3862
  productWhere.id = ids.length > 0 ? typeorm.In(ids) : -1;
3808
3863
  } else {
3809
- const excludeIdsParam = searchParams.get("excludeIds")?.trim();
3810
- if (excludeIdsParam) {
3811
- const excludeIds = excludeIdsParam.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
3864
+ const excludeIdsParam2 = searchParams.get("excludeIds")?.trim();
3865
+ if (excludeIdsParam2) {
3866
+ const excludeIds = excludeIdsParam2.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
3812
3867
  if (excludeIds.length > 0) productWhere.id = typeorm.Not(typeorm.In(excludeIds));
3813
3868
  }
3814
3869
  }
@@ -4085,6 +4140,24 @@ function createCrudHandler(dataSource, entityMap, options) {
4085
4140
  }
4086
4141
  }
4087
4142
  where = mergeDeletedFalseWhere(repo, where);
4143
+ const idsParam = searchParams.get("ids")?.trim();
4144
+ if (idsParam && columnNames.has("id")) {
4145
+ const idList = idsParam.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
4146
+ if (idList.length > 0) {
4147
+ where = mergeListWhereAnd(where, {
4148
+ id: typeorm.In(idList)
4149
+ });
4150
+ }
4151
+ }
4152
+ const excludeIdsParam = searchParams.get("excludeIds")?.trim();
4153
+ if (excludeIdsParam && columnNames.has("id")) {
4154
+ const excludeIdList = excludeIdsParam.split(",").map((s) => Number(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
4155
+ if (excludeIdList.length > 0) {
4156
+ where = mergeListWhereAnd(where, {
4157
+ id: typeorm.Not(typeorm.In(excludeIdList))
4158
+ });
4159
+ }
4160
+ }
4088
4161
  if (resourceUsesVendorScope(resource)) {
4089
4162
  const scope = await resolveScope();
4090
4163
  const catalogFlags = await getVendorCatalogCreateFlags(dataSource);
@@ -4348,7 +4421,7 @@ function createCrudHandler(dataSource, entityMap, options) {
4348
4421
  });
4349
4422
  }
4350
4423
  }
4351
- const savedCustomer = await chunk3EOM4V2M_cjs.ensureCustomerRecord(dataSource, entityMap["customer"], {
4424
+ const savedCustomer = await chunk4U6DATGZ_cjs.ensureCustomerRecord(dataSource, entityMap["customer"], {
4352
4425
  name,
4353
4426
  email,
4354
4427
  phone,
@@ -5127,11 +5200,18 @@ function createCrudHandler(dataSource, entityMap, options) {
5127
5200
  await recordDiscountUsage2(dataSource, entityMap, created.id, orderDiscountId, persistBody.contactId, discount);
5128
5201
  }
5129
5202
  const orderIdForNotify = created.id;
5130
- void import('./emit-order-notification-trigger-NR3VN6C6.cjs').then(({ fireOrderNotificationTrigger }) => {
5203
+ const initialPayStatus = String(persistBody.paymentStatus ?? "unpaid").toLowerCase();
5204
+ void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
5131
5205
  fireOrderNotificationTrigger("order_placed", orderIdForNotify, {
5132
5206
  dataSource,
5133
5207
  entityMap
5134
5208
  });
5209
+ if (initialPayStatus === "paid" || initialPayStatus === "captured") {
5210
+ fireOrderNotificationTrigger("payment_success", orderIdForNotify, {
5211
+ dataSource,
5212
+ entityMap
5213
+ });
5214
+ }
5135
5215
  });
5136
5216
  }
5137
5217
  } catch (err) {
@@ -6598,6 +6678,43 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
6598
6678
  await retireSoftDeletedUniquesFromBody(repo, updatePayload);
6599
6679
  try {
6600
6680
  await repo.update(numericId, updatePayload);
6681
+ if (resource === "payments" && updatePayload.status) {
6682
+ const updatedPay = await repo.findOne({
6683
+ where: {
6684
+ id: numericId
6685
+ }
6686
+ });
6687
+ const pOrder = updatedPay?.orderId;
6688
+ const newPayStatus = String(updatePayload.status).toLowerCase();
6689
+ if (pOrder && Number.isFinite(pOrder)) {
6690
+ if (newPayStatus === "paid" || newPayStatus === "captured") {
6691
+ if (entityMap.orders) {
6692
+ await dataSource.getRepository(entityMap.orders).update(pOrder, {
6693
+ status: "confirmed"
6694
+ });
6695
+ }
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, {
6702
+ dataSource,
6703
+ entityMap
6704
+ });
6705
+ }).catch(() => {
6706
+ });
6707
+ } else if (newPayStatus === "failed") {
6708
+ void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
6709
+ fireOrderNotificationTrigger("payment_failed", pOrder, {
6710
+ dataSource,
6711
+ entityMap
6712
+ });
6713
+ }).catch(() => {
6714
+ });
6715
+ }
6716
+ }
6717
+ }
6601
6718
  } catch (err) {
6602
6719
  if (resource === "events" && isSlugUniqueViolation(err)) {
6603
6720
  return json({
@@ -7281,7 +7398,7 @@ function createInviteAcceptHandler(config) {
7281
7398
  }
7282
7399
  const { userId, email, vendorId } = validation.target;
7283
7400
  if (entityMap.contacts) {
7284
- await chunk3EOM4V2M_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, userId, email);
7401
+ await chunk4U6DATGZ_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, userId, email);
7285
7402
  }
7286
7403
  if (beforeActivate) await beforeActivate(email, userId);
7287
7404
  const hashedPassword = await hashPassword(password);
@@ -8374,7 +8491,7 @@ function createVendorDashboardHandler(config) {
8374
8491
  if (pe) return pe;
8375
8492
  }
8376
8493
  const user = await getSessionUser();
8377
- if (!user || !chunk77NUXO6A_cjs.isVendorPortalUser(user)) {
8494
+ if (!user || !chunkJ7FMZK66_cjs.isVendorPortalUser(user)) {
8378
8495
  return json({
8379
8496
  error: "Forbidden"
8380
8497
  }, {
@@ -8721,25 +8838,79 @@ function createUploadHandler(config) {
8721
8838
  "application/x-zip-compressed"
8722
8839
  ];
8723
8840
  return /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async function POST(req) {
8841
+ const reqId = `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8842
+ console.info("[upload] POST /api/upload start", {
8843
+ reqId,
8844
+ method: req.method,
8845
+ contentType: req.headers.get("content-type"),
8846
+ contentLength: req.headers.get("content-length"),
8847
+ hasStorageConfig: storage != null
8848
+ });
8724
8849
  const authErr = await requireAuth(req);
8725
- if (authErr) return authErr;
8850
+ if (authErr) {
8851
+ console.error("[upload] auth failed", {
8852
+ reqId,
8853
+ status: authErr.status
8854
+ });
8855
+ return authErr;
8856
+ }
8857
+ console.info("[upload] auth ok", {
8858
+ reqId
8859
+ });
8726
8860
  if (requireEntityPermission) {
8727
8861
  const pe = await requireEntityPermission(req, "upload", "create");
8728
- if (pe) return pe;
8862
+ if (pe) {
8863
+ console.error("[upload] permission denied", {
8864
+ reqId,
8865
+ status: pe.status
8866
+ });
8867
+ return pe;
8868
+ }
8869
+ console.info("[upload] permission ok", {
8870
+ reqId,
8871
+ entity: "upload",
8872
+ action: "create"
8873
+ });
8729
8874
  }
8730
8875
  try {
8876
+ console.info("[upload] parsing formData", {
8877
+ reqId
8878
+ });
8731
8879
  const formData = await req.formData();
8732
8880
  const file = formData.get("file");
8733
- if (!file) return json({
8734
- error: "No file uploaded"
8735
- }, {
8736
- status: 400
8737
- });
8738
- if (!allowed.includes(file.type)) return json({
8739
- error: "File type not allowed"
8740
- }, {
8741
- status: 400
8881
+ console.info("[upload] formData parsed", {
8882
+ reqId,
8883
+ hasFile: Boolean(file),
8884
+ fileName: file?.name ?? null,
8885
+ fileType: file?.type ?? null,
8886
+ fileSize: file?.size ?? null,
8887
+ formKeys: [
8888
+ ...formData.keys()
8889
+ ]
8742
8890
  });
8891
+ if (!file) {
8892
+ console.error("[upload] no file in formData", {
8893
+ reqId
8894
+ });
8895
+ return json({
8896
+ error: "No file uploaded"
8897
+ }, {
8898
+ status: 400
8899
+ });
8900
+ }
8901
+ if (!allowed.includes(file.type)) {
8902
+ console.error("[upload] file type not allowed", {
8903
+ reqId,
8904
+ fileType: file.type,
8905
+ fileName: file.name,
8906
+ allowed
8907
+ });
8908
+ return json({
8909
+ error: "File type not allowed"
8910
+ }, {
8911
+ status: 400
8912
+ });
8913
+ }
8743
8914
  const defaultMax = 10 * 1024 * 1024;
8744
8915
  const maxZipBytes = 80 * 1024 * 1024;
8745
8916
  const maxVideoBytes = 100 * 1024 * 1024;
@@ -8747,25 +8918,51 @@ function createUploadHandler(config) {
8747
8918
  const isZip = file.type === "application/zip" || file.type === "application/x-zip-compressed";
8748
8919
  const isVideo = file.type === "video/mp4" || file.type === "video/webm" || file.type === "video/quicktime";
8749
8920
  const effectiveMax = isZip ? Math.max(baseMax, maxZipBytes) : isVideo ? Math.max(baseMax, maxVideoBytes) : baseMax;
8750
- if (file.size > effectiveMax) return json({
8751
- error: "File size exceeds limit"
8752
- }, {
8753
- status: 400
8921
+ console.info("[upload] size check", {
8922
+ reqId,
8923
+ fileSize: file.size,
8924
+ effectiveMax,
8925
+ isZip,
8926
+ isVideo,
8927
+ isImage: file.type.startsWith("image/")
8754
8928
  });
8929
+ if (file.size > effectiveMax) {
8930
+ console.error("[upload] file too large", {
8931
+ reqId,
8932
+ fileSize: file.size,
8933
+ effectiveMax,
8934
+ fileName: file.name
8935
+ });
8936
+ return json({
8937
+ error: "File size exceeds limit"
8938
+ }, {
8939
+ status: 400
8940
+ });
8941
+ }
8755
8942
  const parentRaw = formData.get("parentId");
8756
8943
  let parentId = null;
8757
8944
  if (parentRaw != null && String(parentRaw).trim() !== "") {
8758
8945
  const n = Number(parentRaw);
8759
- if (!Number.isFinite(n)) return json({
8760
- error: "Invalid parentId"
8761
- }, {
8762
- status: 400
8763
- });
8946
+ if (!Number.isFinite(n)) {
8947
+ console.error("[upload] invalid parentId", {
8948
+ reqId,
8949
+ parentRaw
8950
+ });
8951
+ return json({
8952
+ error: "Invalid parentId"
8953
+ }, {
8954
+ status: 400
8955
+ });
8956
+ }
8764
8957
  parentId = n;
8765
8958
  }
8766
8959
  let folder = "";
8767
8960
  if (parentId != null) {
8768
8961
  if (!dataSource || !entityMap?.media) {
8962
+ console.error("[upload] missing dataSource/entityMap for folder upload", {
8963
+ reqId,
8964
+ parentId
8965
+ });
8769
8966
  return json({
8770
8967
  error: "Upload handler needs dataSource and entityMap for folder uploads"
8771
8968
  }, {
@@ -8779,6 +8976,12 @@ function createUploadHandler(config) {
8779
8976
  }
8780
8977
  });
8781
8978
  if (!p || p.kind !== "folder") {
8979
+ console.error("[upload] parent is not a folder", {
8980
+ reqId,
8981
+ parentId,
8982
+ found: Boolean(p),
8983
+ kind: p ? p.kind : null
8984
+ });
8782
8985
  return json({
8783
8986
  error: "parent must be a folder"
8784
8987
  }, {
@@ -8786,25 +8989,90 @@ function createUploadHandler(config) {
8786
8989
  });
8787
8990
  }
8788
8991
  folder = await relativePathFromMediaParentId(dataSource, entityMap, parentId);
8992
+ console.info("[upload] resolved folder from parentId", {
8993
+ reqId,
8994
+ parentId,
8995
+ folder
8996
+ });
8789
8997
  } else {
8790
8998
  const folderRawLegacy = formData.get("folder") ?? formData.get("folderPath");
8791
8999
  if (folderRawLegacy && typeof folderRawLegacy === "string" && folderRawLegacy.trim()) {
8792
9000
  folder = sanitizeMediaFolderPath(folderRawLegacy);
9001
+ console.info("[upload] resolved folder from legacy field", {
9002
+ reqId,
9003
+ folder
9004
+ });
8793
9005
  }
8794
9006
  }
9007
+ console.info("[upload] reading file into buffer", {
9008
+ reqId,
9009
+ fileName: file.name,
9010
+ fileType: file.type,
9011
+ fileSize: file.size
9012
+ });
8795
9013
  const buffer = Buffer.from(await file.arrayBuffer());
8796
9014
  const fileName = `${Date.now()}-${file.name}`;
8797
9015
  const contentType = file.type || "application/octet-stream";
8798
9016
  const relativeUnderUploads = folder ? `${folder}/${fileName}` : fileName;
9017
+ const storageKey = `uploads/${relativeUnderUploads}`;
9018
+ console.info("[upload] S3/storage key prepared", {
9019
+ reqId,
9020
+ originalFileName: file.name,
9021
+ stampedFileName: fileName,
9022
+ folder: folder || "(root)",
9023
+ relativeUnderUploads,
9024
+ storageKey,
9025
+ contentType,
9026
+ bytes: buffer.length
9027
+ });
8799
9028
  const raw = typeof storage === "function" ? storage() : storage;
9029
+ console.info("[upload] resolving storage service", {
9030
+ reqId,
9031
+ storageKey,
9032
+ storageIsFunction: typeof storage === "function",
9033
+ rawIsPromise: raw instanceof Promise,
9034
+ rawIsNullish: raw == null
9035
+ });
8800
9036
  const storageService = raw instanceof Promise ? await raw : raw;
9037
+ console.info("[upload] storage service resolved", {
9038
+ reqId,
9039
+ storageKey,
9040
+ hasStorageService: Boolean(storageService)
9041
+ });
8801
9042
  if (storageService) {
8802
- const fileUrl = await storageService.upload(buffer, `uploads/${relativeUnderUploads}`, contentType);
9043
+ console.info("[upload] calling storage.upload", {
9044
+ reqId,
9045
+ storageKey,
9046
+ contentType,
9047
+ bytes: buffer.length
9048
+ });
9049
+ const uploadStarted = Date.now();
9050
+ let fileUrl;
9051
+ try {
9052
+ fileUrl = await storageService.upload(buffer, storageKey, contentType);
9053
+ } catch (storageErr) {
9054
+ console.error("[upload] storage.upload threw", {
9055
+ reqId,
9056
+ storageKey,
9057
+ contentType,
9058
+ bytes: buffer.length,
9059
+ ms: Date.now() - uploadStarted,
9060
+ error: storageErr instanceof Error ? storageErr.message : String(storageErr),
9061
+ name: storageErr instanceof Error ? storageErr.name : void 0,
9062
+ stack: storageErr instanceof Error ? storageErr.stack : void 0,
9063
+ code: storageErr && typeof storageErr === "object" && ("Code" in storageErr || "code" in storageErr) ? storageErr.Code ?? storageErr.code : void 0,
9064
+ metadata: storageErr && typeof storageErr === "object" && "$metadata" in storageErr ? storageErr.$metadata : void 0
9065
+ });
9066
+ throw storageErr;
9067
+ }
8803
9068
  console.info("[upload] stored via storage plugin", {
8804
- key: `uploads/${relativeUnderUploads}`,
9069
+ reqId,
9070
+ key: storageKey,
9071
+ fullS3KeyHint: storageKey,
8805
9072
  contentType,
8806
9073
  bytes: buffer.length,
8807
- fileUrl
9074
+ fileUrl,
9075
+ ms: Date.now() - uploadStarted
8808
9076
  });
8809
9077
  return json({
8810
9078
  filePath: fileUrl,
@@ -8812,8 +9080,10 @@ function createUploadHandler(config) {
8812
9080
  });
8813
9081
  }
8814
9082
  console.warn("[upload] no storage plugin \u2014 writing local disk (broken on most deploys)", {
9083
+ reqId,
8815
9084
  localUploadDir,
8816
- key: relativeUnderUploads
9085
+ key: relativeUnderUploads,
9086
+ storageKey
8817
9087
  });
8818
9088
  const fs2 = await import('fs/promises');
8819
9089
  const path2 = await import('path');
@@ -8824,6 +9094,12 @@ function createUploadHandler(config) {
8824
9094
  });
8825
9095
  await fs2.writeFile(filePath, buffer);
8826
9096
  const urlRel = `${localUploadDir.replace(/^\/+/, "").replace(/\\/g, "/")}/${relativeUnderUploads.replace(/\\/g, "/")}`;
9097
+ console.info("[upload] local write ok", {
9098
+ reqId,
9099
+ diskPath: filePath,
9100
+ filePath: `/${urlRel}`,
9101
+ key: relativeUnderUploads
9102
+ });
8827
9103
  return json({
8828
9104
  filePath: `/${urlRel}`,
8829
9105
  parentId
@@ -8832,11 +9108,13 @@ function createUploadHandler(config) {
8832
9108
  const message = err instanceof Error ? err.message : String(err);
8833
9109
  const awsMeta = err && typeof err === "object" && "$metadata" in err ? err.$metadata : void 0;
8834
9110
  console.error("[upload] File upload failed", {
9111
+ reqId,
8835
9112
  error: message,
8836
9113
  stack: err instanceof Error ? err.stack : void 0,
8837
9114
  name: err instanceof Error ? err.name : void 0,
8838
9115
  code: err && typeof err === "object" && ("Code" in err || "code" in err) ? err.Code ?? err.code : void 0,
8839
- metadata: awsMeta
9116
+ metadata: awsMeta,
9117
+ raw: err instanceof Error ? void 0 : String(err)
8840
9118
  });
8841
9119
  if (/Failed to parse body as FormData/i.test(message)) {
8842
9120
  return json({
@@ -9152,7 +9430,9 @@ function createFormSaveHandlers(config) {
9152
9430
  "description",
9153
9431
  "campaign",
9154
9432
  "slug",
9155
- "published"
9433
+ "published",
9434
+ "enableTurnstile",
9435
+ "enable_turnstile"
9156
9436
  ]) {
9157
9437
  if (body[key] !== void 0) formRow[key] = body[key];
9158
9438
  }
@@ -9171,13 +9451,43 @@ function createFormSaveHandlers(config) {
9171
9451
  }
9172
9452
  }
9173
9453
  if (Object.keys(formRow).length > 0) await formRepo().update(formId, formRow);
9174
- await fieldRepo().delete({
9175
- formId
9176
- });
9454
+ const incomingFieldIds = /* @__PURE__ */ new Set();
9177
9455
  for (let i = 0; i < fields.length; i++) {
9178
- const row = normalizeFieldRow(fields[i], formId);
9456
+ const f = fields[i];
9457
+ const fieldId = f.id != null && Number.isFinite(Number(f.id)) && Number(f.id) > 0 ? Number(f.id) : null;
9458
+ const row = normalizeFieldRow(f, formId);
9179
9459
  row.order = i + 1;
9180
- await fieldRepo().save(fieldRepo().create(row));
9460
+ if (fieldId) {
9461
+ const existingField = await fieldRepo().findOne({
9462
+ where: {
9463
+ id: fieldId,
9464
+ formId
9465
+ }
9466
+ });
9467
+ if (existingField) {
9468
+ incomingFieldIds.add(fieldId);
9469
+ await fieldRepo().update({
9470
+ id: fieldId,
9471
+ formId
9472
+ }, row);
9473
+ continue;
9474
+ }
9475
+ }
9476
+ const created = await fieldRepo().save(fieldRepo().create(row));
9477
+ if (created?.id) incomingFieldIds.add(created.id);
9478
+ }
9479
+ const allCurrentFields = await fieldRepo().find({
9480
+ where: {
9481
+ formId
9482
+ }
9483
+ });
9484
+ for (const existingField of allCurrentFields) {
9485
+ if (!incomingFieldIds.has(existingField.id)) {
9486
+ await fieldRepo().delete({
9487
+ id: existingField.id,
9488
+ formId
9489
+ });
9490
+ }
9181
9491
  }
9182
9492
  const saved = await formRepo().findOne({
9183
9493
  where: {
@@ -9331,7 +9641,7 @@ function createFormSubmissionListHandler(config) {
9331
9641
  const limit = Math.min(100, Number(searchParams.get("limit")) || 10);
9332
9642
  const skip = (page - 1) * limit;
9333
9643
  const sortField = searchParams.get("sortField") || "createdAt";
9334
- const sortOrder = searchParams.get("sortOrder") === "desc" ? "DESC" : "ASC";
9644
+ const sortOrder = searchParams.get("sortOrder") === "asc" ? "ASC" : "DESC";
9335
9645
  const [data, total] = await repo.findAndCount({
9336
9646
  skip,
9337
9647
  take: limit,
@@ -9743,11 +10053,11 @@ function createUsersApiHandlers(config) {
9743
10053
  adminAccess
9744
10054
  }));
9745
10055
  if (entityMap.contacts) {
9746
- await chunk3EOM4V2M_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, newUser.id, newUser.email);
10056
+ await chunk4U6DATGZ_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, newUser.id, newUser.email);
9747
10057
  }
9748
10058
  if (entityMap.customer) {
9749
10059
  const phone = typeof body.phone === "string" && body.phone.trim() ? body.phone.trim() : null;
9750
- await chunk3EOM4V2M_cjs.ensureCustomerForUser(dataSource, entityMap.customer, {
10060
+ await chunk4U6DATGZ_cjs.ensureCustomerForUser(dataSource, entityMap.customer, {
9751
10061
  id: newUser.id,
9752
10062
  name: String(newUser.name ?? body.name),
9753
10063
  email: String(newUser.email),
@@ -10837,7 +11147,7 @@ function createChatHandlers(config) {
10837
11147
  const notifyEmailAgent = await findLlmAgentByScope(dataSource, entityMap, LLM_AGENT_SCOPE_EMAIL_INTENT_CHATBOT, {
10838
11148
  enabledOnly: false
10839
11149
  });
10840
- const emailTool = chunkHXLC56ZK_cjs.resolveChatEmailToolSettings(llmSettings, {
11150
+ const emailTool = chunkYSYX4GUD_cjs.resolveChatEmailToolSettings(llmSettings, {
10841
11151
  chatbotValidationRules: agentRow?.validationRules ?? null,
10842
11152
  notifyAgent: notifyEmailAgent ? {
10843
11153
  systemInstruction: notifyEmailAgent.systemInstruction,
@@ -10847,7 +11157,7 @@ function createChatHandlers(config) {
10847
11157
  const emailPlugin2 = cms.getPlugin("email");
10848
11158
  const convLeadSent = conv.leadEmailSentAt;
10849
11159
  const chatAgentFn = llm.chatAgent?.bind(llm);
10850
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline check", {
11160
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline check", {
10851
11161
  conversationId,
10852
11162
  enabled: emailTool.enabled,
10853
11163
  intentCount: emailTool.intents.length,
@@ -10861,27 +11171,27 @@ function createChatHandlers(config) {
10861
11171
  mergedPromptIncludesNotify: Boolean(notifyEmailAgent?.systemInstruction?.trim())
10862
11172
  });
10863
11173
  if (!emailTool.enabled) {
10864
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11174
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10865
11175
  conversationId,
10866
11176
  reason: "email_tool_disabled"
10867
11177
  });
10868
11178
  } else if (emailTool.intents.length === 0) {
10869
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11179
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10870
11180
  conversationId,
10871
11181
  reason: "no_intents_configured"
10872
11182
  });
10873
11183
  } else if (!emailPlugin2) {
10874
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11184
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10875
11185
  conversationId,
10876
11186
  reason: "email_plugin_missing"
10877
11187
  });
10878
11188
  } else if (!chatAgentFn) {
10879
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11189
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10880
11190
  conversationId,
10881
11191
  reason: "llm_chat_agent_unavailable"
10882
11192
  });
10883
11193
  } else if (convLeadSent) {
10884
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11194
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10885
11195
  conversationId,
10886
11196
  reason: "lead_email_already_sent",
10887
11197
  leadEmailSentAt: convLeadSent
@@ -10894,7 +11204,7 @@ function createChatHandlers(config) {
10894
11204
  }
10895
11205
  });
10896
11206
  if (!contactRow) {
10897
- console.warn(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
11207
+ console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline skipped", {
10898
11208
  conversationId,
10899
11209
  reason: "contact_not_found",
10900
11210
  contactId
@@ -10902,7 +11212,7 @@ function createChatHandlers(config) {
10902
11212
  } else {
10903
11213
  const c = contactRow;
10904
11214
  try {
10905
- const intent = await chunkHXLC56ZK_cjs.detectChatLeadIntent({
11215
+ const intent = await chunkYSYX4GUD_cjs.detectChatLeadIntent({
10906
11216
  chatAgent: chatAgentFn
10907
11217
  }, {
10908
11218
  settings: emailTool,
@@ -10916,15 +11226,15 @@ function createChatHandlers(config) {
10916
11226
  model: agentRow?.model?.trim() || notifyEmailAgent?.model?.trim() || void 0
10917
11227
  });
10918
11228
  if (!intent.intent || !intent.emailTo) {
10919
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "no email sent", {
11229
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "no email sent", {
10920
11230
  conversationId,
10921
11231
  reason: intent.intent ? "missing_email_to" : "no_intent_match",
10922
11232
  intentLabel: intent.intentLabel,
10923
11233
  classifierReason: intent.reason
10924
11234
  });
10925
11235
  } else {
10926
- const intentRecipients = chunkHXLC56ZK_cjs.parseIntentRecipientEmails(intent.emailTo);
10927
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "intent matched \u2014 sending", {
11236
+ const intentRecipients = chunkYSYX4GUD_cjs.parseIntentRecipientEmails(intent.emailTo);
11237
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "intent matched \u2014 sending", {
10928
11238
  conversationId,
10929
11239
  intent: intent.intent,
10930
11240
  emailTo: intent.emailTo,
@@ -10934,7 +11244,7 @@ function createChatHandlers(config) {
10934
11244
  const emailSettings = await loadSettingsGroupMap(dataSource, entityMap, "email");
10935
11245
  const brandingSettings = await loadSettingsGroupMap(dataSource, entityMap, "branding");
10936
11246
  const companyDetails = chunkBXYZDMTZ_cjs.mergeEmailLayoutCompanyDetails(brandingSettings, emailSettings);
10937
- const leadResult = await chunkHXLC56ZK_cjs.sendChatLeadEmail(cms, emailSettings, brandingSettings, {
11247
+ const leadResult = await chunkYSYX4GUD_cjs.sendChatLeadEmail(cms, emailSettings, brandingSettings, {
10938
11248
  contactName: String(c.name ?? "").trim() || "Visitor",
10939
11249
  contactEmail: String(c.email ?? "").trim(),
10940
11250
  contactPhone: c.phone ?? null,
@@ -10942,7 +11252,7 @@ function createChatHandlers(config) {
10942
11252
  latestMessage: message,
10943
11253
  intentCode: intent.intent,
10944
11254
  intentReason: intent.intentLabel || intent.reason,
10945
- transcript: chunkHXLC56ZK_cjs.buildTranscriptForLeadEmail(history, message),
11255
+ transcript: chunkYSYX4GUD_cjs.buildTranscriptForLeadEmail(history, message),
10946
11256
  companyDetails,
10947
11257
  recipients: intentRecipients.length > 0 ? intentRecipients : void 0
10948
11258
  });
@@ -10950,13 +11260,13 @@ function createChatHandlers(config) {
10950
11260
  await convRepo().update(conversationId, {
10951
11261
  leadEmailSentAt: /* @__PURE__ */ new Date()
10952
11262
  });
10953
- console.info(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "lead email recorded", {
11263
+ console.info(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "lead email recorded", {
10954
11264
  conversationId,
10955
11265
  sent: true,
10956
11266
  recipients: leadResult.recipients
10957
11267
  });
10958
11268
  } else {
10959
- console.warn(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "lead email not sent", {
11269
+ console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "lead email not sent", {
10960
11270
  conversationId,
10961
11271
  sent: false,
10962
11272
  error: leadResult.error ?? "unknown",
@@ -10965,7 +11275,7 @@ function createChatHandlers(config) {
10965
11275
  }
10966
11276
  }
10967
11277
  } catch (intentErr) {
10968
- console.warn(chunkHXLC56ZK_cjs.CHAT_EMAIL_LOG, "pipeline error", {
11278
+ console.warn(chunkYSYX4GUD_cjs.CHAT_EMAIL_LOG, "pipeline error", {
10969
11279
  conversationId,
10970
11280
  error: intentErr instanceof Error ? intentErr.message : String(intentErr)
10971
11281
  });
@@ -10982,7 +11292,7 @@ function createChatHandlers(config) {
10982
11292
  });
10983
11293
  if (agentRow && llm.chatAgent) {
10984
11294
  const fromAgent = llmAgentToChatAgentOptions(agentRow);
10985
- const systemPrompt = chunkHXLC56ZK_cjs.buildChatbotSystemPromptWithEmailTool(fromAgent.systemPrompt, parsedValidation.guardrailsForPrompt, emailTool);
11295
+ const systemPrompt = chunkYSYX4GUD_cjs.buildChatbotSystemPromptWithEmailTool(fromAgent.systemPrompt, parsedValidation.guardrailsForPrompt, emailTool);
10986
11296
  const res = await llm.chatAgent({
10987
11297
  ...fromAgent,
10988
11298
  systemPrompt: systemPrompt || void 0,
@@ -11003,7 +11313,7 @@ ${contextParts.join("\n\n")}` : "";
11003
11313
  agentRow.systemInstruction?.trim(),
11004
11314
  ragSystem
11005
11315
  ].filter(Boolean).join("\n\n");
11006
- systemContent = chunkHXLC56ZK_cjs.buildChatbotSystemPromptWithEmailTool(mergedBase || defaultSystem, parsedValidation.guardrailsForPrompt, emailTool) || defaultSystem;
11316
+ systemContent = chunkYSYX4GUD_cjs.buildChatbotSystemPromptWithEmailTool(mergedBase || defaultSystem, parsedValidation.guardrailsForPrompt, emailTool) || defaultSystem;
11007
11317
  } else {
11008
11318
  systemContent = ragSystem || defaultSystem;
11009
11319
  }
@@ -12258,7 +12568,7 @@ function createDeviceTokensHandlers(config) {
12258
12568
  const title = body.title?.trim() || "Test Push Notification";
12259
12569
  const msgBody = body.body?.trim() || "Firebase Push Notification setup is working!";
12260
12570
  if (!token || token === "validate" || token === "validate_only") {
12261
- const valRes = await chunkHXLC56ZK_cjs.validateFcmCredentials(dataSource, entityMap);
12571
+ const valRes = await chunkYSYX4GUD_cjs.validateFcmCredentials(dataSource, entityMap);
12262
12572
  if (!valRes.success) {
12263
12573
  return json({
12264
12574
  success: false,
@@ -12275,7 +12585,7 @@ function createDeviceTokensHandlers(config) {
12275
12585
  clientEmail: valRes.clientEmail
12276
12586
  });
12277
12587
  }
12278
- const res = await chunkHXLC56ZK_cjs.sendFcmPushNotification(dataSource, entityMap, {
12588
+ const res = await chunkYSYX4GUD_cjs.sendFcmPushNotification(dataSource, entityMap, {
12279
12589
  token,
12280
12590
  title,
12281
12591
  body: msgBody,
@@ -12829,7 +13139,7 @@ chunkUSNT2KNT_cjs.__name(findActiveRefundPolicyForVendor, "findActiveRefundPolic
12829
13139
  // src/api/admin-roles-handlers.ts
12830
13140
  function createAdminRolesHandlers(config) {
12831
13141
  const { dataSource, entityMap, json, getSessionUser } = config;
12832
- const baseEntities = chunk77NUXO6A_cjs.getPermissionableEntityKeys(entityMap);
13142
+ const baseEntities = chunkJ7FMZK66_cjs.getPermissionableEntityKeys(entityMap);
12833
13143
  const allowEntities = /* @__PURE__ */ new Set([
12834
13144
  ...baseEntities,
12835
13145
  "users"
@@ -12844,7 +13154,7 @@ function createAdminRolesHandlers(config) {
12844
13154
  }, {
12845
13155
  status: 401
12846
13156
  });
12847
- if (!chunk3EOM4V2M_cjs.canManageRoles(u) && !chunk77NUXO6A_cjs.canManageVendorRoles(u)) {
13157
+ if (!chunk4U6DATGZ_cjs.canManageRoles(u) && !chunkJ7FMZK66_cjs.canManageVendorRoles(u)) {
12848
13158
  return json({
12849
13159
  error: "Forbidden"
12850
13160
  }, {
@@ -12855,11 +13165,11 @@ function createAdminRolesHandlers(config) {
12855
13165
  }
12856
13166
  chunkUSNT2KNT_cjs.__name(gate, "gate");
12857
13167
  function isVendorRolesOnly(u) {
12858
- return chunk77NUXO6A_cjs.canManageVendorRoles(u) && !chunk3EOM4V2M_cjs.canManageRoles(u);
13168
+ return chunkJ7FMZK66_cjs.canManageVendorRoles(u) && !chunk4U6DATGZ_cjs.canManageRoles(u);
12859
13169
  }
12860
13170
  chunkUSNT2KNT_cjs.__name(isVendorRolesOnly, "isVendorRolesOnly");
12861
13171
  const vendorRoleEntities = [
12862
- ...chunk77NUXO6A_cjs.VENDOR_STORE_RBAC_ENTITIES,
13172
+ ...chunkJ7FMZK66_cjs.VENDOR_STORE_RBAC_ENTITIES,
12863
13173
  "dashboard",
12864
13174
  "settings"
12865
13175
  ].sort();
@@ -13016,7 +13326,7 @@ function createAdminRolesHandlers(config) {
13016
13326
  }, {
13017
13327
  status: 404
13018
13328
  });
13019
- if (chunk77NUXO6A_cjs.isSuperAdminGroupName(g.name) && !chunk77NUXO6A_cjs.isSuperAdminGroupName(name)) {
13329
+ if (chunkJ7FMZK66_cjs.isSuperAdminGroupName(g.name) && !chunkJ7FMZK66_cjs.isSuperAdminGroupName(name)) {
13020
13330
  return json({
13021
13331
  error: "Cannot rename the administrator group"
13022
13332
  }, {
@@ -13073,7 +13383,7 @@ function createAdminRolesHandlers(config) {
13073
13383
  }, {
13074
13384
  status: 404
13075
13385
  });
13076
- if (chunk77NUXO6A_cjs.isSuperAdminGroupName(g.name)) return json({
13386
+ if (chunkJ7FMZK66_cjs.isSuperAdminGroupName(g.name)) return json({
13077
13387
  error: "Cannot delete the administrator group"
13078
13388
  }, {
13079
13389
  status: 400
@@ -13270,7 +13580,7 @@ async function sendVendorOnboardEmails(input, deps) {
13270
13580
  getVendorEmails(deps)
13271
13581
  ]);
13272
13582
  const companyDetails = chunkBXYZDMTZ_cjs.mergeEmailLayoutCompanyDetails(branding, emailSettings);
13273
- const configuredNotify = chunkHXLC56ZK_cjs.parseEmailRecipientsFromConfig(emailSettings.salesTeamEmails ?? emailSettings.salesTeamEmail);
13583
+ const configuredNotify = chunkYSYX4GUD_cjs.parseEmailRecipientsFromConfig(emailSettings.salesTeamEmails ?? emailSettings.salesTeamEmail);
13274
13584
  const ownerEmail = input.ownerEmail?.trim() || "";
13275
13585
  const ownerEmailLower = ownerEmail.toLowerCase();
13276
13586
  const sendToOwner = input.sendToOwner !== false;
@@ -13304,7 +13614,7 @@ chunkUSNT2KNT_cjs.__name(sendVendorOnboardEmails, "sendVendorOnboardEmails");
13304
13614
 
13305
13615
  // src/lib/seed-vendor-roles.ts
13306
13616
  async function insertRolePermissions(exec, vendorRoleId, permissions) {
13307
- for (const entity of chunk77NUXO6A_cjs.VENDOR_RBAC_ENTITIES) {
13617
+ for (const entity of chunkJ7FMZK66_cjs.VENDOR_RBAC_ENTITIES) {
13308
13618
  const flags = permissions[entity];
13309
13619
  if (!flags) continue;
13310
13620
  await exec.query(`
@@ -13335,7 +13645,7 @@ async function seedVendorDefaultRoles(em, vendorId) {
13335
13645
  for (const r of existing) {
13336
13646
  roleIdsByName2[r.name] = Number(r.id);
13337
13647
  if (r.isOwnerRole) ownerRoleId2 = Number(r.id);
13338
- if (r.name === chunk77NUXO6A_cjs.VENDOR_VIEWER_ROLE_NAME) viewerRoleId2 = Number(r.id);
13648
+ if (r.name === chunkJ7FMZK66_cjs.VENDOR_VIEWER_ROLE_NAME) viewerRoleId2 = Number(r.id);
13339
13649
  }
13340
13650
  return {
13341
13651
  roleIdsByName: roleIdsByName2,
@@ -13346,7 +13656,7 @@ async function seedVendorDefaultRoles(em, vendorId) {
13346
13656
  const roleIdsByName = {};
13347
13657
  let ownerRoleId = 0;
13348
13658
  let viewerRoleId = 0;
13349
- for (const def of chunk77NUXO6A_cjs.DEFAULT_VENDOR_ROLE_DEFS) {
13659
+ for (const def of chunkJ7FMZK66_cjs.DEFAULT_VENDOR_ROLE_DEFS) {
13350
13660
  const inserted = await exec.query(`
13351
13661
  INSERT INTO "vendor_roles"
13352
13662
  ("vendorId", "name", "description", "isSystem", "isOwnerRole")
@@ -13363,7 +13673,7 @@ async function seedVendorDefaultRoles(em, vendorId) {
13363
13673
  if (!roleId) continue;
13364
13674
  roleIdsByName[def.name] = roleId;
13365
13675
  if (def.isOwnerRole) ownerRoleId = roleId;
13366
- if (def.name === chunk77NUXO6A_cjs.VENDOR_VIEWER_ROLE_NAME) viewerRoleId = roleId;
13676
+ if (def.name === chunkJ7FMZK66_cjs.VENDOR_VIEWER_ROLE_NAME) viewerRoleId = roleId;
13367
13677
  await insertRolePermissions(exec, roleId, def.permissions);
13368
13678
  }
13369
13679
  return {
@@ -13393,7 +13703,7 @@ async function backfillVendorUserRoleIds(em, vendorId, seeded) {
13393
13703
  vendorId
13394
13704
  ]);
13395
13705
  }
13396
- const viewerId = seeded.viewerRoleId || seeded.roleIdsByName[chunk77NUXO6A_cjs.VENDOR_VIEWER_ROLE_NAME];
13706
+ const viewerId = seeded.viewerRoleId || seeded.roleIdsByName[chunkJ7FMZK66_cjs.VENDOR_VIEWER_ROLE_NAME];
13397
13707
  if (viewerId) {
13398
13708
  await em.query(`
13399
13709
  UPDATE "vendor_users"
@@ -13419,7 +13729,7 @@ async function getDefaultStaffRoleIdForVendor(em, vendorId) {
13419
13729
  LIMIT 1
13420
13730
  `, [
13421
13731
  vendorId,
13422
- chunk77NUXO6A_cjs.VENDOR_VIEWER_ROLE_NAME
13732
+ chunkJ7FMZK66_cjs.VENDOR_VIEWER_ROLE_NAME
13423
13733
  ]);
13424
13734
  const id = rows[0]?.id;
13425
13735
  return id != null ? Number(id) : null;
@@ -13780,7 +14090,7 @@ function createVendorOnboardHandlers(config) {
13780
14090
  }, {
13781
14091
  status: 401
13782
14092
  });
13783
- if (!chunk77NUXO6A_cjs.isPlatformAdministrator(u)) return json({
14093
+ if (!chunkJ7FMZK66_cjs.isPlatformAdministrator(u)) return json({
13784
14094
  error: "Forbidden",
13785
14095
  reason: "admin_only"
13786
14096
  }, {
@@ -13790,7 +14100,7 @@ function createVendorOnboardHandlers(config) {
13790
14100
  }
13791
14101
  chunkUSNT2KNT_cjs.__name(gateAdmin, "gateAdmin");
13792
14102
  async function resolveActiveVendorId(u) {
13793
- const scope = chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u);
14103
+ const scope = chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u);
13794
14104
  const candidates = [];
13795
14105
  if (scope.type === "vendor") candidates.push(scope.vendorId);
13796
14106
  if (scope.type === "all" || scope.type === "vendor") {
@@ -13844,7 +14154,7 @@ function createVendorOnboardHandlers(config) {
13844
14154
  }, {
13845
14155
  status: 401
13846
14156
  });
13847
- if (!chunk77NUXO6A_cjs.isVendorPortalUser(u) && !chunk77NUXO6A_cjs.isPlatformAdministrator(u)) {
14157
+ if (!chunkJ7FMZK66_cjs.isVendorPortalUser(u) && !chunkJ7FMZK66_cjs.isPlatformAdministrator(u)) {
13848
14158
  return json({
13849
14159
  error: "Forbidden"
13850
14160
  }, {
@@ -13872,7 +14182,7 @@ function createVendorOnboardHandlers(config) {
13872
14182
  }, {
13873
14183
  status: 401
13874
14184
  });
13875
- if (!chunk77NUXO6A_cjs.canManageVendorTeam(u)) return json({
14185
+ if (!chunkJ7FMZK66_cjs.canManageVendorTeam(u)) return json({
13876
14186
  error: "Forbidden"
13877
14187
  }, {
13878
14188
  status: 403
@@ -14090,7 +14400,7 @@ function createVendorOnboardHandlers(config) {
14090
14400
  await chunkOY2YTBMP_cjs.retireSoftDeletedUniqueValue(vendorRepo, "slug", slug);
14091
14401
  let ownerGroup = await groupRepo.findOne({
14092
14402
  where: {
14093
- name: chunk77NUXO6A_cjs.VENDOR_GROUP_NAME,
14403
+ name: chunkJ7FMZK66_cjs.VENDOR_GROUP_NAME,
14094
14404
  deleted: false
14095
14405
  }
14096
14406
  });
@@ -14105,12 +14415,12 @@ function createVendorOnboardHandlers(config) {
14105
14415
  if (!ownerGroup) {
14106
14416
  try {
14107
14417
  await groupRepo.save(groupRepo.create({
14108
- name: chunk77NUXO6A_cjs.VENDOR_GROUP_NAME,
14418
+ name: chunkJ7FMZK66_cjs.VENDOR_GROUP_NAME,
14109
14419
  deleted: false
14110
14420
  }));
14111
14421
  ownerGroup = await groupRepo.findOne({
14112
14422
  where: {
14113
- name: chunk77NUXO6A_cjs.VENDOR_GROUP_NAME,
14423
+ name: chunkJ7FMZK66_cjs.VENDOR_GROUP_NAME,
14114
14424
  deleted: false
14115
14425
  }
14116
14426
  });
@@ -14227,7 +14537,7 @@ function createVendorOnboardHandlers(config) {
14227
14537
  }
14228
14538
  if (entityMap.customer) {
14229
14539
  try {
14230
- await chunk3EOM4V2M_cjs.ensureCustomerForUser(em, entityMap.customer, {
14540
+ await chunk4U6DATGZ_cjs.ensureCustomerForUser(em, entityMap.customer, {
14231
14541
  id: newUser.id,
14232
14542
  name: userName,
14233
14543
  email: userEmail,
@@ -14727,7 +15037,7 @@ function createVendorOnboardHandlers(config) {
14727
15037
  if (!groupId) {
14728
15038
  const g = await groupRepo.findOne({
14729
15039
  where: {
14730
- name: chunk77NUXO6A_cjs.VENDOR_GROUP_NAME,
15040
+ name: chunkJ7FMZK66_cjs.VENDOR_GROUP_NAME,
14731
15041
  deleted: false
14732
15042
  }
14733
15043
  }) ?? await groupRepo.findOne({
@@ -14827,7 +15137,7 @@ function createVendorOnboardHandlers(config) {
14827
15137
  }
14828
15138
  if (entityMap.customer) {
14829
15139
  try {
14830
- await chunk3EOM4V2M_cjs.ensureCustomerForUser(em, entityMap.customer, {
15140
+ await chunk4U6DATGZ_cjs.ensureCustomerForUser(em, entityMap.customer, {
14831
15141
  id: newUser.id,
14832
15142
  name: userName,
14833
15143
  email: userEmail,
@@ -15364,10 +15674,10 @@ chunkUSNT2KNT_cjs.__name(createVendorOnboardHandlers, "createVendorOnboardHandle
15364
15674
  function createVendorRolesHandlers(config) {
15365
15675
  const { dataSource, entityMap, json, getSessionUser } = config;
15366
15676
  const vendorRoleEntities = [
15367
- ...chunk77NUXO6A_cjs.VENDOR_RBAC_ENTITIES
15677
+ ...chunkJ7FMZK66_cjs.VENDOR_RBAC_ENTITIES
15368
15678
  ].sort();
15369
15679
  async function resolveActiveVendorId(u) {
15370
- const scope = chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u);
15680
+ const scope = chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u);
15371
15681
  if (scope.type === "vendor") return scope.vendorId;
15372
15682
  if (scope.type === "all") {
15373
15683
  const id = u.activeVendorId ?? u.vendorIds?.[0];
@@ -15383,7 +15693,7 @@ function createVendorRolesHandlers(config) {
15383
15693
  }, {
15384
15694
  status: 401
15385
15695
  });
15386
- if (!chunk77NUXO6A_cjs.canManageVendorRoles(u)) return json({
15696
+ if (!chunkJ7FMZK66_cjs.canManageVendorRoles(u)) return json({
15387
15697
  error: "Forbidden"
15388
15698
  }, {
15389
15699
  status: 403
@@ -17048,6 +17358,7 @@ exports.Form = class Form {
17048
17358
  campaign;
17049
17359
  slug;
17050
17360
  published;
17361
+ enableTurnstile;
17051
17362
  createdAt;
17052
17363
  updatedAt;
17053
17364
  deletedAt;
@@ -17090,6 +17401,14 @@ _ts_decorate14([
17090
17401
  }),
17091
17402
  _ts_metadata14("design:type", Boolean)
17092
17403
  ], exports.Form.prototype, "published", void 0);
17404
+ _ts_decorate14([
17405
+ typeorm.Column("boolean", {
17406
+ default: false,
17407
+ name: "enable_turnstile",
17408
+ nullable: true
17409
+ }),
17410
+ _ts_metadata14("design:type", Boolean)
17411
+ ], exports.Form.prototype, "enableTurnstile", void 0);
17093
17412
  _ts_decorate14([
17094
17413
  typeorm.Column({
17095
17414
  type: "timestamp",
@@ -27839,16 +28158,16 @@ function whatsappPlugin(config = {}) {
27839
28158
  db = await getWhatsAppSettings?.() ?? {};
27840
28159
  } catch {
27841
28160
  }
27842
- if (!chunkHXLC56ZK_cjs.isWhatsAppPluginEnabled(db)) {
28161
+ if (!chunkYSYX4GUD_cjs.isWhatsAppPluginEnabled(db)) {
27843
28162
  context.logger.warn("WhatsApp plugin skipped: disabled in Plugins \u2192 WhatsApp");
27844
28163
  return null;
27845
28164
  }
27846
- const merged = chunkHXLC56ZK_cjs.mergeWhatsAppConfigLayers(env, db, staticRest);
27847
- if (!getWhatsAppSettings && !chunkHXLC56ZK_cjs.whatsAppConfigured(merged)) {
28165
+ const merged = chunkYSYX4GUD_cjs.mergeWhatsAppConfigLayers(env, db, staticRest);
28166
+ if (!getWhatsAppSettings && !chunkYSYX4GUD_cjs.whatsAppConfigured(merged)) {
27848
28167
  context.logger.warn("WhatsApp plugin skipped: set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID, or pass getWhatsAppSettings");
27849
28168
  return null;
27850
28169
  }
27851
- const svc = new chunkHXLC56ZK_cjs.WhatsAppService(env, staticRest, getWhatsAppSettings, getMessageTemplateRow);
28170
+ const svc = new chunkYSYX4GUD_cjs.WhatsAppService(env, staticRest, getWhatsAppSettings, getMessageTemplateRow);
27852
28171
  return {
27853
28172
  send: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((opts) => svc.send(opts), "send")
27854
28173
  };
@@ -27925,7 +28244,7 @@ function registerMessagingQueueProcessors(cms, entityMap) {
27925
28244
  getDataSource: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async () => cms.dataSource, "getDataSource"),
27926
28245
  entityMap
27927
28246
  });
27928
- chunkHXLC56ZK_cjs.registerWhatsAppQueueProcessor(cms);
28247
+ chunkYSYX4GUD_cjs.registerWhatsAppQueueProcessor(cms);
27929
28248
  }
27930
28249
  chunkUSNT2KNT_cjs.__name(registerMessagingQueueProcessors, "registerMessagingQueueProcessors");
27931
28250
  async function ensureMessagingPluginsOnCms(base, options) {
@@ -27954,7 +28273,7 @@ async function ensureMessagingPluginsOnCms(base, options) {
27954
28273
  }
27955
28274
  if (!cms.getPlugin("email")) {
27956
28275
  try {
27957
- const instance = await chunkHXLC56ZK_cjs.emailPlugin({
28276
+ const instance = await chunkYSYX4GUD_cjs.emailPlugin({
27958
28277
  type: "SMTP",
27959
28278
  from: config.SMTP_FROM ?? "no-reply@localhost",
27960
28279
  to: config.SMTP_TO ?? ""
@@ -27995,7 +28314,7 @@ function messagingPlugins(options) {
27995
28314
  const config = options.config ?? (typeof process !== "undefined" ? process.env : {});
27996
28315
  return [
27997
28316
  queuePlugin(),
27998
- chunkHXLC56ZK_cjs.emailPlugin({
28317
+ chunkYSYX4GUD_cjs.emailPlugin({
27999
28318
  type: "SMTP",
28000
28319
  from: config.SMTP_FROM ?? "no-reply@localhost",
28001
28320
  to: config.SMTP_TO ?? ""
@@ -28129,7 +28448,7 @@ function createCmsApiHandler(config) {
28129
28448
  } : void 0;
28130
28449
  const entityMap = withLlmKnowledgeEntityFallbacks(rawEntityMap);
28131
28450
  if (getCms) {
28132
- chunkHXLC56ZK_cjs.initWhatsappTriggerDispatcher({
28451
+ chunkYSYX4GUD_cjs.initWhatsappTriggerDispatcher({
28133
28452
  dataSource,
28134
28453
  entityMap,
28135
28454
  getCms
@@ -28142,7 +28461,7 @@ function createCmsApiHandler(config) {
28142
28461
  ] : baseCrudResources;
28143
28462
  const requireEntityPermissionEffective = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async (_req, entity, action) => {
28144
28463
  if (!resolveSessionUser) {
28145
- chunk77NUXO6A_cjs.logRbac("requireEntityPermission: getSessionUser not passed \u2014 vendor store APIs may 403", {
28464
+ chunkJ7FMZK66_cjs.logRbac("requireEntityPermission: getSessionUser not passed \u2014 vendor store APIs may 403", {
28146
28465
  entity,
28147
28466
  action,
28148
28467
  hint: "Pass getSessionUser: auth.getAuthenticatedUser from createCmsAuthBundle()"
@@ -28152,7 +28471,7 @@ function createCmsApiHandler(config) {
28152
28471
  const raw = await resolveSessionUser();
28153
28472
  const u = await hydrateVendorSessionUser(dataSource, raw);
28154
28473
  if (!u?.email) {
28155
- chunk77NUXO6A_cjs.logRbac("requireEntityPermission: no session user", {
28474
+ chunkJ7FMZK66_cjs.logRbac("requireEntityPermission: no session user", {
28156
28475
  entity,
28157
28476
  action
28158
28477
  });
@@ -28162,13 +28481,13 @@ function createCmsApiHandler(config) {
28162
28481
  status: 401
28163
28482
  });
28164
28483
  }
28165
- const allowed = chunk3EOM4V2M_cjs.sessionHasEntityAccess(u, entity, action);
28166
- await chunk77NUXO6A_cjs.logEntityAccessDecision(dataSource, "cmsApi.requireEntityPermission", u, entity, action, {
28484
+ const allowed = chunk4U6DATGZ_cjs.sessionHasEntityAccess(u, entity, action);
28485
+ await chunkJ7FMZK66_cjs.logEntityAccessDecision(dataSource, "cmsApi.requireEntityPermission", u, entity, action, {
28167
28486
  allowed,
28168
28487
  resolvePath: "hydrated_session"
28169
28488
  });
28170
28489
  if (allowed) return null;
28171
- const { reason } = chunk77NUXO6A_cjs.explainSessionEntityAccess(u, entity, action);
28490
+ const { reason } = chunkJ7FMZK66_cjs.explainSessionEntityAccess(u, entity, action);
28172
28491
  return config.json({
28173
28492
  error: "Forbidden",
28174
28493
  entity,
@@ -28179,7 +28498,7 @@ function createCmsApiHandler(config) {
28179
28498
  });
28180
28499
  }
28181
28500
  if (userRequireEntityPermission) {
28182
- chunk77NUXO6A_cjs.logRbac("requireEntityPermission: using app callback only (no getSessionUser)", {
28501
+ chunkJ7FMZK66_cjs.logRbac("requireEntityPermission: using app callback only (no getSessionUser)", {
28183
28502
  entity,
28184
28503
  action
28185
28504
  });
@@ -28266,10 +28585,10 @@ function createCmsApiHandler(config) {
28266
28585
  getVendorScope: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async () => {
28267
28586
  const multiVendorEnabled = await checkMultiVendorEnabled(dataSource);
28268
28587
  if (!multiVendorEnabled) {
28269
- return chunk77NUXO6A_cjs.resolveDisabledMultiVendorScope(dataSource);
28588
+ return chunkJ7FMZK66_cjs.resolveDisabledMultiVendorScope(dataSource);
28270
28589
  }
28271
28590
  const u = await hydrateVendorSessionUser(dataSource, await resolveSessionUser());
28272
- return chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u ?? null);
28591
+ return chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u ?? null);
28273
28592
  }, "getVendorScope"),
28274
28593
  getHydratedSessionUser: /* @__PURE__ */ chunkUSNT2KNT_cjs.__name(async () => {
28275
28594
  const u = await hydrateVendorSessionUser(dataSource, await resolveSessionUser());
@@ -29227,7 +29546,7 @@ function createCmsApiHandler(config) {
29227
29546
  }
29228
29547
  if (path2[0] === "settings" && path2.length === 2 && settingsHandlers) {
29229
29548
  const group = path2[1];
29230
- const isPublic = group === "multi_vendor" || settingsConfig?.publicGetGroups?.includes(group);
29549
+ const isPublic = group === "multi_vendor" || group === "turnstile" || group === "auth_providers" || settingsConfig?.publicGetGroups?.includes(group);
29231
29550
  if (m === "GET") {
29232
29551
  if (!isPublic) {
29233
29552
  const a = await config.requireAuth(req);
@@ -29603,7 +29922,7 @@ function createCmsApiHandler(config) {
29603
29922
  let vendorId = null;
29604
29923
  if (resolveSessionUser) {
29605
29924
  const u = await hydrateVendorSessionUser(dataSource, await resolveSessionUser());
29606
- const scope = chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u ?? null);
29925
+ const scope = chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u ?? null);
29607
29926
  if (scope.type === "vendor") vendorId = scope.vendorId;
29608
29927
  }
29609
29928
  const result = await validateCoupon(dataSource, entityMap, couponCode, orderLinesNorm, currency, contactId, isAutomatic, discountId ?? void 0, vendorId);
@@ -29686,7 +30005,7 @@ function createCmsApiHandler(config) {
29686
30005
  let vendorId = null;
29687
30006
  if (resolveSessionUser) {
29688
30007
  const u = await hydrateVendorSessionUser(dataSource, await resolveSessionUser());
29689
- const scope = chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u ?? null);
30008
+ const scope = chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u ?? null);
29690
30009
  if (scope.type === "vendor") vendorId = scope.vendorId;
29691
30010
  }
29692
30011
  const orderLinesNorm = normalizeOrderLinesInput(body?.orderLines);
@@ -29885,14 +30204,21 @@ function createCmsApiHandler(config) {
29885
30204
  body = {};
29886
30205
  }
29887
30206
  const triggerKey = String(body.triggerKey ?? "order_placed").trim() || "order_placed";
29888
- if (triggerKey !== "order_placed" && triggerKey !== "order_cancelled") {
30207
+ const validTriggers = [
30208
+ "order_placed",
30209
+ "order_cancelled",
30210
+ "payment_success",
30211
+ "payment_failed",
30212
+ "payment_refund_initiated"
30213
+ ];
30214
+ if (!validTriggers.includes(triggerKey)) {
29889
30215
  return config.json({
29890
- error: "Invalid triggerKey; use order_placed or order_cancelled"
30216
+ error: `Invalid triggerKey; use one of: ${validTriggers.join(", ")}`
29891
30217
  }, {
29892
30218
  status: 400
29893
30219
  });
29894
30220
  }
29895
- const { resendOrderNotification } = await import('./order-notification-dispatcher-2FCZFZUD.cjs');
30221
+ const { resendOrderNotification } = await import('./order-notification-dispatcher-KJVGLK5E.cjs');
29896
30222
  const result = await resendOrderNotification(triggerKey, orderId, {
29897
30223
  dataSource,
29898
30224
  entityMap,
@@ -29914,11 +30240,9 @@ function createCmsApiHandler(config) {
29914
30240
  if (path2[0] === "orders" && path2.length === 3 && path2[2] === "cancel" && m === "POST") {
29915
30241
  const a = await config.requireAuth(req);
29916
30242
  if (a) return a;
29917
- const pe = await requireEntityPermissionEffective(req, "orders", "update");
29918
- if (pe) return pe;
29919
- const orderId = Number(path2[1]);
29920
- if (!Number.isFinite(orderId)) return config.json({
29921
- error: "Invalid id"
30243
+ const orderId = parseInt(path2[1], 10);
30244
+ if (Number.isNaN(orderId)) return config.json({
30245
+ error: "Invalid order ID"
29922
30246
  }, {
29923
30247
  status: 400
29924
30248
  });
@@ -29935,9 +30259,10 @@ function createCmsApiHandler(config) {
29935
30259
  status: 404
29936
30260
  });
29937
30261
  const o = order;
29938
- if (o.status !== "confirmed" && o.status !== "completed") {
30262
+ const currentStatus = (o.status || "").toLowerCase();
30263
+ if (currentStatus === "cancelled") {
29939
30264
  return config.json({
29940
- error: "Only confirmed or completed orders can be cancelled"
30265
+ error: "Order is already cancelled"
29941
30266
  }, {
29942
30267
  status: 400
29943
30268
  });
@@ -29960,7 +30285,7 @@ function createCmsApiHandler(config) {
29960
30285
  }
29961
30286
  });
29962
30287
  if (payment) {
29963
- paymentStatus = String(payment.status ?? "unpaid");
30288
+ paymentStatus = String(payment.status ?? "unpaid").toLowerCase();
29964
30289
  paymentId = Number(payment.id);
29965
30290
  }
29966
30291
  }
@@ -29992,13 +30317,26 @@ function createCmsApiHandler(config) {
29992
30317
  status: "cancelled"
29993
30318
  });
29994
30319
  const fireOrderCancelledNotification = /* @__PURE__ */ chunkUSNT2KNT_cjs.__name((refundAmount) => {
29995
- void import('./emit-order-notification-trigger-NR3VN6C6.cjs').then(({ fireOrderNotificationTrigger }) => {
30320
+ void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
29996
30321
  fireOrderNotificationTrigger("order_cancelled", orderId, {
29997
30322
  dataSource,
29998
30323
  entityMap
29999
30324
  }, refundAmount != null && refundAmount > 0 ? {
30000
30325
  refundAmount
30001
30326
  } : void 0);
30327
+ if (paymentStatus === "paid" || paymentStatus === "captured") {
30328
+ fireOrderNotificationTrigger("payment_refund_initiated", orderId, {
30329
+ dataSource,
30330
+ entityMap
30331
+ }, refundAmount != null && refundAmount > 0 ? {
30332
+ refundAmount
30333
+ } : void 0);
30334
+ } else {
30335
+ fireOrderNotificationTrigger("payment_failed", orderId, {
30336
+ dataSource,
30337
+ entityMap
30338
+ });
30339
+ }
30002
30340
  });
30003
30341
  }, "fireOrderCancelledNotification");
30004
30342
  if (paymentStatus === "paid" && entityMap.payments && paymentId) {
@@ -30324,7 +30662,7 @@ function createCmsApiHandler(config) {
30324
30662
  if (resolveSessionUser) {
30325
30663
  const raw = await resolveSessionUser();
30326
30664
  const u = await hydrateVendorSessionUser(dataSource, raw);
30327
- const scope = chunk77NUXO6A_cjs.resolveVendorScopeFromSessionUser(u ?? null);
30665
+ const scope = chunkJ7FMZK66_cjs.resolveVendorScopeFromSessionUser(u ?? null);
30328
30666
  if (scope.type === "vendor") {
30329
30667
  scopedVendorIds = scope.vendorIds;
30330
30668
  }
@@ -31024,12 +31362,23 @@ function createStorefrontApiHandler(config) {
31024
31362
  const otpFlags = config.otpFlags;
31025
31363
  const otpPepper = config.otpPepper;
31026
31364
  const defaultPhoneCc = config.defaultPhoneCountryCode;
31027
- function fireOrderPlacedNotification(orderId) {
31028
- void import('./emit-order-notification-trigger-NR3VN6C6.cjs').then(({ fireOrderNotificationTrigger }) => {
31365
+ function fireOrderPlacedNotification(orderId, isPaid) {
31366
+ void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
31029
31367
  fireOrderNotificationTrigger("order_placed", orderId, {
31030
31368
  dataSource,
31031
31369
  entityMap
31032
31370
  });
31371
+ if (isPaid) {
31372
+ fireOrderNotificationTrigger("payment_success", orderId, {
31373
+ dataSource,
31374
+ entityMap
31375
+ });
31376
+ } else {
31377
+ fireOrderNotificationTrigger("payment_failed", orderId, {
31378
+ dataSource,
31379
+ entityMap
31380
+ });
31381
+ }
31033
31382
  }).catch((err) => console.error("[notification-triggers] import failed", err));
31034
31383
  }
31035
31384
  chunkUSNT2KNT_cjs.__name(fireOrderPlacedNotification, "fireOrderPlacedNotification");
@@ -31064,7 +31413,7 @@ function createStorefrontApiHandler(config) {
31064
31413
  const meta = it.metadata && typeof it.metadata === "object" && !Array.isArray(it.metadata) ? it.metadata : {};
31065
31414
  const fromMeta = Number(meta.comboId ?? meta.combo_id);
31066
31415
  if (Number.isInteger(fromMeta) && fromMeta > 0) return fromMeta;
31067
- if (meta.isCombo === true || meta.type === "combo" || meta.lineType === "combo") {
31416
+ if (meta.isCombo === true || meta.type === "combo" || meta.lineType === "combo" || meta.lineKind === "combo" || meta.itemType === "combo") {
31068
31417
  const pid = Number(it.productId);
31069
31418
  if (Number.isInteger(pid) && pid > 0) return pid;
31070
31419
  }
@@ -32872,10 +33221,10 @@ function createStorefrontApiHandler(config) {
32872
33221
  adminAccess: false
32873
33222
  }));
32874
33223
  const userId = newUser.id;
32875
- await chunk3EOM4V2M_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, userId, email);
33224
+ await chunk4U6DATGZ_cjs.linkUnclaimedContactToUser(dataSource, entityMap.contacts, userId, email);
32876
33225
  if (entityMap.customer) {
32877
33226
  const phone = typeof b.phone === "string" && b.phone.trim() ? String(b.phone).trim() : null;
32878
- await chunk3EOM4V2M_cjs.ensureCustomerForUser(dataSource, entityMap.customer, {
33227
+ await chunk4U6DATGZ_cjs.ensureCustomerForUser(dataSource, entityMap.customer, {
32879
33228
  id: userId,
32880
33229
  name,
32881
33230
  email,
@@ -33193,7 +33542,10 @@ function createStorefrontApiHandler(config) {
33193
33542
  });
33194
33543
  if (existing) {
33195
33544
  await cartItemRepo().update(existing.id, {
33196
- quantity: existing.quantity + gi.quantity
33545
+ quantity: gi.quantity,
33546
+ ...gi.metadata ? {
33547
+ metadata: gi.metadata
33548
+ } : {}
33197
33549
  });
33198
33550
  } else {
33199
33551
  await cartItemRepo().save(cartItemRepo().create({
@@ -33914,6 +34266,20 @@ function createStorefrontApiHandler(config) {
33914
34266
  }
33915
34267
  } catch {
33916
34268
  }
34269
+ try {
34270
+ void import('./emit-order-notification-trigger-TNEZOYEE.cjs').then(({ fireOrderNotificationTrigger }) => {
34271
+ fireOrderNotificationTrigger("order_cancelled", orderId, {
34272
+ dataSource,
34273
+ entityMap
34274
+ });
34275
+ fireOrderNotificationTrigger("payment_failed", orderId, {
34276
+ dataSource,
34277
+ entityMap
34278
+ });
34279
+ }).catch(() => {
34280
+ });
34281
+ } catch {
34282
+ }
33917
34283
  }
33918
34284
  return json({
33919
34285
  ok: true,