@vectoriox/iox-ui 5.102.0 → 5.104.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriox/iox-ui",
3
- "version": "5.102.0",
3
+ "version": "5.104.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -1,6 +1,7 @@
1
1
  import { CatalogEntry, catalogKey } from './catalog';
2
2
  import { Cart, CART_ISSUE_LABELS, cartOf, CartIssue, PricedCart, PricedLine, priceCart, StudioCommerce } from './cart';
3
3
  import { CurrencyCode } from './currency';
4
+ import { AppliedCoupon } from './coupons';
4
5
  import { CommerceLabel, labelIn } from './labels';
5
6
  import { MAX_LINE_QUANTITY } from './limits';
6
7
  import { Money } from './money';
@@ -35,6 +36,9 @@ export interface CartView {
35
36
  count: number;
36
37
  empty: boolean;
37
38
  subtotal: Money | null;
39
+ /** The coupon's discount (E4) — zero, or null on a cart never priced. */
40
+ discount: Money | null;
41
+ coupon: AppliedCoupon | null;
38
42
  total: Money | null;
39
43
  vat: Money | null;
40
44
  vatPercent: number;
@@ -101,7 +105,7 @@ export function checkoutHref(orgLabel?: string | null): string {
101
105
 
102
106
  /** A cart with nothing in it. */
103
107
  export function emptyCartView(currency: CurrencyCode | null = null): CartView {
104
- return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
108
+ return { currency, lines: [], count: 0, empty: true, subtotal: null, discount: null, coupon: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
105
109
  }
106
110
 
107
111
  /** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
@@ -121,6 +125,8 @@ export function cartViewOf(priced: PricedCart, options: {
121
125
  count,
122
126
  empty: lines.length === 0,
123
127
  subtotal: priced.subtotal,
128
+ discount: priced.discount,
129
+ coupon: priced.coupon ?? null,
124
130
  total: priced.total,
125
131
  vat: priced.vat,
126
132
  vatPercent: priced.vatPercent,
@@ -1,4 +1,5 @@
1
1
  import { CatalogEntry, catalogKey, sellableQuantity } from './catalog';
2
+ import { AppliedCoupon, Coupon, couponDiscount, CouponRefusal, normalizeCouponCode } from './coupons';
2
3
  import { CurrencyCode, currencyExponent } from './currency';
3
4
  import { CommerceLabel } from './labels';
4
5
  import { MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY } from './limits';
@@ -26,6 +27,10 @@ export interface StudioCommerce {
26
27
 
27
28
  export interface PricingChoice {
28
29
  shippingMethodId?: string | null;
30
+ /** The buyer's coupon (E4) — the caller looked it up; `priceCart` decides what it gives. */
31
+ coupon?: Coupon | null;
32
+ /** Epoch ms the coupon's dates are judged at (no clock is read here). */
33
+ now?: number | null;
29
34
  }
30
35
 
31
36
  export enum CartIssueCode {
@@ -51,6 +56,8 @@ export enum CartIssueCode {
51
56
  ShippingUnavailable = 'shipping-unavailable',
52
57
  /** The studio's VAT is not a usable rate: the VAT line reads 0. */
53
58
  VatInvalid = 'vat-invalid',
59
+ /** The coupon gives this cart nothing now (expired, used up, under its minimum…): no discount; `couponRefusal` says why. */
60
+ CouponNotApplied = 'coupon-not-applied',
54
61
  }
55
62
 
56
63
  export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> = Object.freeze({
@@ -69,6 +76,7 @@ export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> =
69
76
  [CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
70
77
  [CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
71
78
  [CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
79
+ [CartIssueCode.CouponNotApplied]: { en: 'Your coupon no longer applies to this order and was removed.', he: 'הקופון כבר לא חל על ההזמנה הזו והוסר.' },
72
80
  });
73
81
 
74
82
  export interface CartIssue {
@@ -80,6 +88,9 @@ export interface CartIssue {
80
88
  /** What the priced line holds now (clamped / capped). */
81
89
  quantity?: number;
82
90
  shippingMethodId?: string;
91
+ /** CouponNotApplied: the code and why. */
92
+ coupon?: string;
93
+ couponRefusal?: CouponRefusal;
83
94
  }
84
95
 
85
96
  export interface PricedLine {
@@ -100,8 +111,10 @@ export interface PricedCart {
100
111
  currency: CurrencyCode;
101
112
  lines: PricedLine[];
102
113
  subtotal: Money;
103
- /** Zero until coupons (E4); `total` already subtracts it. */
114
+ /** The coupon's discount on the goods (E4); `total` already subtracts it. */
104
115
  discount: Money;
116
+ /** The coupon that gave `discount`, or null. */
117
+ coupon: AppliedCoupon | null;
105
118
  shipping: Money;
106
119
  shippingMethod: ShippingQuote | null;
107
120
  requiresShipping: boolean;
@@ -196,6 +209,18 @@ function lineTotalWithin(unitPrice: Money, quantity: number, subtotal: Money): M
196
209
  }
197
210
  }
198
211
 
212
+ /** The coupon's discount on the goods — none, and an issue said, when the coupon gives this cart nothing now. */
213
+ function discountOf(choice: PricingChoice | null | undefined, subtotal: Money, issues: CartIssue[]): { discount: Money; coupon: AppliedCoupon | null } {
214
+ const none = { discount: money(0, subtotal.currency), coupon: null };
215
+ if (!choice?.coupon) return none;
216
+ const check = couponDiscount(choice.coupon, subtotal, choice.now);
217
+ if (check.ok === false) {
218
+ issues.push({ code: CartIssueCode.CouponNotApplied, coupon: normalizeCouponCode(choice.coupon.code), couponRefusal: check.refusal });
219
+ return none;
220
+ }
221
+ return { discount: check.discount, coupon: check.applied };
222
+ }
223
+
199
224
  /**
200
225
  * THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
201
226
  * payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
@@ -253,7 +278,7 @@ export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio:
253
278
  });
254
279
  }
255
280
 
256
- const discount = money(0, currency);
281
+ const { discount, coupon } = discountOf(choice, subtotal, issues);
257
282
  const goods = subtractMoney(subtotal, discount);
258
283
  const requiresShipping = lines.some(line => line.requiresShipping);
259
284
  const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
@@ -270,6 +295,7 @@ export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio:
270
295
  lines,
271
296
  subtotal,
272
297
  discount,
298
+ coupon,
273
299
  shipping,
274
300
  shippingMethod,
275
301
  requiresShipping,
@@ -0,0 +1,186 @@
1
+ import { CurrencyCode } from './currency';
2
+ import { CommerceLabel, labelIn } from './labels';
3
+ import { isMoney, money, Money, percentOf } from './money';
4
+
5
+ /**
6
+ * Coupons v1 (commerce plan §3h, E4): a code, a percent or a fixed amount off the GOODS (never the delivery), an
7
+ * optional minimum order, start and end, a uses limit; one per order. `priceCart` is the only place a coupon becomes
8
+ * a discount — iox-cms recomputes it at checkout and when the order is placed (trap T1). Pure: the caller passes `now`.
9
+ */
10
+ export enum CouponKind {
11
+ Percent = 'percent',
12
+ Fixed = 'fixed',
13
+ }
14
+
15
+ export interface Coupon {
16
+ code: string;
17
+ kind: CouponKind;
18
+ /** 1–100, at most two decimals — a Percent coupon's. */
19
+ percent?: number | null;
20
+ /** A Fixed coupon's amount, in the studio currency. */
21
+ amount?: Money | null;
22
+ /** The goods (after nothing else) must come to at least this. */
23
+ minimumOrder?: Money | null;
24
+ /** ISO dates; a missing one is open-ended. */
25
+ startsAt?: string | null;
26
+ expiresAt?: string | null;
27
+ /** Orders it may be used on; null = no limit. */
28
+ maxUses?: number | null;
29
+ /** Orders placed with it so far. */
30
+ uses?: number;
31
+ enabled: boolean;
32
+ }
33
+
34
+ /** What a priced cart says about the coupon it applied (the summary's "Discount · CODE"). */
35
+ export interface AppliedCoupon {
36
+ code: string;
37
+ kind: CouponKind;
38
+ percent: number | null;
39
+ amount: Money | null;
40
+ }
41
+
42
+ export const COUPON_CODE_MIN = 3;
43
+ export const COUPON_CODE_MAX = 32;
44
+ const COUPON_CODE = new RegExp(`^[A-Z0-9][A-Z0-9_-]{${COUPON_CODE_MIN - 1},${COUPON_CODE_MAX - 1}}$`);
45
+ const PERCENT_MAX = 100;
46
+ const PERCENT_DECIMALS = 2;
47
+
48
+ /** A code as it is stored and compared: trimmed, upper-case. A buyer may type `back10` for `BACK10`. */
49
+ export function normalizeCouponCode(value: unknown): string {
50
+ return typeof value === 'string' ? value.trim().toUpperCase() : '';
51
+ }
52
+
53
+ export function isCouponCode(value: unknown): boolean {
54
+ return COUPON_CODE.test(normalizeCouponCode(value));
55
+ }
56
+
57
+ /** What the owner must fix before a coupon may be saved. */
58
+ export enum CouponProblem {
59
+ CodeInvalid = 'code-invalid',
60
+ KindInvalid = 'kind-invalid',
61
+ PercentInvalid = 'percent-invalid',
62
+ AmountInvalid = 'amount-invalid',
63
+ MinimumInvalid = 'minimum-invalid',
64
+ DatesInvalid = 'dates-invalid',
65
+ MaxUsesInvalid = 'max-uses-invalid',
66
+ }
67
+
68
+ const dateOf = (value: unknown): number | null => {
69
+ if (value === null || value === undefined || value === '') return null;
70
+ const at = new Date(value as string).getTime();
71
+ return Number.isFinite(at) ? at : NaN;
72
+ };
73
+
74
+ const percentValid = (value: unknown): boolean => {
75
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > PERCENT_MAX) return false;
76
+ const [, frac = ''] = String(value).split('.');
77
+ return frac.length <= PERCENT_DECIMALS;
78
+ };
79
+
80
+ const positiveMoneyIn = (value: unknown, currency: CurrencyCode): boolean =>
81
+ isMoney(value) && value.currency === currency && value.amount > 0;
82
+
83
+ /** Every reason this coupon cannot be saved for a studio selling in `currency` — empty when it can. */
84
+ export function couponProblems(coupon: Partial<Coupon> | null | undefined, currency: CurrencyCode): CouponProblem[] {
85
+ const c = coupon ?? {};
86
+ const problems: CouponProblem[] = [];
87
+ if (!isCouponCode(c.code)) problems.push(CouponProblem.CodeInvalid);
88
+ if (c.kind === CouponKind.Percent) {
89
+ if (!percentValid(c.percent)) problems.push(CouponProblem.PercentInvalid);
90
+ } else if (c.kind === CouponKind.Fixed) {
91
+ if (!positiveMoneyIn(c.amount, currency)) problems.push(CouponProblem.AmountInvalid);
92
+ } else {
93
+ problems.push(CouponProblem.KindInvalid);
94
+ }
95
+ if (c.minimumOrder !== null && c.minimumOrder !== undefined && !(isMoney(c.minimumOrder) && c.minimumOrder.currency === currency && c.minimumOrder.amount >= 0)) {
96
+ problems.push(CouponProblem.MinimumInvalid);
97
+ }
98
+ const starts = dateOf(c.startsAt);
99
+ const ends = dateOf(c.expiresAt);
100
+ if (Number.isNaN(starts) || Number.isNaN(ends) || (starts !== null && ends !== null && ends <= starts)) problems.push(CouponProblem.DatesInvalid);
101
+ if (c.maxUses !== null && c.maxUses !== undefined && !(Number.isSafeInteger(c.maxUses) && c.maxUses >= 1)) problems.push(CouponProblem.MaxUsesInvalid);
102
+ return problems;
103
+ }
104
+
105
+ /** Why a coupon gives no discount to this cart — each said to the buyer on the coupon field. */
106
+ export enum CouponRefusal {
107
+ Unknown = 'coupon-unknown',
108
+ Disabled = 'coupon-disabled',
109
+ NotStarted = 'coupon-not-started',
110
+ Expired = 'coupon-expired',
111
+ UsedUp = 'coupon-used-up',
112
+ MinimumNotMet = 'coupon-minimum-not-met',
113
+ /** Another currency, or a coupon the owner would not be allowed to save now. */
114
+ NotUsable = 'coupon-not-usable',
115
+ }
116
+
117
+ /** `{amount}` is the minimum order, filled by `couponRefusalWords`. */
118
+ export const COUPON_REFUSAL_LABELS: Readonly<Record<CouponRefusal, CommerceLabel>> = Object.freeze({
119
+ [CouponRefusal.Unknown]: { en: 'This code does not exist. Check it and try again.', he: 'הקוד הזה לא קיים. בדקו אותו ונסו שוב.' },
120
+ [CouponRefusal.Disabled]: { en: 'This code is not active.', he: 'הקוד הזה אינו פעיל.' },
121
+ [CouponRefusal.NotStarted]: { en: 'This code cannot be used yet.', he: 'עדיין אי אפשר להשתמש בקוד הזה.' },
122
+ [CouponRefusal.Expired]: { en: 'This code has expired.', he: 'תוקף הקוד הזה פג.' },
123
+ [CouponRefusal.UsedUp]: { en: 'This code has been used up.', he: 'הקוד הזה נוצל עד תומו.' },
124
+ [CouponRefusal.MinimumNotMet]: { en: 'This code is for orders of {amount} or more.', he: 'הקוד הזה תקף להזמנות של {amount} ומעלה.' },
125
+ [CouponRefusal.NotUsable]: { en: 'This code cannot be used on this order.', he: 'אי אפשר להשתמש בקוד הזה בהזמנה הזו.' },
126
+ });
127
+
128
+ export function couponRefusalWords(refusal: CouponRefusal, lang: string | null | undefined, fill: { amount?: string } = {}): string {
129
+ return labelIn(COUPON_REFUSAL_LABELS[refusal], lang).replace('{amount}', fill.amount ?? '');
130
+ }
131
+
132
+ const COUPON_OFFER_LABELS: Readonly<Record<CouponKind, CommerceLabel>> = Object.freeze({
133
+ [CouponKind.Percent]: { en: '{percent}% off', he: '{percent}% הנחה' },
134
+ [CouponKind.Fixed]: { en: '{amount} off', he: '{amount} הנחה' },
135
+ });
136
+
137
+ /** What a coupon gives, in words ("10% off", "₪50.00 off") — the reminder's offer and the admin's coupon list. */
138
+ export function couponOfferWords(coupon: Pick<Coupon, 'kind' | 'percent' | 'amount'>, lang: string | null | undefined, formatMoney: (value: Money) => string): string {
139
+ const label = COUPON_OFFER_LABELS[coupon.kind];
140
+ if (!label) return '';
141
+ return labelIn(label, lang).replace('{percent}', String(coupon.percent ?? '')).replace('{amount}', coupon.amount ? formatMoney(coupon.amount) : '');
142
+ }
143
+
144
+ export type CouponCheck =
145
+ | { ok: true; discount: Money; applied: AppliedCoupon }
146
+ | { ok: false; refusal: CouponRefusal };
147
+
148
+ interface CouponRule {
149
+ readonly refusal: CouponRefusal;
150
+ readonly refuses: (coupon: Coupon, goods: Money, now: number) => boolean;
151
+ }
152
+
153
+ /** Checked in order; the first that refuses is the one said. */
154
+ const COUPON_RULES: readonly CouponRule[] = Object.freeze([
155
+ { refusal: CouponRefusal.Disabled, refuses: (c: Coupon) => c.enabled !== true },
156
+ { refusal: CouponRefusal.NotUsable, refuses: (c: Coupon, goods: Money) => couponProblems(c, goods.currency).length > 0 },
157
+ { refusal: CouponRefusal.NotStarted, refuses: (c: Coupon, _g: Money, now: number) => dateOf(c.startsAt) !== null && now < (dateOf(c.startsAt) as number) },
158
+ { refusal: CouponRefusal.Expired, refuses: (c: Coupon, _g: Money, now: number) => dateOf(c.expiresAt) !== null && now >= (dateOf(c.expiresAt) as number) },
159
+ { refusal: CouponRefusal.UsedUp, refuses: (c: Coupon) => typeof c.maxUses === 'number' && (c.uses ?? 0) >= c.maxUses },
160
+ { refusal: CouponRefusal.MinimumNotMet, refuses: (c: Coupon, goods: Money) => !!c.minimumOrder && goods.amount < c.minimumOrder.amount },
161
+ ]);
162
+
163
+ /**
164
+ * The discount `coupon` gives goods worth `goods` at `now`: a percent of them (rounded once, half to even) or the
165
+ * fixed amount, never more than the goods themselves. No clock is read: a missing `now` refuses a dated coupon.
166
+ */
167
+ export function couponDiscount(coupon: Coupon | null | undefined, goods: Money, now: number | null | undefined): CouponCheck {
168
+ if (!coupon) return { ok: false, refusal: CouponRefusal.Unknown };
169
+ const at = typeof now === 'number' && Number.isFinite(now) ? now : NaN;
170
+ const dated = dateOf(coupon.startsAt) !== null || dateOf(coupon.expiresAt) !== null;
171
+ if (dated && Number.isNaN(at)) return { ok: false, refusal: CouponRefusal.NotUsable };
172
+ const refused = COUPON_RULES.find(rule => rule.refuses(coupon, goods, at));
173
+ if (refused) return { ok: false, refusal: refused.refusal };
174
+ const raw = coupon.kind === CouponKind.Percent ? percentOf(goods, coupon.percent as number) : (coupon.amount as Money);
175
+ const discount = money(Math.min(raw.amount, goods.amount), goods.currency);
176
+ return {
177
+ ok: true,
178
+ discount,
179
+ applied: {
180
+ code: normalizeCouponCode(coupon.code),
181
+ kind: coupon.kind,
182
+ percent: coupon.kind === CouponKind.Percent ? (coupon.percent as number) : null,
183
+ amount: coupon.kind === CouponKind.Fixed ? money((coupon.amount as Money).amount, goods.currency) : null,
184
+ },
185
+ };
186
+ }
@@ -51,6 +51,8 @@ export interface OrderSnapshot {
51
51
  readonly lines: readonly OrderSnapshotLine[];
52
52
  readonly subtotal: Money;
53
53
  readonly discount: Money;
54
+ /** The coupon code the discount came from (E4), or null. */
55
+ readonly coupon: { readonly code: string } | null;
54
56
  readonly shipping: Money;
55
57
  readonly delivery: { readonly methodId: string; readonly kind: ShippingMethodKind; readonly name: string } | null;
56
58
  readonly total: Money;
@@ -130,6 +132,7 @@ export function orderSnapshot(pricedCart: PricedCart, payment: PaymentMethodConf
130
132
  })),
131
133
  subtotal: copyMoney(pricedCart.subtotal),
132
134
  discount: copyMoney(pricedCart.discount),
135
+ coupon: pricedCart.coupon ? { code: pricedCart.coupon.code } : null,
133
136
  shipping: copyMoney(pricedCart.shipping),
134
137
  delivery: delivery ? { methodId: delivery.methodId, kind: delivery.kind, name: delivery.name } : null,
135
138
  total: copyMoney(pricedCart.total),
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms compute the same
5
5
  * totals (trap T6: never a float). E0 shipped Money; E1a adds the cart and its ONE pricing function, shipping v1,
6
- * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot. No clock is
6
+ * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot; E4 adds
7
+ * coupons (one per order, priced by `priceCart`) and the journey: reminders, the consent gate, the funnel. No clock is
7
8
  * read anywhere — a caller passes `now`.
8
9
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
9
10
  * jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
@@ -15,7 +16,9 @@ export * from './labels';
15
16
  export * from './limits';
16
17
  export * from './vat';
17
18
  export * from './catalog';
19
+ export * from './storefront-fields';
18
20
  export * from './shipping';
21
+ export * from './coupons';
19
22
  export * from './cart';
20
23
  export * from './payments';
21
24
  export * from './orders';
@@ -26,4 +29,5 @@ export * from './quantity';
26
29
  export * from './cart-transport';
27
30
  export * from './shop-display';
28
31
  export * from './site-checkout';
32
+ export * from './recovery';
29
33
  export { looksLikeEmail, looksLikePhone } from './text';