@vectoriox/iox-ui 5.101.0 → 5.103.0

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.
@@ -570,6 +570,153 @@ function freeShippingRemaining(methods, cart) {
570
570
  return gap;
571
571
  }
572
572
 
573
+ /**
574
+ * Coupons v1 (commerce plan §3h, E4): a code, a percent or a fixed amount off the GOODS (never the delivery), an
575
+ * optional minimum order, start and end, a uses limit; one per order. `priceCart` is the only place a coupon becomes
576
+ * a discount — iox-cms recomputes it at checkout and when the order is placed (trap T1). Pure: the caller passes `now`.
577
+ */
578
+ var CouponKind;
579
+ (function (CouponKind) {
580
+ CouponKind["Percent"] = "percent";
581
+ CouponKind["Fixed"] = "fixed";
582
+ })(CouponKind || (CouponKind = {}));
583
+ const COUPON_CODE_MIN = 3;
584
+ const COUPON_CODE_MAX = 32;
585
+ const COUPON_CODE = new RegExp(`^[A-Z0-9][A-Z0-9_-]{${COUPON_CODE_MIN - 1},${COUPON_CODE_MAX - 1}}$`);
586
+ const PERCENT_MAX = 100;
587
+ const PERCENT_DECIMALS = 2;
588
+ /** A code as it is stored and compared: trimmed, upper-case. A buyer may type `back10` for `BACK10`. */
589
+ function normalizeCouponCode(value) {
590
+ return typeof value === 'string' ? value.trim().toUpperCase() : '';
591
+ }
592
+ function isCouponCode(value) {
593
+ return COUPON_CODE.test(normalizeCouponCode(value));
594
+ }
595
+ /** What the owner must fix before a coupon may be saved. */
596
+ var CouponProblem;
597
+ (function (CouponProblem) {
598
+ CouponProblem["CodeInvalid"] = "code-invalid";
599
+ CouponProblem["KindInvalid"] = "kind-invalid";
600
+ CouponProblem["PercentInvalid"] = "percent-invalid";
601
+ CouponProblem["AmountInvalid"] = "amount-invalid";
602
+ CouponProblem["MinimumInvalid"] = "minimum-invalid";
603
+ CouponProblem["DatesInvalid"] = "dates-invalid";
604
+ CouponProblem["MaxUsesInvalid"] = "max-uses-invalid";
605
+ })(CouponProblem || (CouponProblem = {}));
606
+ const dateOf = (value) => {
607
+ if (value === null || value === undefined || value === '')
608
+ return null;
609
+ const at = new Date(value).getTime();
610
+ return Number.isFinite(at) ? at : NaN;
611
+ };
612
+ const percentValid = (value) => {
613
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > PERCENT_MAX)
614
+ return false;
615
+ const [, frac = ''] = String(value).split('.');
616
+ return frac.length <= PERCENT_DECIMALS;
617
+ };
618
+ const positiveMoneyIn = (value, currency) => isMoney(value) && value.currency === currency && value.amount > 0;
619
+ /** Every reason this coupon cannot be saved for a studio selling in `currency` — empty when it can. */
620
+ function couponProblems(coupon, currency) {
621
+ const c = coupon ?? {};
622
+ const problems = [];
623
+ if (!isCouponCode(c.code))
624
+ problems.push(CouponProblem.CodeInvalid);
625
+ if (c.kind === CouponKind.Percent) {
626
+ if (!percentValid(c.percent))
627
+ problems.push(CouponProblem.PercentInvalid);
628
+ }
629
+ else if (c.kind === CouponKind.Fixed) {
630
+ if (!positiveMoneyIn(c.amount, currency))
631
+ problems.push(CouponProblem.AmountInvalid);
632
+ }
633
+ else {
634
+ problems.push(CouponProblem.KindInvalid);
635
+ }
636
+ if (c.minimumOrder !== null && c.minimumOrder !== undefined && !(isMoney(c.minimumOrder) && c.minimumOrder.currency === currency && c.minimumOrder.amount >= 0)) {
637
+ problems.push(CouponProblem.MinimumInvalid);
638
+ }
639
+ const starts = dateOf(c.startsAt);
640
+ const ends = dateOf(c.expiresAt);
641
+ if (Number.isNaN(starts) || Number.isNaN(ends) || (starts !== null && ends !== null && ends <= starts))
642
+ problems.push(CouponProblem.DatesInvalid);
643
+ if (c.maxUses !== null && c.maxUses !== undefined && !(Number.isSafeInteger(c.maxUses) && c.maxUses >= 1))
644
+ problems.push(CouponProblem.MaxUsesInvalid);
645
+ return problems;
646
+ }
647
+ /** Why a coupon gives no discount to this cart — each said to the buyer on the coupon field. */
648
+ var CouponRefusal;
649
+ (function (CouponRefusal) {
650
+ CouponRefusal["Unknown"] = "coupon-unknown";
651
+ CouponRefusal["Disabled"] = "coupon-disabled";
652
+ CouponRefusal["NotStarted"] = "coupon-not-started";
653
+ CouponRefusal["Expired"] = "coupon-expired";
654
+ CouponRefusal["UsedUp"] = "coupon-used-up";
655
+ CouponRefusal["MinimumNotMet"] = "coupon-minimum-not-met";
656
+ /** Another currency, or a coupon the owner would not be allowed to save now. */
657
+ CouponRefusal["NotUsable"] = "coupon-not-usable";
658
+ })(CouponRefusal || (CouponRefusal = {}));
659
+ /** `{amount}` is the minimum order, filled by `couponRefusalWords`. */
660
+ const COUPON_REFUSAL_LABELS = Object.freeze({
661
+ [CouponRefusal.Unknown]: { en: 'This code does not exist. Check it and try again.', he: 'הקוד הזה לא קיים. בדקו אותו ונסו שוב.' },
662
+ [CouponRefusal.Disabled]: { en: 'This code is not active.', he: 'הקוד הזה אינו פעיל.' },
663
+ [CouponRefusal.NotStarted]: { en: 'This code cannot be used yet.', he: 'עדיין אי אפשר להשתמש בקוד הזה.' },
664
+ [CouponRefusal.Expired]: { en: 'This code has expired.', he: 'תוקף הקוד הזה פג.' },
665
+ [CouponRefusal.UsedUp]: { en: 'This code has been used up.', he: 'הקוד הזה נוצל עד תומו.' },
666
+ [CouponRefusal.MinimumNotMet]: { en: 'This code is for orders of {amount} or more.', he: 'הקוד הזה תקף להזמנות של {amount} ומעלה.' },
667
+ [CouponRefusal.NotUsable]: { en: 'This code cannot be used on this order.', he: 'אי אפשר להשתמש בקוד הזה בהזמנה הזו.' },
668
+ });
669
+ function couponRefusalWords(refusal, lang, fill = {}) {
670
+ return labelIn(COUPON_REFUSAL_LABELS[refusal], lang).replace('{amount}', fill.amount ?? '');
671
+ }
672
+ const COUPON_OFFER_LABELS = Object.freeze({
673
+ [CouponKind.Percent]: { en: '{percent}% off', he: '{percent}% הנחה' },
674
+ [CouponKind.Fixed]: { en: '{amount} off', he: '{amount} הנחה' },
675
+ });
676
+ /** What a coupon gives, in words ("10% off", "₪50.00 off") — the reminder's offer and the admin's coupon list. */
677
+ function couponOfferWords(coupon, lang, formatMoney) {
678
+ const label = COUPON_OFFER_LABELS[coupon.kind];
679
+ if (!label)
680
+ return '';
681
+ return labelIn(label, lang).replace('{percent}', String(coupon.percent ?? '')).replace('{amount}', coupon.amount ? formatMoney(coupon.amount) : '');
682
+ }
683
+ /** Checked in order; the first that refuses is the one said. */
684
+ const COUPON_RULES = Object.freeze([
685
+ { refusal: CouponRefusal.Disabled, refuses: (c) => c.enabled !== true },
686
+ { refusal: CouponRefusal.NotUsable, refuses: (c, goods) => couponProblems(c, goods.currency).length > 0 },
687
+ { refusal: CouponRefusal.NotStarted, refuses: (c, _g, now) => dateOf(c.startsAt) !== null && now < dateOf(c.startsAt) },
688
+ { refusal: CouponRefusal.Expired, refuses: (c, _g, now) => dateOf(c.expiresAt) !== null && now >= dateOf(c.expiresAt) },
689
+ { refusal: CouponRefusal.UsedUp, refuses: (c) => typeof c.maxUses === 'number' && (c.uses ?? 0) >= c.maxUses },
690
+ { refusal: CouponRefusal.MinimumNotMet, refuses: (c, goods) => !!c.minimumOrder && goods.amount < c.minimumOrder.amount },
691
+ ]);
692
+ /**
693
+ * The discount `coupon` gives goods worth `goods` at `now`: a percent of them (rounded once, half to even) or the
694
+ * fixed amount, never more than the goods themselves. No clock is read: a missing `now` refuses a dated coupon.
695
+ */
696
+ function couponDiscount(coupon, goods, now) {
697
+ if (!coupon)
698
+ return { ok: false, refusal: CouponRefusal.Unknown };
699
+ const at = typeof now === 'number' && Number.isFinite(now) ? now : NaN;
700
+ const dated = dateOf(coupon.startsAt) !== null || dateOf(coupon.expiresAt) !== null;
701
+ if (dated && Number.isNaN(at))
702
+ return { ok: false, refusal: CouponRefusal.NotUsable };
703
+ const refused = COUPON_RULES.find(rule => rule.refuses(coupon, goods, at));
704
+ if (refused)
705
+ return { ok: false, refusal: refused.refusal };
706
+ const raw = coupon.kind === CouponKind.Percent ? percentOf(goods, coupon.percent) : coupon.amount;
707
+ const discount = money(Math.min(raw.amount, goods.amount), goods.currency);
708
+ return {
709
+ ok: true,
710
+ discount,
711
+ applied: {
712
+ code: normalizeCouponCode(coupon.code),
713
+ kind: coupon.kind,
714
+ percent: coupon.kind === CouponKind.Percent ? coupon.percent : null,
715
+ amount: coupon.kind === CouponKind.Fixed ? money(coupon.amount.amount, goods.currency) : null,
716
+ },
717
+ };
718
+ }
719
+
573
720
  var CartIssueCode;
574
721
  (function (CartIssueCode) {
575
722
  /** Not a whole number ≥ 1: the line is dropped. */
@@ -594,6 +741,8 @@ var CartIssueCode;
594
741
  CartIssueCode["ShippingUnavailable"] = "shipping-unavailable";
595
742
  /** The studio's VAT is not a usable rate: the VAT line reads 0. */
596
743
  CartIssueCode["VatInvalid"] = "vat-invalid";
744
+ /** The coupon gives this cart nothing now (expired, used up, under its minimum…): no discount; `couponRefusal` says why. */
745
+ CartIssueCode["CouponNotApplied"] = "coupon-not-applied";
597
746
  })(CartIssueCode || (CartIssueCode = {}));
598
747
  const CART_ISSUE_LABELS = Object.freeze({
599
748
  [CartIssueCode.InvalidQuantity]: { en: 'A quantity was not a whole number, so the item was removed.', he: 'כמות שאינה מספר שלם — הפריט הוסר.' },
@@ -611,6 +760,7 @@ const CART_ISSUE_LABELS = Object.freeze({
611
760
  [CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
612
761
  [CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
613
762
  [CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
763
+ [CartIssueCode.CouponNotApplied]: { en: 'Your coupon no longer applies to this order and was removed.', he: 'הקופון כבר לא חל על ההזמנה הזו והוסר.' },
614
764
  });
615
765
  /** Checked in order; the first that refuses drops the line. */
616
766
  const LINE_REFUSALS = Object.freeze([
@@ -679,6 +829,18 @@ function lineTotalWithin(unitPrice, quantity, subtotal) {
679
829
  return null;
680
830
  }
681
831
  }
832
+ /** The coupon's discount on the goods — none, and an issue said, when the coupon gives this cart nothing now. */
833
+ function discountOf(choice, subtotal, issues) {
834
+ const none = { discount: money(0, subtotal.currency), coupon: null };
835
+ if (!choice?.coupon)
836
+ return none;
837
+ const check = couponDiscount(choice.coupon, subtotal, choice.now);
838
+ if (check.ok === false) {
839
+ issues.push({ code: CartIssueCode.CouponNotApplied, coupon: normalizeCouponCode(choice.coupon.code), couponRefusal: check.refusal });
840
+ return none;
841
+ }
842
+ return { discount: check.discount, coupon: check.applied };
843
+ }
682
844
  /**
683
845
  * THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
684
846
  * payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
@@ -734,7 +896,7 @@ function priceCart(cart, catalog, studio, choice) {
734
896
  image: isText(entry.image) ? entry.image : null,
735
897
  });
736
898
  }
737
- const discount = money(0, currency);
899
+ const { discount, coupon } = discountOf(choice, subtotal, issues);
738
900
  const goods = subtractMoney(subtotal, discount);
739
901
  const requiresShipping = lines.some(line => line.requiresShipping);
740
902
  const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
@@ -752,6 +914,7 @@ function priceCart(cart, catalog, studio, choice) {
752
914
  lines,
753
915
  subtotal,
754
916
  discount,
917
+ coupon,
755
918
  shipping,
756
919
  shippingMethod,
757
920
  requiresShipping,
@@ -1261,15 +1424,15 @@ function deepFreeze(value) {
1261
1424
  return value;
1262
1425
  }
1263
1426
  const copyMoney = (value) => money(value.amount, value.currency);
1264
- const text$1 = (value) => (filled(value) ? value.trim() : null);
1427
+ const text$2 = (value) => (filled(value) ? value.trim() : null);
1265
1428
  function copyAddress(address) {
1266
1429
  if (!address || !filled(address.line1) || !filled(address.city) || !filled(address.country))
1267
1430
  return null;
1268
1431
  return {
1269
1432
  line1: address.line1.trim(),
1270
- line2: text$1(address.line2),
1433
+ line2: text$2(address.line2),
1271
1434
  city: address.city.trim(),
1272
- postalCode: text$1(address.postalCode),
1435
+ postalCode: text$2(address.postalCode),
1273
1436
  country: address.country.trim(),
1274
1437
  };
1275
1438
  }
@@ -1308,6 +1471,7 @@ function orderSnapshot(pricedCart, payment, buyer) {
1308
1471
  })),
1309
1472
  subtotal: copyMoney(pricedCart.subtotal),
1310
1473
  discount: copyMoney(pricedCart.discount),
1474
+ coupon: pricedCart.coupon ? { code: pricedCart.coupon.code } : null,
1311
1475
  shipping: copyMoney(pricedCart.shipping),
1312
1476
  delivery: delivery ? { methodId: delivery.methodId, kind: delivery.kind, name: delivery.name } : null,
1313
1477
  total: copyMoney(pricedCart.total),
@@ -1316,12 +1480,12 @@ function orderSnapshot(pricedCart, payment, buyer) {
1316
1480
  kind: payment.kind,
1317
1481
  channel: paymentChannelOf(payment.kind),
1318
1482
  details: { ...(payment.details ?? {}) },
1319
- note: text$1(payment.note),
1483
+ note: text$2(payment.note),
1320
1484
  },
1321
1485
  buyer: {
1322
1486
  email: buyer.email.trim(),
1323
1487
  name: buyer.name.trim(),
1324
- phone: text$1(buyer.phone),
1488
+ phone: text$2(buyer.phone),
1325
1489
  address: delivery?.needsAddress ? copyAddress(buyer.address) : null,
1326
1490
  },
1327
1491
  };
@@ -1341,14 +1505,14 @@ const VARIANT_NAME_SEPARATOR = '-';
1341
1505
  /** The one variant row a product with no options keeps (iox-cms `DEFAULT_VARIANT_NAME`). */
1342
1506
  const DEFAULT_VARIANT_NAME = 'Default';
1343
1507
  const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
1344
- const text = (value) => (typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
1508
+ const text$1 = (value) => (typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
1345
1509
  /** True for something the storefront could have served as a product: a title and a price or variants. */
1346
1510
  function isStorefrontProduct(value) {
1347
1511
  return isRecord(value) && typeof value['title'] === 'string' && (isRecord(value['pricing']) || Array.isArray(value['variants']));
1348
1512
  }
1349
1513
  /** The product's currency, or null when it names none we know (a price is then never shown — never guessed). */
1350
1514
  function productCurrency(product) {
1351
- const code = text(product?.currency).toUpperCase();
1515
+ const code = text$1(product?.currency).toUpperCase();
1352
1516
  return isCurrencyCode(code) ? code : null;
1353
1517
  }
1354
1518
  /** The options a product offers, cleaned: named, each value once, no empty value. None when it has no variants. */
@@ -1357,12 +1521,12 @@ function productOptions(product) {
1357
1521
  return [];
1358
1522
  const out = [];
1359
1523
  for (const raw of product.options) {
1360
- const name = text(raw?.name);
1524
+ const name = text$1(raw?.name);
1361
1525
  if (!name || out.some(o => o.name === name))
1362
1526
  continue;
1363
1527
  const values = [];
1364
1528
  for (const v of Array.isArray(raw?.values) ? raw.values : []) {
1365
- const value = text(v);
1529
+ const value = text$1(v);
1366
1530
  if (value && !values.includes(value))
1367
1531
  values.push(value);
1368
1532
  }
@@ -1386,7 +1550,7 @@ function combinations(options) {
1386
1550
  }
1387
1551
  /** The choice a stored variant's flat name stands for, or null when no combination of the options writes it. */
1388
1552
  function variantChoiceOf(variant, options) {
1389
- const name = text(variant?.name);
1553
+ const name = text$1(variant?.name);
1390
1554
  if (!name || !options.length)
1391
1555
  return null;
1392
1556
  return combinations(options).find(c => c.name === name)?.choice ?? null;
@@ -1413,7 +1577,7 @@ const AVAILABILITIES = Object.values(Availability);
1413
1577
  function availabilityOf(value, enabled) {
1414
1578
  if (!enabled)
1415
1579
  return Availability.Out;
1416
- return AVAILABILITIES.includes(text(value)) ? text(value) : Availability.InStock;
1580
+ return AVAILABILITIES.includes(text$1(value)) ? text$1(value) : Availability.InStock;
1417
1581
  }
1418
1582
  function aboveOnly(compareAt, price) {
1419
1583
  return compareAt && price && compareAt.amount > price.amount ? compareAt : null;
@@ -1434,12 +1598,12 @@ function productVariants(product) {
1434
1598
  const price = storefrontMoney(priceRaw, currency);
1435
1599
  const state = availabilityOf(availability, enabled);
1436
1600
  return {
1437
- variantId: text(row?._id) || null,
1438
- name: text(row?.name) || null,
1601
+ variantId: text$1(row?._id) || null,
1602
+ name: text$1(row?.name) || null,
1439
1603
  choice,
1440
1604
  price,
1441
1605
  compareAt: aboveOnly(storefrontMoney(compareRaw, currency), price),
1442
- image: text(image) || null,
1606
+ image: text$1(image) || null,
1443
1607
  availability: state,
1444
1608
  enabled,
1445
1609
  sellable: enabled && !!price && state !== Availability.Out,
@@ -1519,14 +1683,14 @@ function chooseValue(options, variants, choice, name, value) {
1519
1683
  * `priceCart` reads where only the storefront is known (the builder canvas's simulated cart). iox-cms builds its own
1520
1684
  * from the stored row, with the stock COUNT. */
1521
1685
  function storefrontCatalog(product) {
1522
- const productId = text(product?._id);
1686
+ const productId = text$1(product?._id);
1523
1687
  if (!product || !productId)
1524
1688
  return [];
1525
1689
  const hasOptions = productOptions(product).length > 0;
1526
1690
  return productVariants(product).map(v => ({
1527
1691
  productId,
1528
1692
  variantId: hasOptions ? v.variantId : null,
1529
- title: text(product.title),
1693
+ title: text$1(product.title),
1530
1694
  variantName: hasOptions ? Object.values(v.choice).join(' · ') : null,
1531
1695
  unitPrice: v.price,
1532
1696
  compareAt: v.compareAt,
@@ -1662,7 +1826,7 @@ function checkoutHref(orgLabel) {
1662
1826
  }
1663
1827
  /** A cart with nothing in it. */
1664
1828
  function emptyCartView(currency = null) {
1665
- return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
1829
+ return { currency, lines: [], count: 0, empty: true, subtotal: null, discount: null, coupon: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
1666
1830
  }
1667
1831
  /** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
1668
1832
  * `maxOf` says how many a line may hold (default the line cap). */
@@ -1677,6 +1841,8 @@ function cartViewOf(priced, options = {}) {
1677
1841
  count,
1678
1842
  empty: lines.length === 0,
1679
1843
  subtotal: priced.subtotal,
1844
+ discount: priced.discount,
1845
+ coupon: priced.coupon ?? null,
1680
1846
  total: priced.total,
1681
1847
  vat: priced.vat,
1682
1848
  vatPercent: priced.vatPercent,
@@ -1874,6 +2040,12 @@ var SiteCommerceRoute;
1874
2040
  SiteCommerceRoute["CheckoutOptions"] = "checkout/options";
1875
2041
  SiteCommerceRoute["Checkout"] = "checkout";
1876
2042
  SiteCommerceRoute["CheckoutPlace"] = "checkout/place";
2043
+ /** `PUT {code}` applies a coupon to the open checkout; `DELETE` removes it (E4). */
2044
+ SiteCommerceRoute["CheckoutCoupon"] = "checkout/coupon";
2045
+ /** `POST /:token` — a reminder's link: the bag back under this browser's cookie, the checkout as it was (E4). */
2046
+ SiteCommerceRoute["CheckoutRecover"] = "checkout/recover";
2047
+ /** `GET|POST /:token` — the unsubscribe page's state, and the unsubscribe itself (E4). */
2048
+ SiteCommerceRoute["Unsubscribe"] = "marketing/unsubscribe";
1877
2049
  SiteCommerceRoute["Order"] = "order";
1878
2050
  })(SiteCommerceRoute || (SiteCommerceRoute = {}));
1879
2051
  /** A public commerce route of one org, ROOT-relative (the same rule as `cartEndpointPath`). */
@@ -1978,6 +2150,10 @@ var CheckoutWord;
1978
2150
  CheckoutWord["StepOf"] = "stepOf";
1979
2151
  CheckoutWord["OrderMissing"] = "orderMissing";
1980
2152
  CheckoutWord["Legal"] = "legal";
2153
+ CheckoutWord["Coupon"] = "coupon";
2154
+ CheckoutWord["ApplyCoupon"] = "applyCoupon";
2155
+ CheckoutWord["RemoveCoupon"] = "removeCoupon";
2156
+ CheckoutWord["Discount"] = "discount";
1981
2157
  })(CheckoutWord || (CheckoutWord = {}));
1982
2158
  /** `{name}`, `{n}`, `{of}`, `{amount}`, `{percent}`, `{number}`, `{email}`, `{total}`, `{place}` are filled by `checkoutWord`. */
1983
2159
  const CHECKOUT_WORDS = Object.freeze({
@@ -2022,6 +2198,10 @@ const CHECKOUT_WORDS = Object.freeze({
2022
2198
  [CheckoutWord.StepOf]: { en: 'Step {n} of {of}', he: 'שלב {n} מתוך {of}' },
2023
2199
  [CheckoutWord.OrderMissing]: { en: 'We could not find this order.', he: 'לא מצאנו את ההזמנה הזו.' },
2024
2200
  [CheckoutWord.Legal]: { en: 'Policies', he: 'מדיניות' },
2201
+ [CheckoutWord.Coupon]: { en: 'Coupon code', he: 'קוד קופון' },
2202
+ [CheckoutWord.ApplyCoupon]: { en: 'Apply', he: 'החלה' },
2203
+ [CheckoutWord.RemoveCoupon]: { en: 'Remove', he: 'הסרה' },
2204
+ [CheckoutWord.Discount]: { en: 'Discount · {code}', he: 'הנחה · {code}' },
2025
2205
  });
2026
2206
  function checkoutWord(word, lang, fill = {}) {
2027
2207
  return labelIn(CHECKOUT_WORDS[word], lang).replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
@@ -2040,6 +2220,8 @@ var CheckoutSlot;
2040
2220
  CheckoutSlot["Terms"] = "terms";
2041
2221
  /** The order summary: the bag itself changed. */
2042
2222
  CheckoutSlot["Cart"] = "cart";
2223
+ /** The coupon field in the order summary (E4). */
2224
+ CheckoutSlot["Coupon"] = "coupon";
2043
2225
  /** The whole page: closed, busy, unreachable. */
2044
2226
  CheckoutSlot["Page"] = "page";
2045
2227
  })(CheckoutSlot || (CheckoutSlot = {}));
@@ -2079,6 +2261,17 @@ var SiteRefusalCode;
2079
2261
  SiteRefusalCode["UnknownSite"] = "unknown-site";
2080
2262
  /** The owner blocked this buyer (commerce E3c): no checkout, no order. */
2081
2263
  SiteRefusalCode["CustomerBlocked"] = "customer-blocked";
2264
+ SiteRefusalCode["CouponUnknown"] = "coupon-unknown";
2265
+ SiteRefusalCode["CouponDisabled"] = "coupon-disabled";
2266
+ SiteRefusalCode["CouponNotStarted"] = "coupon-not-started";
2267
+ SiteRefusalCode["CouponExpired"] = "coupon-expired";
2268
+ SiteRefusalCode["CouponUsedUp"] = "coupon-used-up";
2269
+ SiteRefusalCode["CouponMinimumNotMet"] = "coupon-minimum-not-met";
2270
+ SiteRefusalCode["CouponNotUsable"] = "coupon-not-usable";
2271
+ /** A reminder's link to a purchase that was completed (E4). */
2272
+ SiteRefusalCode["RecoveryDone"] = "recovery-done";
2273
+ /** A reminder's link whose bag is gone, or a link that is not one. */
2274
+ SiteRefusalCode["RecoveryExpired"] = "recovery-expired";
2082
2275
  SiteRefusalCode["Network"] = "network";
2083
2276
  })(SiteRefusalCode || (SiteRefusalCode = {}));
2084
2277
  const ENTER_EMAIL = { en: 'Enter an email address, like name@example.com.', he: 'הקלידו כתובת אימייל, למשל name@example.com.' };
@@ -2118,35 +2311,341 @@ const SITE_REFUSALS = Object.freeze({
2118
2311
  [SiteRefusalCode.UnknownOrder]: { slot: CheckoutSlot.Page, label: { en: 'We could not find this order.', he: 'לא מצאנו את ההזמנה הזו.' } },
2119
2312
  [SiteRefusalCode.UnknownSite]: { slot: CheckoutSlot.Page, label: CLOSED },
2120
2313
  [SiteRefusalCode.CustomerBlocked]: { slot: CheckoutSlot.Page, label: { en: 'This account cannot place orders here. Contact the business.', he: 'החשבון הזה לא יכול לבצע הזמנות כאן. פנו לעסק.' } },
2314
+ [SiteRefusalCode.CouponUnknown]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.Unknown] },
2315
+ [SiteRefusalCode.CouponDisabled]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.Disabled] },
2316
+ [SiteRefusalCode.CouponNotStarted]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.NotStarted] },
2317
+ [SiteRefusalCode.CouponExpired]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.Expired] },
2318
+ [SiteRefusalCode.CouponUsedUp]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.UsedUp] },
2319
+ [SiteRefusalCode.CouponMinimumNotMet]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.MinimumNotMet] },
2320
+ [SiteRefusalCode.CouponNotUsable]: { slot: CheckoutSlot.Coupon, label: COUPON_REFUSAL_LABELS[CouponRefusal.NotUsable] },
2321
+ [SiteRefusalCode.RecoveryDone]: { slot: CheckoutSlot.Page, label: { en: 'This purchase was already completed.', he: 'הרכישה הזו כבר הושלמה.' } },
2322
+ [SiteRefusalCode.RecoveryExpired]: { slot: CheckoutSlot.Page, label: { en: 'This bag is no longer kept. You are welcome to shop again.', he: 'הסל הזה כבר לא שמור. אפשר לקנות שוב.' } },
2121
2323
  [SiteRefusalCode.Network]: { slot: CheckoutSlot.Page, label: { en: 'We could not reach the shop. Try again.', he: 'לא הצלחנו להגיע לחנות. נסו שוב.' } },
2122
2324
  });
2123
2325
  const isRefusalCode = (code) => typeof code === 'string' && Object.values(SiteRefusalCode).includes(code);
2124
2326
  const ORDER_REFUSED = 'order-refused';
2125
- function refusalOf(code, lang) {
2327
+ function refusalOf(code, lang, fill = {}) {
2126
2328
  const known = isRefusalCode(code) ? code : SiteRefusalCode.InvalidBody;
2127
2329
  const rule = SITE_REFUSALS[known];
2128
- return { code: isRefusalCode(code) ? code : String(code ?? known), slot: rule.slot, words: labelIn(rule.label, lang) };
2330
+ const words = labelIn(rule.label, lang).replace(/\{(\w+)\}/g, (all, key) => fill[key] ?? all);
2331
+ return { code: isRefusalCode(code) ? code : String(code ?? known), slot: rule.slot, words };
2129
2332
  }
2130
2333
  /**
2131
2334
  * A refused call's body (`{ statusCode, code, message, refusals? }`) as sentences: `order-refused` says each of its
2132
2335
  * `refusals` on its own field; any other code is one sentence; no body at all is `network`. `message` is a log line
2133
2336
  * and is never shown. One sentence per slot (the first wins).
2134
2337
  */
2135
- function siteRefusalsOf(body, lang) {
2338
+ function siteRefusalsOf(body, lang, formatMoney) {
2136
2339
  const answer = body && typeof body === 'object' ? body : null;
2137
2340
  if (!answer)
2138
2341
  return [refusalOf(SiteRefusalCode.Network, lang)];
2139
2342
  const codes = answer.code === ORDER_REFUSED && Array.isArray(answer.refusals) && answer.refusals.length ? answer.refusals : [answer.code];
2343
+ // A coupon's minimum is said as an amount (`{amount}`), in the host's money format.
2344
+ const fill = isMoney(answer.minimum) && formatMoney ? { amount: formatMoney(answer.minimum) } : {};
2140
2345
  const seen = new Set();
2141
- return codes.map(code => refusalOf(code, lang)).filter(r => !seen.has(r.slot) && !!seen.add(r.slot));
2346
+ return codes.map(code => refusalOf(code, lang, fill)).filter(r => !seen.has(r.slot) && !!seen.add(r.slot));
2347
+ }
2348
+
2349
+ /**
2350
+ * The journey and recovery (commerce plan §3g, C-D13, C-D14 — E4): when a purchase counts as abandoned, the reminder
2351
+ * sequence (1 h · 24 h · 72 h, the last may carry a coupon), the ONE consent rule a reminder obeys, the funnel the owner
2352
+ * reads, the words of the reminder email and the unsubscribe page, and their site paths. Pure: no clock is read —
2353
+ * every caller passes `now` (epoch ms).
2354
+ */
2355
+ const HOUR_MS = 60 * 60 * 1000;
2356
+ /** A purchase with an email and no payment for this long is abandoned — a lead the owner can follow up. */
2357
+ const ABANDONED_AFTER_MS = HOUR_MS;
2358
+ /** A reminder this late (a pod was down, reminders were just switched on) is passed over, never sent stale. */
2359
+ const REMINDER_LATE_MS = 12 * HOUR_MS;
2360
+ var ReminderStep;
2361
+ (function (ReminderStep) {
2362
+ ReminderStep["First"] = "first";
2363
+ ReminderStep["Second"] = "second";
2364
+ ReminderStep["Third"] = "third";
2365
+ })(ReminderStep || (ReminderStep = {}));
2366
+ /** The sequence (board 9): 1 hour after leaving, after 24 hours, after 72 hours + a coupon. */
2367
+ const REMINDER_SEQUENCE = Object.freeze([
2368
+ { step: ReminderStep.First, afterMs: HOUR_MS, carriesCoupon: false },
2369
+ { step: ReminderStep.Second, afterMs: 24 * HOUR_MS, carriesCoupon: false },
2370
+ { step: ReminderStep.Third, afterMs: 72 * HOUR_MS, carriesCoupon: true },
2371
+ ]);
2372
+ const REMINDER_STEPS = Object.freeze(REMINDER_SEQUENCE.map(timing => timing.step));
2373
+ const REMINDER_WORDS_MAX = 200;
2374
+ /** On, every step on, no coupon (board 9). Reminders still go ONLY to a buyer who ticked consent. */
2375
+ const DEFAULT_REMINDER_SETTINGS = Object.freeze({
2376
+ enabled: true,
2377
+ steps: Object.freeze({ [ReminderStep.First]: true, [ReminderStep.Second]: true, [ReminderStep.Third]: true }),
2378
+ couponCode: null,
2379
+ words: Object.freeze({}),
2380
+ });
2381
+ const text = (value, max) => typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null;
2382
+ /** A stored (or sent) settings value read leniently: anything missing or malformed is the default. */
2383
+ function reminderSettingsOf(raw) {
2384
+ const r = raw && typeof raw === 'object' ? raw : {};
2385
+ const steps = { ...DEFAULT_REMINDER_SETTINGS.steps };
2386
+ const words = {};
2387
+ for (const step of REMINDER_STEPS) {
2388
+ if (typeof r.steps?.[step] === 'boolean')
2389
+ steps[step] = r.steps[step];
2390
+ const w = r.words?.[step];
2391
+ const subject = text(w?.subject, REMINDER_WORDS_MAX);
2392
+ const lead = text(w?.lead, REMINDER_WORDS_MAX * 2);
2393
+ if (subject || lead)
2394
+ words[step] = { subject, lead };
2395
+ }
2396
+ return {
2397
+ enabled: typeof r.enabled === 'boolean' ? r.enabled : DEFAULT_REMINDER_SETTINGS.enabled,
2398
+ steps,
2399
+ couponCode: text(r.couponCode, 64)?.toUpperCase() ?? null,
2400
+ words,
2401
+ };
2402
+ }
2403
+ const timeOf = (at) => {
2404
+ if (at === null || at === undefined)
2405
+ return Number.NEGATIVE_INFINITY;
2406
+ const ms = at instanceof Date ? at.getTime() : new Date(at).getTime();
2407
+ return Number.isFinite(ms) ? ms : Number.NEGATIVE_INFINITY;
2408
+ };
2409
+ /**
2410
+ * THE consent gate of a marketing message (Israel's Communications Law §30A, the GDPR — C-D14): the LATEST decision
2411
+ * wins. A tick at a checkout allows; an unsubscribe or the owner's "Stop reminders" after it forbids; a new tick at a
2412
+ * later checkout allows again. No decision at all forbids — a reminder is never sent on silence. A tie forbids.
2413
+ */
2414
+ function marketingAllowed(...decisions) {
2415
+ let latest = null;
2416
+ for (const d of decisions) {
2417
+ if (!d || typeof d.given !== 'boolean')
2418
+ continue;
2419
+ const at = timeOf(d.at);
2420
+ if (!latest || at > latest.at || (at === latest.at && !d.given))
2421
+ latest = { given: d.given, at };
2422
+ }
2423
+ return latest?.given === true;
2424
+ }
2425
+ // ── the sequence ─────────────────────────────────────────────────────────────────────────────────────────
2426
+ /** Why a checkout gets no (more) reminders. */
2427
+ var ReminderStop;
2428
+ (function (ReminderStop) {
2429
+ /** The purchase was made. */
2430
+ ReminderStop["Completed"] = "completed";
2431
+ ReminderStop["NoEmail"] = "no-email";
2432
+ /** No tick, or the latest decision is a withdrawal. */
2433
+ ReminderStop["NoConsent"] = "no-consent";
2434
+ /** The owner marked the lead lost. */
2435
+ ReminderStop["Lost"] = "lost";
2436
+ /** The studio's reminders are off. */
2437
+ ReminderStop["Off"] = "off";
2438
+ /** Every reminder was sent, or its time has passed. */
2439
+ ReminderStop["Done"] = "done";
2440
+ })(ReminderStop || (ReminderStop = {}));
2441
+ const STOPS = Object.freeze([
2442
+ { stop: ReminderStop.Completed, when: (f) => !f.open },
2443
+ { stop: ReminderStop.NoEmail, when: (f) => !f.hasEmail },
2444
+ { stop: ReminderStop.NoConsent, when: (f) => !f.consent },
2445
+ { stop: ReminderStop.Lost, when: (f) => f.lost },
2446
+ { stop: ReminderStop.Off, when: (f) => !f.settings.enabled },
2447
+ ]);
2448
+ /**
2449
+ * The next reminder of a checkout at `now`: the first step that is switched on, not done yet, and not more than
2450
+ * `REMINDER_LATE_MS` past its time — due at `lastActivityAt + afterMs` (it may be in the future: the scheduler waits).
2451
+ * A buyer who comes back moves every later reminder with their activity. Steps too late are passed over silently.
2452
+ */
2453
+ function nextReminder(facts, now) {
2454
+ const stopped = STOPS.find(rule => rule.when(facts));
2455
+ if (stopped)
2456
+ return { due: false, stop: stopped.stop };
2457
+ for (const timing of REMINDER_SEQUENCE) {
2458
+ if (facts.done.includes(timing.step) || facts.settings.steps[timing.step] !== true)
2459
+ continue;
2460
+ const dueAt = facts.lastActivityAt + timing.afterMs;
2461
+ if (now > dueAt + REMINDER_LATE_MS)
2462
+ continue;
2463
+ return { due: true, step: timing.step, dueAt, carriesCoupon: timing.carriesCoupon };
2464
+ }
2465
+ return { due: false, stop: ReminderStop.Done };
2466
+ }
2467
+ /** The step's number as the owner reads it ("Reminder 2"). */
2468
+ function reminderNumber(step) {
2469
+ return REMINDER_STEPS.indexOf(step) + 1;
2470
+ }
2471
+ /** What became of one reminder. */
2472
+ var ReminderOutcome;
2473
+ (function (ReminderOutcome) {
2474
+ ReminderOutcome["Sent"] = "sent";
2475
+ ReminderOutcome["Failed"] = "failed";
2476
+ /** Not sent, on purpose — `ReminderSkip` says why. */
2477
+ ReminderOutcome["Skipped"] = "skipped";
2478
+ })(ReminderOutcome || (ReminderOutcome = {}));
2479
+ var ReminderSkip;
2480
+ (function (ReminderSkip) {
2481
+ /** The studio's sender domain is not verified: it would land in spam (T13). */
2482
+ ReminderSkip["SenderUnverified"] = "sender-unverified";
2483
+ ReminderSkip["NoMailer"] = "no-mailer";
2484
+ /** The studio's public address is unknown, so there is no link to put in it. */
2485
+ ReminderSkip["NoSiteAddress"] = "no-site-address";
2486
+ /** The bag is empty now: nothing to come back to. */
2487
+ ReminderSkip["EmptyBag"] = "empty-bag";
2488
+ /** A send was started and the pod stopped before it was recorded: never sent twice. */
2489
+ ReminderSkip["Interrupted"] = "interrupted";
2490
+ })(ReminderSkip || (ReminderSkip = {}));
2491
+ /** Is a checkout an abandoned purchase at `now`: open, with an email, untouched for an hour. */
2492
+ function isAbandoned(c, now) {
2493
+ return c.open && c.hasEmail && now - c.lastActivityAt >= ABANDONED_AFTER_MS;
2494
+ }
2495
+ /** Where a purchase stopped: the step after the furthest one the buyer completed (board 9's "Stopped at"). */
2496
+ function stoppedAt(furthest) {
2497
+ if (furthest === CheckoutStep.Paid)
2498
+ return CheckoutStep.Paid;
2499
+ if (furthest === CheckoutStep.Delivery || furthest === CheckoutStep.Payment)
2500
+ return CheckoutStep.Payment;
2501
+ return CheckoutStep.Delivery;
2502
+ }
2503
+ // ── the funnel (Shop ▸ Sales journey) ─────────────────────────────────────────────────────────────────────
2504
+ var FunnelStage;
2505
+ (function (FunnelStage) {
2506
+ FunnelStage["AddedToBag"] = "added-to-bag";
2507
+ FunnelStage["GaveEmail"] = "gave-email";
2508
+ FunnelStage["ChoseDelivery"] = "chose-delivery";
2509
+ FunnelStage["ReachedPayment"] = "reached-payment";
2510
+ FunnelStage["PlacedOrder"] = "placed-order";
2511
+ FunnelStage["Paid"] = "paid";
2512
+ })(FunnelStage || (FunnelStage = {}));
2513
+ const FUNNEL_STAGES = Object.freeze([
2514
+ FunnelStage.AddedToBag, FunnelStage.GaveEmail, FunnelStage.ChoseDelivery, FunnelStage.ReachedPayment, FunnelStage.PlacedOrder, FunnelStage.Paid,
2515
+ ]);
2516
+ const count = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
2517
+ /**
2518
+ * The funnel's rows. Each stage is a subset of the one before, so a count is raised to the next stage's when the
2519
+ * records disagree (a bag removed after 30 days while its checkout is kept) — a share never passes 100 %.
2520
+ */
2521
+ function funnelOf(counts) {
2522
+ const values = FUNNEL_STAGES.map(stage => count(counts[stage]));
2523
+ for (let i = values.length - 2; i >= 0; i--)
2524
+ values[i] = Math.max(values[i], values[i + 1]);
2525
+ const first = values[0];
2526
+ return FUNNEL_STAGES.map((stage, i) => ({
2527
+ stage,
2528
+ count: values[i],
2529
+ share: first ? Math.round((values[i] / first) * 100) : 0,
2530
+ drop: i === 0 ? null : values[i - 1] ? Math.round(((values[i - 1] - values[i]) / values[i - 1]) * 100) : 0,
2531
+ }));
2142
2532
  }
2533
+ /** The stage that loses the most buyers after `after` (board 9: "After contact, the biggest drop is at delivery"). */
2534
+ function biggestDrop(rows, after = FunnelStage.GaveEmail) {
2535
+ const from = rows.findIndex(row => row.stage === after);
2536
+ let best = null;
2537
+ for (const row of rows.slice(from + 1))
2538
+ if ((row.drop ?? 0) > 0 && (!best || (row.drop ?? 0) > (best.drop ?? 0)))
2539
+ best = row;
2540
+ return best?.stage ?? null;
2541
+ }
2542
+ /** The Sales journey's periods (board 9). */
2543
+ const JOURNEY_PERIODS_DAYS = Object.freeze([7, 30, 90]);
2544
+ const DEFAULT_JOURNEY_DAYS = 30;
2545
+ // ── one purchase's journey (board 8) ──────────────────────────────────────────────────────────────────────
2546
+ /** What a timeline says happened — the purchase's own records, never browsing (C-D13). */
2547
+ var JourneyEventKind;
2548
+ (function (JourneyEventKind) {
2549
+ JourneyEventKind["CheckoutStarted"] = "checkout-started";
2550
+ JourneyEventKind["DeliveryChosen"] = "delivery-chosen";
2551
+ JourneyEventKind["PaymentChosen"] = "payment-chosen";
2552
+ JourneyEventKind["ReminderSent"] = "reminder-sent";
2553
+ JourneyEventKind["ReminderFailed"] = "reminder-failed";
2554
+ JourneyEventKind["ReminderSkipped"] = "reminder-skipped";
2555
+ JourneyEventKind["ReminderScheduled"] = "reminder-scheduled";
2556
+ JourneyEventKind["CameBack"] = "came-back";
2557
+ JourneyEventKind["Unsubscribed"] = "unsubscribed";
2558
+ JourneyEventKind["MarkedLost"] = "marked-lost";
2559
+ JourneyEventKind["OrderPlaced"] = "order-placed";
2560
+ })(JourneyEventKind || (JourneyEventKind = {}));
2561
+ // ── the site paths ────────────────────────────────────────────────────────────────────────────────────────
2562
+ /** `/<orgLabel>/checkout/r/<token>` — the reminder's link: the bag restored, the step they left. */
2563
+ const RECOVERY_PATH = 'r';
2564
+ /** `/<orgLabel>/checkout/unsubscribe/<token>` — works without signing in. */
2565
+ const UNSUBSCRIBE_PATH = 'unsubscribe';
2566
+ const checkoutTail = (orgLabel, tail) => {
2567
+ const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
2568
+ const path = `checkout/${tail}`;
2569
+ return label ? `/${encodeURIComponent(label)}/${path}` : `/${path}`;
2570
+ };
2571
+ function recoveryHref(orgLabel, token) {
2572
+ return checkoutTail(orgLabel, `${RECOVERY_PATH}/${encodeURIComponent(token)}`);
2573
+ }
2574
+ function unsubscribeHref(orgLabel, token) {
2575
+ return checkoutTail(orgLabel, `${UNSUBSCRIBE_PATH}/${encodeURIComponent(token)}`);
2576
+ }
2577
+ /** `n•••@example.com` — enough for a person to recognise their address, not enough to harvest it. */
2578
+ function maskEmail(email) {
2579
+ const value = String(email ?? '');
2580
+ const at = value.indexOf('@');
2581
+ if (at < 1)
2582
+ return '';
2583
+ return `${value[0]}•••${value.slice(at)}`;
2584
+ }
2585
+ // ── the words ─────────────────────────────────────────────────────────────────────────────────────────────
2586
+ var RecoveryWord;
2587
+ (function (RecoveryWord) {
2588
+ RecoveryWord["SubjectFirst"] = "subjectFirst";
2589
+ RecoveryWord["SubjectSecond"] = "subjectSecond";
2590
+ RecoveryWord["SubjectThird"] = "subjectThird";
2591
+ RecoveryWord["Heading"] = "heading";
2592
+ RecoveryWord["Lead"] = "lead";
2593
+ RecoveryWord["Return"] = "return";
2594
+ RecoveryWord["KeptDetails"] = "keptDetails";
2595
+ RecoveryWord["CouponOffer"] = "couponOffer";
2596
+ RecoveryWord["Why"] = "why";
2597
+ RecoveryWord["Unsubscribe"] = "unsubscribe";
2598
+ RecoveryWord["UnsubscribeTitle"] = "unsubscribeTitle";
2599
+ RecoveryWord["UnsubscribeAsk"] = "unsubscribeAsk";
2600
+ RecoveryWord["UnsubscribeButton"] = "unsubscribeButton";
2601
+ RecoveryWord["UnsubscribeDone"] = "unsubscribeDone";
2602
+ RecoveryWord["UnsubscribeAlready"] = "unsubscribeAlready";
2603
+ RecoveryWord["UnsubscribeUnknown"] = "unsubscribeUnknown";
2604
+ RecoveryWord["UnsubscribeTransactional"] = "unsubscribeTransactional";
2605
+ RecoveryWord["RecoveryDone"] = "recoveryDone";
2606
+ RecoveryWord["RecoveryExpired"] = "recoveryExpired";
2607
+ RecoveryWord["Restoring"] = "restoring";
2608
+ })(RecoveryWord || (RecoveryWord = {}));
2609
+ /** `{studio}`, `{code}`, `{offer}`, `{step}`, `{email}` are filled by `recoveryWord`. */
2610
+ const RECOVERY_WORDS = Object.freeze({
2611
+ [RecoveryWord.SubjectFirst]: { en: '{studio}: your bag is waiting', he: '{studio}: הסל שלך מחכה' },
2612
+ [RecoveryWord.SubjectSecond]: { en: '{studio}: still thinking it over?', he: '{studio}: עדיין מתלבטים?' },
2613
+ [RecoveryWord.SubjectThird]: { en: '{studio}: a little something to finish your order', he: '{studio}: משהו קטן כדי להשלים את ההזמנה' },
2614
+ [RecoveryWord.Heading]: { en: 'You left something in your bag', he: 'השארת משהו בסל' },
2615
+ [RecoveryWord.Lead]: { en: 'Your bag at {studio} is just as you left it.', he: 'הסל שלך ב{studio} בדיוק כפי שהשארת אותו.' },
2616
+ [RecoveryWord.Return]: { en: 'Return to checkout', he: 'חזרה לתשלום' },
2617
+ [RecoveryWord.KeptDetails]: { en: 'We kept your details — you will continue from {step}.', he: 'שמרנו את הפרטים שלך — ממשיכים מ{step}.' },
2618
+ [RecoveryWord.CouponOffer]: { en: 'Use the code {code} for {offer}.', he: 'השתמשו בקוד {code} לקבלת {offer}.' },
2619
+ [RecoveryWord.Why]: { en: 'You are getting this because you asked {studio} for reminders and offers.', he: 'המייל נשלח כי ביקשת מ{studio} תזכורות והצעות.' },
2620
+ [RecoveryWord.Unsubscribe]: { en: 'Unsubscribe', he: 'הסרה מרשימת התפוצה' },
2621
+ [RecoveryWord.UnsubscribeTitle]: { en: 'Reminders and offers from {studio}', he: 'תזכורות והצעות מ{studio}' },
2622
+ [RecoveryWord.UnsubscribeAsk]: { en: 'Stop sending reminders and offers to {email}?', he: 'להפסיק לשלוח תזכורות והצעות אל {email}?' },
2623
+ [RecoveryWord.UnsubscribeButton]: { en: 'Unsubscribe', he: 'הסירו אותי' },
2624
+ [RecoveryWord.UnsubscribeDone]: { en: 'Done. {studio} will send no more reminders or offers to {email}.', he: 'בוצע. {studio} לא ישלחו עוד תזכורות או הצעות אל {email}.' },
2625
+ [RecoveryWord.UnsubscribeAlready]: { en: '{email} gets no reminders or offers from {studio}.', he: '{email} לא מקבל/ת תזכורות או הצעות מ{studio}.' },
2626
+ [RecoveryWord.UnsubscribeUnknown]: { en: 'This link does not work any more. You will get no reminders or offers through it.', he: 'הקישור הזה כבר לא פעיל. לא יישלחו דרכו תזכורות או הצעות.' },
2627
+ [RecoveryWord.UnsubscribeTransactional]: { en: 'Emails about an order you place still arrive.', he: 'מיילים על הזמנה שתבצעו ימשיכו להגיע.' },
2628
+ [RecoveryWord.RecoveryDone]: { en: 'This purchase was already completed.', he: 'הרכישה הזו כבר הושלמה.' },
2629
+ [RecoveryWord.RecoveryExpired]: { en: 'This bag is no longer kept. You are welcome to shop again.', he: 'הסל הזה כבר לא שמור. אפשר לקנות שוב.' },
2630
+ [RecoveryWord.Restoring]: { en: 'Opening your bag…', he: 'פותחים את הסל שלך…' },
2631
+ });
2632
+ function recoveryWord(word, lang, fill = {}) {
2633
+ return labelIn(RECOVERY_WORDS[word], lang).replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
2634
+ }
2635
+ /** The default subject of each reminder. */
2636
+ const REMINDER_SUBJECT_WORDS = Object.freeze({
2637
+ [ReminderStep.First]: RecoveryWord.SubjectFirst,
2638
+ [ReminderStep.Second]: RecoveryWord.SubjectSecond,
2639
+ [ReminderStep.Third]: RecoveryWord.SubjectThird,
2640
+ });
2143
2641
 
2144
2642
  /**
2145
2643
  * @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7…C-D11, C-D19).
2146
2644
  *
2147
2645
  * Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms compute the same
2148
2646
  * totals (trap T6: never a float). E0 shipped Money; E1a adds the cart and its ONE pricing function, shipping v1,
2149
- * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot. No clock is
2647
+ * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot; E4 adds
2648
+ * coupons (one per order, priced by `priceCart`) and the journey: reminders, the consent gate, the funnel. No clock is
2150
2649
  * read anywhere — a caller passes `now`.
2151
2650
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
2152
2651
  * jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
@@ -2156,5 +2655,5 @@ function siteRefusalsOf(body, lang) {
2156
2655
  * Generated bundle index. Do not edit.
2157
2656
  */
2158
2657
 
2159
- export { Availability, CART_COOKIE_PREFIX, CART_ISSUE_LABELS, CART_TRANSPORT_ERROR_LABELS, CHECKOUT_FORM_STEPS, CHECKOUT_GATE_RULES, CHECKOUT_PATH, CHECKOUT_STEPS, CHECKOUT_STEP_LABELS, CHECKOUT_WORDS, CURRENCY_CODES, CURRENCY_EXPONENTS, CartIssueCode, CartTransportError, CartTransportErrorCode, CheckoutAskedField, CheckoutFieldMode, CheckoutGateArea, CheckoutGateCode, CheckoutSlot, CheckoutStep, CheckoutWord, CommerceLanguage, CurrencyCode, DEFAULT_MONEY_LOCALE, DEFAULT_VARIANT_NAME, DeliveryFit, FINAL_ORDER_STATES, LegalPage, MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY, MAX_VAT_PERCENT, MIN_LINE_QUANTITY, MoneyError, MoneyErrorCode, NO_CART_TRANSPORT, ORDER_PATH, ORDER_STATE_LABELS, ORDER_STOCK_HOLD, ORDER_TRANSITIONS, OrderActor, OrderEvent, OrderRefusal, OrderSnapshotRefusal, OrderState, PAYMENT_FIELD_LABELS, PAYMENT_METHODS, PaymentChannel, PaymentField, PaymentMethodKind, PaymentProvider, QuantityStep, SAMPLE_CART_LINE, SAMPLE_PRODUCT, SAMPLE_STUDIO, SAMPLE_SWATCHES, SHIPPING_KINDS, SHOP_SLOTS, SHOP_WORDS, SITE_REFUSALS, STOCK_EFFECTS, STOCK_RESERVATION_MINUTES, ShippingField, ShippingMethodKind, ShopSlot, ShopWord, SiteCommerceRoute, SiteRefusalCode, StockEffect, StockHold, VARIANT_NAME_SEPARATOR, VAT_PERCENT_MAX_DECIMALS, addMoney, addressLine, availableShippingMethods, canBuy, canStep, cartCookieName, cartEndpointPath, cartIssueWords, cartLineId, cartOf, cartTransportErrorFor, cartViewOf, catalogKey, checkoutGate, checkoutHref, checkoutWord, chooseValue, clampQuantity, commerceLanguage, currencyExponent, currentCheckoutStep, defaultChoice, emptyCartView, fieldAsked, fieldRequired, findVariant, formatMoney, formatMoneyValue, freeShippingRemaining, furthestStep, includedVat, isCurrencyCode, isMoney, isPaymentMethodKind, isShippingMethodKind, isStorefrontProduct, isVatPercent, labelIn, looksLikeEmail, looksLikePhone, majorToMinor, mergeCarts, migrateMajorPrice, minorToMajor, money, nextOrderState, openingOrderState, optionValueStates, orderHref, orderSnapshot, paymentChannelOf, paymentInstructions, paymentMethodProblems, paymentMethodReady, percentOf, priceCart, productCurrency, productInScope, productOptions, productVariants, quantityBounds, quoteShipping, reservationExpiresAt, sellableQuantity, shippingMethodProblems, shippingMethodReady, shippingNeedsAddress, shopWord, simulatedCartTransport, siteCartView, siteCommercePath, siteRefusalsOf, stepQuantity, stockEffect, storefrontCatalog, storefrontMoney, subtractMoney, timesMoney, usablePaymentMethods, variantChoiceOf, variantSlotOf, variantWords };
2658
+ export { ABANDONED_AFTER_MS, Availability, CART_COOKIE_PREFIX, CART_ISSUE_LABELS, CART_TRANSPORT_ERROR_LABELS, CHECKOUT_FORM_STEPS, CHECKOUT_GATE_RULES, CHECKOUT_PATH, CHECKOUT_STEPS, CHECKOUT_STEP_LABELS, CHECKOUT_WORDS, COUPON_CODE_MAX, COUPON_CODE_MIN, COUPON_REFUSAL_LABELS, CURRENCY_CODES, CURRENCY_EXPONENTS, CartIssueCode, CartTransportError, CartTransportErrorCode, CheckoutAskedField, CheckoutFieldMode, CheckoutGateArea, CheckoutGateCode, CheckoutSlot, CheckoutStep, CheckoutWord, CommerceLanguage, CouponKind, CouponProblem, CouponRefusal, CurrencyCode, DEFAULT_JOURNEY_DAYS, DEFAULT_MONEY_LOCALE, DEFAULT_REMINDER_SETTINGS, DEFAULT_VARIANT_NAME, DeliveryFit, FINAL_ORDER_STATES, FUNNEL_STAGES, FunnelStage, JOURNEY_PERIODS_DAYS, JourneyEventKind, LegalPage, MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY, MAX_VAT_PERCENT, MIN_LINE_QUANTITY, MoneyError, MoneyErrorCode, NO_CART_TRANSPORT, ORDER_PATH, ORDER_STATE_LABELS, ORDER_STOCK_HOLD, ORDER_TRANSITIONS, OrderActor, OrderEvent, OrderRefusal, OrderSnapshotRefusal, OrderState, PAYMENT_FIELD_LABELS, PAYMENT_METHODS, PaymentChannel, PaymentField, PaymentMethodKind, PaymentProvider, QuantityStep, RECOVERY_PATH, RECOVERY_WORDS, REMINDER_LATE_MS, REMINDER_SEQUENCE, REMINDER_STEPS, REMINDER_SUBJECT_WORDS, REMINDER_WORDS_MAX, RecoveryWord, ReminderOutcome, ReminderSkip, ReminderStep, ReminderStop, SAMPLE_CART_LINE, SAMPLE_PRODUCT, SAMPLE_STUDIO, SAMPLE_SWATCHES, SHIPPING_KINDS, SHOP_SLOTS, SHOP_WORDS, SITE_REFUSALS, STOCK_EFFECTS, STOCK_RESERVATION_MINUTES, ShippingField, ShippingMethodKind, ShopSlot, ShopWord, SiteCommerceRoute, SiteRefusalCode, StockEffect, StockHold, UNSUBSCRIBE_PATH, VARIANT_NAME_SEPARATOR, VAT_PERCENT_MAX_DECIMALS, addMoney, addressLine, availableShippingMethods, biggestDrop, canBuy, canStep, cartCookieName, cartEndpointPath, cartIssueWords, cartLineId, cartOf, cartTransportErrorFor, cartViewOf, catalogKey, checkoutGate, checkoutHref, checkoutWord, chooseValue, clampQuantity, commerceLanguage, couponDiscount, couponOfferWords, couponProblems, couponRefusalWords, currencyExponent, currentCheckoutStep, defaultChoice, emptyCartView, fieldAsked, fieldRequired, findVariant, formatMoney, formatMoneyValue, freeShippingRemaining, funnelOf, furthestStep, includedVat, isAbandoned, isCouponCode, isCurrencyCode, isMoney, isPaymentMethodKind, isShippingMethodKind, isStorefrontProduct, isVatPercent, labelIn, looksLikeEmail, looksLikePhone, majorToMinor, marketingAllowed, maskEmail, mergeCarts, migrateMajorPrice, minorToMajor, money, nextOrderState, nextReminder, normalizeCouponCode, openingOrderState, optionValueStates, orderHref, orderSnapshot, paymentChannelOf, paymentInstructions, paymentMethodProblems, paymentMethodReady, percentOf, priceCart, productCurrency, productInScope, productOptions, productVariants, quantityBounds, quoteShipping, recoveryHref, recoveryWord, reminderNumber, reminderSettingsOf, reservationExpiresAt, sellableQuantity, shippingMethodProblems, shippingMethodReady, shippingNeedsAddress, shopWord, simulatedCartTransport, siteCartView, siteCommercePath, siteRefusalsOf, stepQuantity, stockEffect, stoppedAt, storefrontCatalog, storefrontMoney, subtractMoney, timesMoney, unsubscribeHref, usablePaymentMethods, variantChoiceOf, variantSlotOf, variantWords };
2160
2659
  //# sourceMappingURL=vectoriox-iox-ui-commerce-core.mjs.map