@vectoriox/iox-ui 5.92.0 → 5.94.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.
@@ -0,0 +1,196 @@
1
+ import { CommerceLabel, CommerceLanguage, commerceLanguage, labelIn } from './labels';
2
+ import { formatMoney, Money } from './money';
3
+ import { isShippingMethodKind, ShippingMethodKind, SHIPPING_KINDS } from './shipping';
4
+ import { filled, looksLikeIsraeliMobile } from './text';
5
+
6
+ export enum PaymentChannel {
7
+ /** The owner marks the order paid (C-D11). */
8
+ Manual = 'manual',
9
+ /** The studio's PSP; only its verified callback marks the order paid. */
10
+ Online = 'online',
11
+ }
12
+
13
+ export enum PaymentMethodKind {
14
+ BankTransfer = 'bankTransfer',
15
+ PayOnPickup = 'payOnPickup',
16
+ CashOnDelivery = 'cashOnDelivery',
17
+ Bit = 'bit',
18
+ /** A PSP's hosted page (E2, Cardcom first) — typed now, not offered yet. */
19
+ Online = 'online',
20
+ }
21
+
22
+ export enum PaymentProvider {
23
+ Cardcom = 'cardcom',
24
+ }
25
+
26
+ /** What an owner fills for a method. */
27
+ export enum PaymentField {
28
+ AccountName = 'accountName',
29
+ Bank = 'bank',
30
+ Branch = 'branch',
31
+ AccountNumber = 'accountNumber',
32
+ BitPhone = 'bitPhone',
33
+ Provider = 'provider',
34
+ }
35
+
36
+ /** Which deliveries a method can be used with. */
37
+ export enum DeliveryFit {
38
+ Any = 'any',
39
+ /** Paid at the counter: only with a pickup method. */
40
+ PickupOnly = 'pickupOnly',
41
+ /** Paid to the courier: only with a method that delivers to an address. */
42
+ AddressOnly = 'addressOnly',
43
+ }
44
+
45
+ interface PaymentMethodRule {
46
+ readonly channel: PaymentChannel;
47
+ /** false = typed for a later phase, never shown to a buyer. */
48
+ readonly offered: boolean;
49
+ readonly fields: readonly PaymentField[];
50
+ readonly fit: DeliveryFit;
51
+ readonly label: CommerceLabel;
52
+ /** What the buyer reads after placing the order; `{total}`, `{orderNumber}` and the method's fields fill in. */
53
+ readonly instructions: CommerceLabel;
54
+ }
55
+
56
+ export const PAYMENT_METHODS: Readonly<Record<PaymentMethodKind, PaymentMethodRule>> = Object.freeze({
57
+ [PaymentMethodKind.BankTransfer]: {
58
+ channel: PaymentChannel.Manual,
59
+ offered: true,
60
+ fields: [PaymentField.AccountName, PaymentField.Bank, PaymentField.Branch, PaymentField.AccountNumber],
61
+ fit: DeliveryFit.Any,
62
+ label: { en: 'Bank transfer', he: 'העברה בנקאית' },
63
+ instructions: {
64
+ en: 'Transfer {total} to {accountName}, bank {bank}, branch {branch}, account {accountNumber}. Write order {orderNumber} in the transfer\'s reference. We will confirm your order once the money arrives.',
65
+ he: 'העבירו {total} לחשבון על שם {accountName}, בנק {bank}, סניף {branch}, חשבון {accountNumber}. ציינו את מספר ההזמנה {orderNumber} בפרטי ההעברה. נאשר את ההזמנה כשהכסף יגיע.',
66
+ },
67
+ },
68
+ [PaymentMethodKind.PayOnPickup]: {
69
+ channel: PaymentChannel.Manual,
70
+ offered: true,
71
+ fields: [],
72
+ fit: DeliveryFit.PickupOnly,
73
+ label: { en: 'Pay on pickup', he: 'תשלום באיסוף' },
74
+ instructions: {
75
+ en: 'Pay {total} when you pick up order {orderNumber}.',
76
+ he: 'שלמו {total} כשאתם אוספים את הזמנה {orderNumber}.',
77
+ },
78
+ },
79
+ [PaymentMethodKind.CashOnDelivery]: {
80
+ channel: PaymentChannel.Manual,
81
+ offered: true,
82
+ fields: [],
83
+ fit: DeliveryFit.AddressOnly,
84
+ label: { en: 'Cash on delivery', he: 'מזומן במסירה' },
85
+ instructions: {
86
+ en: 'Pay {total} in cash when order {orderNumber} is delivered.',
87
+ he: 'שלמו {total} במזומן כשהזמנה {orderNumber} נמסרת לכם.',
88
+ },
89
+ },
90
+ [PaymentMethodKind.Bit]: {
91
+ channel: PaymentChannel.Manual,
92
+ offered: true,
93
+ fields: [PaymentField.BitPhone],
94
+ fit: DeliveryFit.Any,
95
+ label: { en: 'Bit', he: 'ביט' },
96
+ instructions: {
97
+ en: 'Send {total} with Bit to {bitPhone}. Write order {orderNumber} in the note. We will confirm your order once the payment arrives.',
98
+ he: 'שלחו {total} בביט למספר {bitPhone}. ציינו את מספר ההזמנה {orderNumber} בהערה. נאשר את ההזמנה כשהתשלום יגיע.',
99
+ },
100
+ },
101
+ [PaymentMethodKind.Online]: {
102
+ channel: PaymentChannel.Online,
103
+ offered: false,
104
+ fields: [PaymentField.Provider],
105
+ fit: DeliveryFit.Any,
106
+ label: { en: 'Card', he: 'כרטיס אשראי' },
107
+ instructions: {
108
+ en: 'You will pay {total} for order {orderNumber} on a secure payment page.',
109
+ he: 'תשלמו {total} עבור הזמנה {orderNumber} בעמוד תשלום מאובטח.',
110
+ },
111
+ },
112
+ });
113
+
114
+ export const PAYMENT_FIELD_LABELS: Readonly<Record<PaymentField, CommerceLabel>> = Object.freeze({
115
+ [PaymentField.AccountName]: { en: 'Account holder', he: 'שם בעל החשבון' },
116
+ [PaymentField.Bank]: { en: 'Bank', he: 'בנק' },
117
+ [PaymentField.Branch]: { en: 'Branch', he: 'סניף' },
118
+ [PaymentField.AccountNumber]: { en: 'Account number', he: 'מספר חשבון' },
119
+ [PaymentField.BitPhone]: { en: 'Phone number for Bit', he: 'מספר טלפון לביט' },
120
+ [PaymentField.Provider]: { en: 'Payment provider', he: 'ספק סליקה' },
121
+ });
122
+
123
+ const isPaymentProvider = (value: unknown): boolean =>
124
+ typeof value === 'string' && (Object.values(PaymentProvider) as string[]).includes(value);
125
+
126
+ const PAYMENT_FIELD_CHECKS: Readonly<Record<PaymentField, (value: unknown) => boolean>> = Object.freeze({
127
+ [PaymentField.AccountName]: filled,
128
+ [PaymentField.Bank]: filled,
129
+ [PaymentField.Branch]: filled,
130
+ [PaymentField.AccountNumber]: filled,
131
+ [PaymentField.BitPhone]: looksLikeIsraeliMobile,
132
+ [PaymentField.Provider]: isPaymentProvider,
133
+ });
134
+
135
+ const DELIVERY_FITS: Readonly<Record<DeliveryFit, (kind: ShippingMethodKind | null) => boolean>> = Object.freeze({
136
+ [DeliveryFit.Any]: () => true,
137
+ [DeliveryFit.PickupOnly]: (kind: ShippingMethodKind | null) => kind === ShippingMethodKind.Pickup,
138
+ [DeliveryFit.AddressOnly]: (kind: ShippingMethodKind | null) => !!kind && isShippingMethodKind(kind) && SHIPPING_KINDS[kind].needsAddress,
139
+ });
140
+
141
+ export interface PaymentMethodConfig {
142
+ kind: PaymentMethodKind;
143
+ enabled: boolean;
144
+ details?: Partial<Record<PaymentField, string>> | null;
145
+ /** The owner's own words, shown after the instructions. */
146
+ note?: string | null;
147
+ }
148
+
149
+ export const isPaymentMethodKind = (value: unknown): value is PaymentMethodKind =>
150
+ typeof value === 'string' && Object.prototype.hasOwnProperty.call(PAYMENT_METHODS, value);
151
+
152
+ export function paymentChannelOf(kind: PaymentMethodKind): PaymentChannel {
153
+ return PAYMENT_METHODS[kind].channel;
154
+ }
155
+
156
+ /** The fields a method lacks or holds in a form it cannot be paid with. */
157
+ export function paymentMethodProblems(config: PaymentMethodConfig): PaymentField[] {
158
+ if (!config || !isPaymentMethodKind(config.kind)) return [];
159
+ const details = config.details ?? {};
160
+ return PAYMENT_METHODS[config.kind].fields.filter(field => !PAYMENT_FIELD_CHECKS[field](details[field]));
161
+ }
162
+
163
+ /** Enabled, offered in this phase, complete: the ONE rule the checkout and its gate read. */
164
+ export function paymentMethodReady(config: PaymentMethodConfig): boolean {
165
+ return !!config && isPaymentMethodKind(config.kind) && config.enabled === true
166
+ && PAYMENT_METHODS[config.kind].offered && paymentMethodProblems(config).length === 0;
167
+ }
168
+
169
+ /** The methods a buyer may pick with this delivery (null = nothing ships). */
170
+ export function usablePaymentMethods(configs: readonly PaymentMethodConfig[], shippingKind?: ShippingMethodKind | null): PaymentMethodConfig[] {
171
+ const seen = new Set<PaymentMethodKind>();
172
+ const list: readonly PaymentMethodConfig[] = Array.isArray(configs) ? configs : [];
173
+ return list.filter(config =>
174
+ paymentMethodReady(config)
175
+ && DELIVERY_FITS[PAYMENT_METHODS[config.kind].fit](shippingKind ?? null)
176
+ && !seen.has(config.kind) && !!seen.add(config.kind));
177
+ }
178
+
179
+ const LOCALES: Readonly<Record<CommerceLanguage, string>> = Object.freeze({ [CommerceLanguage.En]: 'en-US', [CommerceLanguage.He]: 'he-IL' });
180
+
181
+ /** What the buyer is told to do, in their language: the method's sentence with the order, the amount and the owner's details, then the owner's note. */
182
+ export function paymentInstructions(
183
+ config: PaymentMethodConfig,
184
+ order: { orderNumber: string; total: Money },
185
+ lang: string | null | undefined,
186
+ locale?: string,
187
+ ): string {
188
+ const rule = PAYMENT_METHODS[config.kind];
189
+ const values: Record<string, string> = {
190
+ ...(config.details ?? {}),
191
+ orderNumber: order.orderNumber,
192
+ total: formatMoney(order.total, locale ?? LOCALES[commerceLanguage(lang)]),
193
+ };
194
+ const sentence = labelIn(rule.instructions, lang).replace(/\{(\w+)\}/g, (_match, name: string) => values[name] ?? '');
195
+ return filled(config.note) ? `${sentence}\n${config.note.trim()}` : sentence;
196
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7…C-D11, C-D19).
3
+ *
4
+ * Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms compute the same
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
7
+ * read anywhere — a caller passes `now`.
8
+ * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
9
+ * jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
10
+ */
11
+ export * from './money-error';
12
+ export * from './currency';
13
+ export * from './money';
14
+ export * from './labels';
15
+ export * from './limits';
16
+ export * from './vat';
17
+ export * from './catalog';
18
+ export * from './shipping';
19
+ export * from './cart';
20
+ export * from './payments';
21
+ export * from './orders';
22
+ export * from './checkout';
23
+ export * from './order-snapshot';
@@ -0,0 +1,168 @@
1
+ import { CurrencyCode } from './currency';
2
+ import { CommerceLabel } from './labels';
3
+ import { MAX_CART_AMOUNT } from './limits';
4
+ import { isMoney, money, Money, subtractMoney } from './money';
5
+ import { filled } from './text';
6
+
7
+ /** Shipping v1 (C-D9): methods per studio, one country. Zones and weights come later. */
8
+ export enum ShippingMethodKind {
9
+ Pickup = 'pickup',
10
+ Flat = 'flat',
11
+ /** A flat price that becomes free once the goods reach `freeOver`. */
12
+ FreeOver = 'freeOver',
13
+ /** No address, nothing shipped — offered only when nothing in the cart ships. */
14
+ Digital = 'digital',
15
+ }
16
+
17
+ /** What an owner must fill for a method of a kind. */
18
+ export enum ShippingField {
19
+ Price = 'price',
20
+ FreeOver = 'freeOver',
21
+ PickupAddress = 'pickupAddress',
22
+ }
23
+
24
+ export interface ShippingMethod {
25
+ id: string;
26
+ kind: ShippingMethodKind;
27
+ name: string;
28
+ enabled: boolean;
29
+ price?: Money | null;
30
+ freeOver?: Money | null;
31
+ pickupAddress?: string | null;
32
+ pickupHours?: string | null;
33
+ }
34
+
35
+ interface ShippingKindRule {
36
+ readonly needsAddress: boolean;
37
+ /** Offered for a cart where something ships (true) or for one where nothing does (false). */
38
+ readonly forPhysical: boolean;
39
+ readonly requires: readonly ShippingField[];
40
+ readonly price: (method: ShippingMethod, goods: Money) => Money;
41
+ readonly label: CommerceLabel;
42
+ }
43
+
44
+ const zero = (goods: Money): Money => money(0, goods.currency);
45
+
46
+ export const SHIPPING_KINDS: Readonly<Record<ShippingMethodKind, ShippingKindRule>> = Object.freeze({
47
+ [ShippingMethodKind.Pickup]: {
48
+ needsAddress: false,
49
+ forPhysical: true,
50
+ requires: [ShippingField.PickupAddress],
51
+ price: (_method: ShippingMethod, goods: Money) => zero(goods),
52
+ label: { en: 'Pickup', he: 'איסוף עצמי' },
53
+ },
54
+ [ShippingMethodKind.Flat]: {
55
+ needsAddress: true,
56
+ forPhysical: true,
57
+ requires: [ShippingField.Price],
58
+ price: (method: ShippingMethod) => method.price as Money,
59
+ label: { en: 'Flat-rate delivery', he: 'משלוח במחיר קבוע' },
60
+ },
61
+ [ShippingMethodKind.FreeOver]: {
62
+ needsAddress: true,
63
+ forPhysical: true,
64
+ requires: [ShippingField.Price, ShippingField.FreeOver],
65
+ price: (method: ShippingMethod, goods: Money) =>
66
+ goods.amount >= (method.freeOver as Money).amount ? zero(goods) : (method.price as Money),
67
+ label: { en: 'Delivery, free over an amount', he: 'משלוח, חינם מעל סכום' },
68
+ },
69
+ [ShippingMethodKind.Digital]: {
70
+ needsAddress: false,
71
+ forPhysical: false,
72
+ requires: [],
73
+ price: (_method: ShippingMethod, goods: Money) => zero(goods),
74
+ label: { en: 'Digital — nothing shipped', he: 'דיגיטלי — ללא משלוח' },
75
+ },
76
+ });
77
+
78
+ const validAmount = (value: unknown, currency: CurrencyCode): boolean =>
79
+ isMoney(value) && value.currency === currency && value.amount >= 0 && value.amount <= MAX_CART_AMOUNT;
80
+
81
+ const SHIPPING_FIELD_CHECKS: Readonly<Record<ShippingField, (method: ShippingMethod, currency: CurrencyCode) => boolean>> = Object.freeze({
82
+ [ShippingField.Price]: (method: ShippingMethod, currency: CurrencyCode) => validAmount(method.price, currency),
83
+ [ShippingField.FreeOver]: (method: ShippingMethod, currency: CurrencyCode) => validAmount(method.freeOver, currency),
84
+ [ShippingField.PickupAddress]: (method: ShippingMethod) => filled(method.pickupAddress),
85
+ });
86
+
87
+ export const isShippingMethodKind = (value: unknown): value is ShippingMethodKind =>
88
+ typeof value === 'string' && Object.prototype.hasOwnProperty.call(SHIPPING_KINDS, value);
89
+
90
+ export function shippingNeedsAddress(kind: ShippingMethodKind): boolean {
91
+ return isShippingMethodKind(kind) && SHIPPING_KINDS[kind].needsAddress;
92
+ }
93
+
94
+ /** The fields a method lacks (or holds in another currency) — empty = it can be offered. */
95
+ export function shippingMethodProblems(method: ShippingMethod, currency: CurrencyCode): ShippingField[] {
96
+ if (!method || !isShippingMethodKind(method.kind)) return [ShippingField.Price];
97
+ return SHIPPING_KINDS[method.kind].requires.filter(field => !SHIPPING_FIELD_CHECKS[field](method, currency));
98
+ }
99
+
100
+ /** Enabled, complete, with an id and a name: the ONE rule both the offer and the checkout gate read. */
101
+ export function shippingMethodReady(method: ShippingMethod, currency: CurrencyCode): boolean {
102
+ return !!method && method.enabled === true && filled(method.id) && filled(method.name)
103
+ && shippingMethodProblems(method, currency).length === 0;
104
+ }
105
+
106
+ export interface ShippingQuote {
107
+ methodId: string;
108
+ kind: ShippingMethodKind;
109
+ name: string;
110
+ price: Money;
111
+ /** A free-over method whose threshold the goods reached. */
112
+ free: boolean;
113
+ needsAddress: boolean;
114
+ }
115
+
116
+ /** What a quote reads of a cart. */
117
+ export interface ShippingGoods {
118
+ currency: CurrencyCode;
119
+ /** The goods after discounts — what a free-over threshold is compared with. */
120
+ goods: Money;
121
+ requiresShipping: boolean;
122
+ lineCount: number;
123
+ }
124
+
125
+ /** The part of a `PricedCart` the offer reads. */
126
+ export interface ShippingCart {
127
+ currency: CurrencyCode;
128
+ subtotal: Money;
129
+ discount: Money;
130
+ requiresShipping: boolean;
131
+ lines: readonly unknown[];
132
+ }
133
+
134
+ export function quoteShipping(methods: readonly ShippingMethod[], cart: ShippingGoods): ShippingQuote[] {
135
+ const list: readonly ShippingMethod[] = Array.isArray(methods) ? methods : [];
136
+ if (!cart.lineCount) return [];
137
+ const seen = new Set<string>();
138
+ return list
139
+ .filter(method => shippingMethodReady(method, cart.currency)
140
+ && SHIPPING_KINDS[method.kind].forPhysical === cart.requiresShipping
141
+ && !seen.has(method.id) && !!seen.add(method.id))
142
+ .map(method => {
143
+ const rule = SHIPPING_KINDS[method.kind];
144
+ const price = rule.price(method, cart.goods);
145
+ return {
146
+ methodId: method.id,
147
+ kind: method.kind,
148
+ name: method.name,
149
+ price: money(price.amount, price.currency),
150
+ free: method.kind === ShippingMethodKind.FreeOver && price.amount === 0,
151
+ needsAddress: rule.needsAddress,
152
+ };
153
+ });
154
+ }
155
+
156
+ /**
157
+ * The methods a buyer may choose for this cart, each priced for it (free over: free when the goods after
158
+ * discounts are AT or above the threshold). A cart where nothing ships is offered Digital methods only; a cart
159
+ * where anything ships never is.
160
+ */
161
+ export function availableShippingMethods(methods: readonly ShippingMethod[], pricedCart: ShippingCart): ShippingQuote[] {
162
+ return quoteShipping(methods, {
163
+ currency: pricedCart.currency,
164
+ goods: subtractMoney(pricedCart.subtotal, pricedCart.discount),
165
+ requiresShipping: pricedCart.requiresShipping,
166
+ lineCount: pricedCart.lines.length,
167
+ });
168
+ }
@@ -0,0 +1,13 @@
1
+ export const filled = (value: unknown): value is string => typeof value === 'string' && value.trim() !== '';
2
+
3
+ export const looksLikeEmail = (value: unknown): boolean => filled(value) && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
4
+
5
+ export const digitsOf = (value: unknown): string => (typeof value === 'string' ? value.replace(/\D/g, '') : '');
6
+
7
+ /** A phone a person can be called on: 7–15 digits once spaces, dashes, brackets and a leading + are dropped. */
8
+ export const looksLikePhone = (value: unknown): boolean =>
9
+ filled(value) && /^\+?[\d\s\-().]+$/.test(value.trim()) && digitsOf(value).length >= 7 && digitsOf(value).length <= 15;
10
+
11
+ /** An Israeli mobile number (Bit sends to one): 05X-XXXXXXX, or +972 5X-XXXXXXX. */
12
+ export const looksLikeIsraeliMobile = (value: unknown): boolean =>
13
+ filled(value) && /^\+?[\d\s\-().]+$/.test(value.trim()) && /^(?:9725|05)\d{8}$/.test(digitsOf(value));
@@ -0,0 +1,38 @@
1
+ import { currencyExponent } from './currency';
2
+ import { decimalToScaledInteger, DecimalRounding, mulDivHalfEven, parseDecimal } from './decimal';
3
+ import { Money } from './money';
4
+ import { MoneyError, MoneyErrorCode } from './money-error';
5
+
6
+ export const MAX_VAT_PERCENT = 100;
7
+ /** 17, 18, 7.7, 8.1 — four decimals is more than any rate in force; it also keeps the arithmetic below 2^53. */
8
+ export const VAT_PERCENT_MAX_DECIMALS = 4;
9
+
10
+ export function isVatPercent(value: unknown): value is number {
11
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > MAX_VAT_PERCENT) return false;
12
+ const decimal = parseDecimal(String(value));
13
+ return !!decimal && decimal.frac.length <= VAT_PERCENT_MAX_DECIMALS;
14
+ }
15
+
16
+ /**
17
+ * The VAT a VAT-INCLUSIVE amount already holds (C-D8): amount × v / (100 + v), rounded ONCE to a minor unit,
18
+ * half-to-even. Exact: v is read as the integer R = v·10^s (s ≤ 4 decimals), so the share is
19
+ * amount × R / (100·10^s + R) in whole numbers. 118.00 at 18 % → 18.00; 100.00 at 17 % → 14.53.
20
+ */
21
+ export function includedVat(total: Money, vatPercent: number): Money {
22
+ currencyExponent(total.currency);
23
+ if (typeof total.amount !== 'number' || !Number.isSafeInteger(total.amount)) {
24
+ throw new MoneyError(MoneyErrorCode.NotInteger, `total must be a whole number of minor units, got ${String(total.amount)}`);
25
+ }
26
+ if (!isVatPercent(vatPercent)) {
27
+ throw new MoneyError(MoneyErrorCode.OutOfRange, `VAT must be 0–${MAX_VAT_PERCENT} with at most ${VAT_PERCENT_MAX_DECIMALS} decimals, got ${String(vatPercent)}`);
28
+ }
29
+ const decimal = parseDecimal(String(vatPercent))!;
30
+ const scale = decimal.frac.length;
31
+ const rate = decimalToScaledInteger(decimal, scale, DecimalRounding.Exact);
32
+ const magnitude = Math.abs(total.amount);
33
+ if (magnitude > Number.MAX_SAFE_INTEGER / 2) {
34
+ throw new MoneyError(MoneyErrorCode.Overflow, 'Amount is beyond the range VAT is computed for');
35
+ }
36
+ const share = mulDivHalfEven(magnitude, rate, 100 * 10 ** scale + rate);
37
+ return { amount: total.amount < 0 && share !== 0 ? -share : share, currency: total.currency };
38
+ }