@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,106 @@
1
+ import { MoneyError, MoneyErrorCode } from './money-error';
2
+
3
+ export interface DecimalDigits {
4
+ negative: boolean;
5
+ int: string;
6
+ frac: string;
7
+ }
8
+
9
+ export enum DecimalRounding {
10
+ Exact = 'exact',
11
+ HalfEven = 'half-even',
12
+ }
13
+
14
+ const DECIMAL = /^([+-])?(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d{1,3}))?$/;
15
+
16
+ /** Plain decimal text, or the e-notation `String(number)` produces below 1e-6 and from 1e21. */
17
+ export function parseDecimal(text: string): DecimalDigits | null {
18
+ const match = DECIMAL.exec(text);
19
+ if (!match) return null;
20
+ const int = match[2] ?? '';
21
+ const frac = match[3] ?? '';
22
+ if (!int && !frac) return null;
23
+ const digits = int + frac;
24
+ const point = int.length + Number(match[4] ?? 0);
25
+ const shiftedInt = point <= 0 ? '' : point >= digits.length ? digits + '0'.repeat(point - digits.length) : digits.slice(0, point);
26
+ const shiftedFrac = point <= 0 ? '0'.repeat(-point) + digits : point >= digits.length ? '' : digits.slice(point);
27
+ return {
28
+ negative: match[1] === '-',
29
+ int: shiftedInt.replace(/^0+/, ''),
30
+ frac: shiftedFrac.replace(/0+$/, ''),
31
+ };
32
+ }
33
+
34
+ function safeFromDigits(digits: string): number {
35
+ const trimmed = digits.replace(/^0+/, '') || '0';
36
+ const value = trimmed.length > 16 ? Infinity : Number(trimmed);
37
+ if (!Number.isSafeInteger(value)) {
38
+ throw new MoneyError(MoneyErrorCode.Overflow, `${digits} is beyond the safe integer range`);
39
+ }
40
+ return value;
41
+ }
42
+
43
+ /** Scales a parsed decimal by 10^exponent into an integer, without ever touching a float. */
44
+ export function decimalToScaledInteger(decimal: DecimalDigits, exponent: number, rounding: DecimalRounding): number {
45
+ const kept = decimal.frac.slice(0, exponent);
46
+ const rest = decimal.frac.slice(exponent);
47
+ if (rest && rounding === DecimalRounding.Exact) {
48
+ throw new MoneyError(MoneyErrorCode.TooManyDecimals, `More than ${exponent} decimal digits`);
49
+ }
50
+ let magnitude = safeFromDigits(decimal.int + kept.padEnd(exponent, '0'));
51
+ if (rest) {
52
+ const first = Number(rest[0]);
53
+ const tie = first === 5 && /^5$/.test(rest);
54
+ const up = first > 5 || (first === 5 && !tie) || (tie && magnitude % 2 === 1);
55
+ if (up) magnitude += 1;
56
+ if (!Number.isSafeInteger(magnitude)) {
57
+ throw new MoneyError(MoneyErrorCode.Overflow, 'Rounded value is beyond the safe integer range');
58
+ }
59
+ }
60
+ return decimal.negative && magnitude !== 0 ? -magnitude : magnitude;
61
+ }
62
+
63
+ /** Integer division rounded half-to-even; numerator ≥ 0, denominator > 0, both safe integers. */
64
+ export function divideHalfEven(numerator: number, denominator: number): number {
65
+ let quotient = Math.trunc(numerator / denominator);
66
+ let remainder = numerator - quotient * denominator;
67
+ while (remainder < 0) {
68
+ quotient -= 1;
69
+ remainder += denominator;
70
+ }
71
+ while (remainder >= denominator) {
72
+ quotient += 1;
73
+ remainder -= denominator;
74
+ }
75
+ const twice = remainder * 2;
76
+ if (twice > denominator || (twice === denominator && quotient % 2 === 1)) quotient += 1;
77
+ return quotient;
78
+ }
79
+
80
+ /** Integer division that never trusts the float quotient: trunc, then corrected by the remainder. */
81
+ function divMod(numerator: number, denominator: number): [number, number] {
82
+ let quotient = Math.trunc(numerator / denominator);
83
+ let remainder = numerator - quotient * denominator;
84
+ while (remainder < 0) {
85
+ quotient -= 1;
86
+ remainder += denominator;
87
+ }
88
+ while (remainder >= denominator) {
89
+ quotient += 1;
90
+ remainder -= denominator;
91
+ }
92
+ return [quotient, remainder];
93
+ }
94
+
95
+ /**
96
+ * round-half-even(a × b / d) for a, b ≥ 0 and d > b, without forming a × b (it can pass 2^53): a = q·d + r, so
97
+ * a·b/d = q·b + r·b/d, where q·b < a and r·b < d·b — callers keep d·b a safe integer.
98
+ */
99
+ export function mulDivHalfEven(a: number, b: number, d: number): number {
100
+ const [q, r] = divMod(a, d);
101
+ const [f, rest] = divMod(r * b, d);
102
+ let result = q * b + f;
103
+ const twice = rest * 2;
104
+ if (twice > d || (twice === d && result % 2 === 1)) result += 1;
105
+ return result;
106
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The words a refusal or a state is shown with. A string-rendered site and iox-cms's emails have no translation
3
+ * service, so the core carries English and Hebrew itself (the `blurbHe` / `sentWord` precedent); a host with its
4
+ * own translations may key them by the stable code instead.
5
+ */
6
+ export enum CommerceLanguage {
7
+ En = 'en',
8
+ He = 'he',
9
+ }
10
+
11
+ export interface CommerceLabel {
12
+ readonly en: string;
13
+ readonly he: string;
14
+ }
15
+
16
+ const LANGUAGE_ALIASES: Readonly<Record<string, CommerceLanguage>> = Object.freeze({
17
+ en: CommerceLanguage.En,
18
+ he: CommerceLanguage.He,
19
+ iw: CommerceLanguage.He,
20
+ });
21
+
22
+ export function commerceLanguage(lang: string | null | undefined): CommerceLanguage {
23
+ const primary = String(lang ?? '').trim().toLowerCase().split(/[-_]/)[0];
24
+ return LANGUAGE_ALIASES[primary] ?? CommerceLanguage.En;
25
+ }
26
+
27
+ export function labelIn(label: CommerceLabel, lang: string | null | undefined): string {
28
+ return label[commerceLanguage(lang)];
29
+ }
@@ -0,0 +1,9 @@
1
+ /** A cart holds at most this many distinct lines; more are dropped (`too-many-lines`). */
2
+ export const MAX_CART_LINES = 100;
3
+ /** One line's quantity is capped here (`quantity-capped`), before stock. */
4
+ export const MAX_LINE_QUANTITY = 999;
5
+ /**
6
+ * The largest subtotal, shipping price or threshold, in minor units. Subtotal + shipping stays far below 2^53, and
7
+ * the included-VAT arithmetic never forms a product past it.
8
+ */
9
+ export const MAX_CART_AMOUNT = 10 ** 15;
@@ -0,0 +1,19 @@
1
+ export enum MoneyErrorCode {
2
+ UnknownCurrency = 'unknown-currency',
3
+ NotMoney = 'not-money',
4
+ NotInteger = 'not-integer',
5
+ NotANumber = 'not-a-number',
6
+ TooManyDecimals = 'too-many-decimals',
7
+ CurrencyMismatch = 'currency-mismatch',
8
+ NotWhole = 'not-whole',
9
+ Negative = 'negative',
10
+ Overflow = 'overflow',
11
+ OutOfRange = 'out-of-range',
12
+ }
13
+
14
+ export class MoneyError extends Error {
15
+ constructor(readonly code: MoneyErrorCode, message: string) {
16
+ super(message);
17
+ this.name = 'MoneyError';
18
+ }
19
+ }
@@ -0,0 +1,159 @@
1
+ import { CurrencyCode, currencyExponent, isCurrencyCode } from './currency';
2
+ import { DecimalRounding, decimalToScaledInteger, divideHalfEven, parseDecimal } from './decimal';
3
+ import { MoneyError, MoneyErrorCode } from './money-error';
4
+
5
+ export interface Money {
6
+ /** Integer minor units (agorot, cents, fils…). */
7
+ amount: number;
8
+ currency: CurrencyCode;
9
+ }
10
+
11
+ const MAX_PERCENT_DECIMALS = 6;
12
+
13
+ export function isMoney(value: unknown): value is Money {
14
+ if (typeof value !== 'object' || value === null) return false;
15
+ const record = value as Record<string, unknown>;
16
+ return Number.isSafeInteger(record['amount']) && isCurrencyCode(record['currency']);
17
+ }
18
+
19
+ function assertWhole(amount: number, what: string): void {
20
+ if (typeof amount !== 'number' || !Number.isSafeInteger(amount)) {
21
+ throw new MoneyError(MoneyErrorCode.NotInteger, `${what} must be a whole number of minor units, got ${String(amount)}`);
22
+ }
23
+ }
24
+
25
+ function assertMoney(value: Money): void {
26
+ if (typeof value !== 'object' || value === null) {
27
+ throw new MoneyError(MoneyErrorCode.NotMoney, `Not a Money value: ${String(value)}`);
28
+ }
29
+ currencyExponent(value.currency);
30
+ assertWhole(value.amount, 'Money.amount');
31
+ }
32
+
33
+ function assertSameCurrency(a: Money, b: Money): void {
34
+ assertMoney(a);
35
+ assertMoney(b);
36
+ if (a.currency !== b.currency) {
37
+ throw new MoneyError(MoneyErrorCode.CurrencyMismatch, `Cannot combine ${a.currency} with ${b.currency}`);
38
+ }
39
+ }
40
+
41
+ function safeResult(amount: number, currency: CurrencyCode): Money {
42
+ if (!Number.isSafeInteger(amount)) {
43
+ throw new MoneyError(MoneyErrorCode.Overflow, 'Result is beyond the safe integer range');
44
+ }
45
+ return { amount: amount === 0 ? 0 : amount, currency };
46
+ }
47
+
48
+ export function money(amount: number, currency: CurrencyCode): Money {
49
+ currencyExponent(currency);
50
+ assertWhole(amount, 'amount');
51
+ return { amount: amount === 0 ? 0 : amount, currency };
52
+ }
53
+
54
+ function decimalText(value: number | string): string | null {
55
+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : null;
56
+ if (typeof value === 'string') return value.trim();
57
+ return null;
58
+ }
59
+
60
+ /** Exact: `19.99` → 1999 by reading the digits, never `x * 100`; refuses digits the currency lacks. */
61
+ export function majorToMinor(major: number | string, currency: CurrencyCode): number {
62
+ const exponent = currencyExponent(currency);
63
+ const text = decimalText(major);
64
+ const decimal = text === null ? null : parseDecimal(text);
65
+ if (!decimal) {
66
+ throw new MoneyError(MoneyErrorCode.NotANumber, `Not a decimal amount: ${String(major)}`);
67
+ }
68
+ return decimalToScaledInteger(decimal, exponent, DecimalRounding.Exact);
69
+ }
70
+
71
+ export function minorToMajor(minor: number, currency: CurrencyCode): number {
72
+ const exponent = currencyExponent(currency);
73
+ assertWhole(minor, 'minor');
74
+ return exponent === 0 ? minor : minor / 10 ** exponent;
75
+ }
76
+
77
+ export function addMoney(a: Money, b: Money): Money {
78
+ assertSameCurrency(a, b);
79
+ return safeResult(a.amount + b.amount, a.currency);
80
+ }
81
+
82
+ export function subtractMoney(a: Money, b: Money): Money {
83
+ assertSameCurrency(a, b);
84
+ return safeResult(a.amount - b.amount, a.currency);
85
+ }
86
+
87
+ export function timesMoney(value: Money, quantity: number): Money {
88
+ assertMoney(value);
89
+ if (typeof quantity !== 'number' || !Number.isSafeInteger(quantity)) {
90
+ throw new MoneyError(MoneyErrorCode.NotWhole, `Quantity must be a whole number, got ${String(quantity)}`);
91
+ }
92
+ if (quantity < 0) {
93
+ throw new MoneyError(MoneyErrorCode.Negative, `Quantity cannot be negative, got ${quantity}`);
94
+ }
95
+ return safeResult(value.amount * quantity, value.currency);
96
+ }
97
+
98
+ /** `percent` of an amount, rounded ONCE to a minor unit, half-to-even (banker's). */
99
+ export function percentOf(value: Money, percent: number): Money {
100
+ assertMoney(value);
101
+ if (typeof percent !== 'number' || !Number.isFinite(percent)) {
102
+ throw new MoneyError(MoneyErrorCode.NotANumber, `Percent must be a finite number, got ${String(percent)}`);
103
+ }
104
+ if (percent < 0) {
105
+ throw new MoneyError(MoneyErrorCode.Negative, `Percent cannot be negative, got ${percent}`);
106
+ }
107
+ const decimal = parseDecimal(String(percent));
108
+ if (!decimal) {
109
+ throw new MoneyError(MoneyErrorCode.NotANumber, `Percent must be a finite number, got ${String(percent)}`);
110
+ }
111
+ if (decimal.frac.length > MAX_PERCENT_DECIMALS) {
112
+ throw new MoneyError(MoneyErrorCode.TooManyDecimals, `Percent has more than ${MAX_PERCENT_DECIMALS} decimal digits`);
113
+ }
114
+ const scale = decimal.frac.length;
115
+ const percentScaled = decimalToScaledInteger(decimal, scale, DecimalRounding.Exact);
116
+ const numerator = Math.abs(value.amount) * percentScaled;
117
+ if (!Number.isSafeInteger(numerator)) {
118
+ throw new MoneyError(MoneyErrorCode.Overflow, 'Percent of this amount is beyond the safe integer range');
119
+ }
120
+ const magnitude = divideHalfEven(numerator, 100 * 10 ** scale);
121
+ return safeResult(value.amount < 0 ? -magnitude : magnitude, value.currency);
122
+ }
123
+
124
+ const formatters = new Map<string, Intl.NumberFormat>();
125
+
126
+ export function formatMoney(value: Money, locale: string): string {
127
+ assertMoney(value);
128
+ const exponent = currencyExponent(value.currency);
129
+ const key = `${locale}|${value.currency}`;
130
+ let formatter = formatters.get(key);
131
+ if (!formatter) {
132
+ formatter = new Intl.NumberFormat(locale, {
133
+ style: 'currency',
134
+ currency: value.currency,
135
+ minimumFractionDigits: exponent,
136
+ maximumFractionDigits: exponent,
137
+ });
138
+ formatters.set(key, formatter);
139
+ }
140
+ return formatter.format(minorToMajor(value.amount, value.currency));
141
+ }
142
+
143
+ /**
144
+ * For the one boot migration of stored major-unit prices. A stored float may carry arithmetic noise
145
+ * (19.990000000000002), so extra digits round half-to-even instead of refusing. No usable price
146
+ * (null, '', NaN, text, a negative) → null; it never applies twice by itself — the caller marks rows.
147
+ */
148
+ export function migrateMajorPrice(value: unknown, currency: CurrencyCode): number | null {
149
+ const exponent = currencyExponent(currency);
150
+ if (typeof value !== 'number' && typeof value !== 'string') return null;
151
+ const text = decimalText(value);
152
+ const decimal = text ? parseDecimal(text) : null;
153
+ if (!decimal || (decimal.negative && (decimal.int || decimal.frac))) return null;
154
+ try {
155
+ return decimalToScaledInteger(decimal, exponent, DecimalRounding.HalfEven);
156
+ } catch {
157
+ return null;
158
+ }
159
+ }
@@ -0,0 +1,151 @@
1
+ import { PricedCart } from './cart';
2
+ import { CurrencyCode } from './currency';
3
+ import { Money, money } from './money';
4
+ import { PaymentChannel, paymentChannelOf, PaymentField, PaymentMethodConfig, PaymentMethodKind, usablePaymentMethods } from './payments';
5
+ import { ShippingMethodKind } from './shipping';
6
+ import { filled, looksLikeEmail } from './text';
7
+
8
+ export interface PostalAddress {
9
+ line1: string;
10
+ line2?: string | null;
11
+ city: string;
12
+ postalCode?: string | null;
13
+ /** ISO 3166-1 alpha-2 — one country in v1 (C-D9). */
14
+ country: string;
15
+ }
16
+
17
+ export interface OrderBuyer {
18
+ email: string;
19
+ name: string;
20
+ phone?: string | null;
21
+ /** Needed when the delivery method delivers to an address. */
22
+ address?: PostalAddress | null;
23
+ }
24
+
25
+ export enum OrderSnapshotRefusal {
26
+ EmptyCart = 'empty-cart',
27
+ /** The priced cart has issues the buyer has not seen: show them the priced cart first. */
28
+ CartChanged = 'cart-changed',
29
+ ShippingNotChosen = 'shipping-not-chosen',
30
+ AddressRequired = 'address-required',
31
+ EmailRequired = 'email-required',
32
+ NameRequired = 'name-required',
33
+ /** Not enabled, not complete, not offered yet, or not usable with this delivery. */
34
+ PaymentMethodUnusable = 'payment-method-unusable',
35
+ }
36
+
37
+ export interface OrderSnapshotLine {
38
+ readonly productId: string;
39
+ readonly variantId: string | null;
40
+ readonly title: string;
41
+ readonly variantName: string | null;
42
+ readonly quantity: number;
43
+ readonly unitPrice: Money;
44
+ readonly lineTotal: Money;
45
+ readonly requiresShipping: boolean;
46
+ }
47
+
48
+ /** What an order stores: frozen, so a later price, name or bank-detail change never changes a placed order. */
49
+ export interface OrderSnapshot {
50
+ readonly currency: CurrencyCode;
51
+ readonly lines: readonly OrderSnapshotLine[];
52
+ readonly subtotal: Money;
53
+ readonly discount: Money;
54
+ readonly shipping: Money;
55
+ readonly delivery: { readonly methodId: string; readonly kind: ShippingMethodKind; readonly name: string } | null;
56
+ readonly total: Money;
57
+ readonly vat: { readonly percent: number; readonly amount: Money };
58
+ readonly payment: {
59
+ readonly kind: PaymentMethodKind;
60
+ readonly channel: PaymentChannel;
61
+ readonly details: Readonly<Partial<Record<PaymentField, string>>>;
62
+ readonly note: string | null;
63
+ };
64
+ readonly buyer: Readonly<OrderBuyer>;
65
+ }
66
+
67
+ export type OrderSnapshotResult =
68
+ | { ok: true; snapshot: OrderSnapshot }
69
+ | { ok: false; refusals: OrderSnapshotRefusal[] };
70
+
71
+ function deepFreeze<T>(value: T): T {
72
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
73
+ Object.freeze(value);
74
+ for (const key of Object.keys(value as object)) deepFreeze((value as Record<string, unknown>)[key]);
75
+ }
76
+ return value;
77
+ }
78
+
79
+ const copyMoney = (value: Money): Money => money(value.amount, value.currency);
80
+ const text = (value: unknown): string | null => (filled(value) ? value.trim() : null);
81
+
82
+ function copyAddress(address: PostalAddress | null | undefined): PostalAddress | null {
83
+ if (!address || !filled(address.line1) || !filled(address.city) || !filled(address.country)) return null;
84
+ return {
85
+ line1: address.line1.trim(),
86
+ line2: text(address.line2),
87
+ city: address.city.trim(),
88
+ postalCode: text(address.postalCode),
89
+ country: address.country.trim(),
90
+ };
91
+ }
92
+
93
+ interface SnapshotRule {
94
+ readonly refusal: OrderSnapshotRefusal;
95
+ readonly refuses: (priced: PricedCart, payment: PaymentMethodConfig, buyer: OrderBuyer) => boolean;
96
+ }
97
+
98
+ const SNAPSHOT_RULES: readonly SnapshotRule[] = Object.freeze([
99
+ { refusal: OrderSnapshotRefusal.EmptyCart, refuses: (priced: PricedCart) => !priced.lines.length },
100
+ { refusal: OrderSnapshotRefusal.CartChanged, refuses: (priced: PricedCart) => priced.issues.length > 0 },
101
+ { refusal: OrderSnapshotRefusal.ShippingNotChosen, refuses: (priced: PricedCart) => priced.requiresShipping && !priced.shippingMethod },
102
+ {
103
+ refusal: OrderSnapshotRefusal.AddressRequired,
104
+ refuses: (priced: PricedCart, _payment: PaymentMethodConfig, buyer: OrderBuyer) => !!priced.shippingMethod?.needsAddress && !copyAddress(buyer?.address),
105
+ },
106
+ { refusal: OrderSnapshotRefusal.EmailRequired, refuses: (_priced: PricedCart, _payment: PaymentMethodConfig, buyer: OrderBuyer) => !looksLikeEmail(buyer?.email) },
107
+ { refusal: OrderSnapshotRefusal.NameRequired, refuses: (_priced: PricedCart, _payment: PaymentMethodConfig, buyer: OrderBuyer) => !filled(buyer?.name) },
108
+ {
109
+ refusal: OrderSnapshotRefusal.PaymentMethodUnusable,
110
+ refuses: (priced: PricedCart, payment: PaymentMethodConfig) => usablePaymentMethods([payment], priced.shippingMethod?.kind ?? null).length === 0,
111
+ },
112
+ ]);
113
+
114
+ /** Freezes what an order stores (lines, unit prices, totals, VAT, currency, delivery, payment, buyer) — or says why it cannot. */
115
+ export function orderSnapshot(pricedCart: PricedCart, payment: PaymentMethodConfig, buyer: OrderBuyer): OrderSnapshotResult {
116
+ const refusals = SNAPSHOT_RULES.filter(rule => rule.refuses(pricedCart, payment, buyer)).map(rule => rule.refusal);
117
+ if (refusals.length) return { ok: false, refusals };
118
+ const delivery = pricedCart.shippingMethod;
119
+ const snapshot: OrderSnapshot = {
120
+ currency: pricedCart.currency,
121
+ lines: pricedCart.lines.map(line => ({
122
+ productId: line.productId,
123
+ variantId: line.variantId,
124
+ title: line.title,
125
+ variantName: line.variantName,
126
+ quantity: line.quantity,
127
+ unitPrice: copyMoney(line.unitPrice),
128
+ lineTotal: copyMoney(line.lineTotal),
129
+ requiresShipping: line.requiresShipping,
130
+ })),
131
+ subtotal: copyMoney(pricedCart.subtotal),
132
+ discount: copyMoney(pricedCart.discount),
133
+ shipping: copyMoney(pricedCart.shipping),
134
+ delivery: delivery ? { methodId: delivery.methodId, kind: delivery.kind, name: delivery.name } : null,
135
+ total: copyMoney(pricedCart.total),
136
+ vat: { percent: pricedCart.vatPercent, amount: copyMoney(pricedCart.vat) },
137
+ payment: {
138
+ kind: payment.kind,
139
+ channel: paymentChannelOf(payment.kind),
140
+ details: { ...(payment.details ?? {}) },
141
+ note: text(payment.note),
142
+ },
143
+ buyer: {
144
+ email: buyer.email.trim(),
145
+ name: buyer.name.trim(),
146
+ phone: text(buyer.phone),
147
+ address: delivery?.needsAddress ? copyAddress(buyer.address) : null,
148
+ },
149
+ };
150
+ return { ok: true, snapshot: deepFreeze(snapshot) };
151
+ }
@@ -0,0 +1,172 @@
1
+ import { CommerceLabel } from './labels';
2
+ import { PaymentChannel, paymentChannelOf, PaymentMethodKind } from './payments';
3
+
4
+ /** C-D11 — the order's closed states. */
5
+ export enum OrderState {
6
+ /** A manual method: waiting for the owner to see the money. */
7
+ AwaitingPayment = 'awaiting_payment',
8
+ /** An online method: the PSP's page is open. */
9
+ PendingPayment = 'pending_payment',
10
+ Paid = 'paid',
11
+ Fulfilled = 'fulfilled',
12
+ Delivered = 'delivered',
13
+ Cancelled = 'cancelled',
14
+ PaymentFailed = 'payment_failed',
15
+ Refunded = 'refunded',
16
+ PartiallyRefunded = 'partially_refunded',
17
+ }
18
+
19
+ export enum OrderEvent {
20
+ /** The buyer tries to pay again after a failure. */
21
+ StartPayment = 'startPayment',
22
+ /** The PSP's verified callback says paid. */
23
+ ConfirmPayment = 'confirmPayment',
24
+ FailPayment = 'failPayment',
25
+ /** The owner saw the money of a manual method. */
26
+ MarkPaid = 'markPaid',
27
+ Fulfil = 'fulfil',
28
+ Deliver = 'deliver',
29
+ Cancel = 'cancel',
30
+ /** Nobody paid in time (the jobs runner). */
31
+ Expire = 'expire',
32
+ Refund = 'refund',
33
+ PartialRefund = 'partialRefund',
34
+ }
35
+
36
+ export enum OrderActor {
37
+ Buyer = 'buyer',
38
+ Owner = 'owner',
39
+ /** A VERIFIED payment callback (trap T2) — never the browser's return redirect. */
40
+ PaymentCallback = 'paymentCallback',
41
+ System = 'system',
42
+ }
43
+
44
+ /** What an order holds of the stock in a state (C-D10). */
45
+ export enum StockHold {
46
+ None = 'none',
47
+ /** Held for `STOCK_RESERVATION_MINUTES` while a PSP payment is open. */
48
+ Reserved = 'reserved',
49
+ /** Decremented: sold, or promised to a manual order. */
50
+ Taken = 'taken',
51
+ }
52
+
53
+ /** What the server does to stock when an order moves — read from data, never decided per call site. */
54
+ export enum StockEffect {
55
+ None = 'none',
56
+ Reserve = 'reserve',
57
+ CommitReservation = 'commitReservation',
58
+ ReleaseReservation = 'releaseReservation',
59
+ /** The conditional atomic decrement (E0's `takeStock`). */
60
+ Take = 'take',
61
+ GiveBack = 'giveBack',
62
+ }
63
+
64
+ export enum OrderRefusal {
65
+ /** The event does not apply in this state. */
66
+ InvalidTransition = 'invalid-transition',
67
+ /** It applies — but not from this actor (e.g. the owner marking an online payment paid). */
68
+ ActorNotAllowed = 'actor-not-allowed',
69
+ /** Cancelled and refunded orders move no more. */
70
+ OrderFinal = 'order-final',
71
+ }
72
+
73
+ export const STOCK_RESERVATION_MINUTES = 15;
74
+
75
+ export const ORDER_STOCK_HOLD: Readonly<Record<OrderState, StockHold>> = Object.freeze({
76
+ [OrderState.AwaitingPayment]: StockHold.Taken,
77
+ [OrderState.PendingPayment]: StockHold.Reserved,
78
+ [OrderState.Paid]: StockHold.Taken,
79
+ [OrderState.Fulfilled]: StockHold.Taken,
80
+ [OrderState.Delivered]: StockHold.Taken,
81
+ [OrderState.Cancelled]: StockHold.None,
82
+ [OrderState.PaymentFailed]: StockHold.None,
83
+ /** A refund never restocks by itself: whether the goods came back is the owner's to say. */
84
+ [OrderState.Refunded]: StockHold.Taken,
85
+ [OrderState.PartiallyRefunded]: StockHold.Taken,
86
+ });
87
+
88
+ /** from-hold → to-hold → effect. Taken → Reserved never happens (the transitions spec proves it). */
89
+ export const STOCK_EFFECTS: Readonly<Record<StockHold, Readonly<Record<StockHold, StockEffect>>>> = Object.freeze({
90
+ [StockHold.None]: { [StockHold.None]: StockEffect.None, [StockHold.Reserved]: StockEffect.Reserve, [StockHold.Taken]: StockEffect.Take },
91
+ [StockHold.Reserved]: { [StockHold.None]: StockEffect.ReleaseReservation, [StockHold.Reserved]: StockEffect.None, [StockHold.Taken]: StockEffect.CommitReservation },
92
+ [StockHold.Taken]: { [StockHold.None]: StockEffect.GiveBack, [StockHold.Reserved]: StockEffect.None, [StockHold.Taken]: StockEffect.None },
93
+ });
94
+
95
+ export const FINAL_ORDER_STATES: readonly OrderState[] = Object.freeze([OrderState.Cancelled, OrderState.Refunded]);
96
+
97
+ export interface OrderTransition {
98
+ readonly from: OrderState;
99
+ readonly event: OrderEvent;
100
+ readonly to: OrderState;
101
+ readonly actors: readonly OrderActor[];
102
+ }
103
+
104
+ const OWNER = [OrderActor.Owner];
105
+ const CALLBACK = [OrderActor.PaymentCallback];
106
+ const SYSTEM = [OrderActor.System];
107
+ const REFUNDERS = [OrderActor.Owner, OrderActor.PaymentCallback];
108
+ const REFUNDABLE = [OrderState.Paid, OrderState.Fulfilled, OrderState.Delivered, OrderState.PartiallyRefunded];
109
+
110
+ /** THE order state machine (C-D11). Anything not listed is refused. */
111
+ export const ORDER_TRANSITIONS: readonly OrderTransition[] = Object.freeze([
112
+ { from: OrderState.AwaitingPayment, event: OrderEvent.MarkPaid, to: OrderState.Paid, actors: OWNER },
113
+ { from: OrderState.AwaitingPayment, event: OrderEvent.Cancel, to: OrderState.Cancelled, actors: OWNER },
114
+ { from: OrderState.AwaitingPayment, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
115
+ { from: OrderState.PendingPayment, event: OrderEvent.ConfirmPayment, to: OrderState.Paid, actors: CALLBACK },
116
+ { from: OrderState.PendingPayment, event: OrderEvent.FailPayment, to: OrderState.PaymentFailed, actors: CALLBACK },
117
+ { from: OrderState.PendingPayment, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
118
+ { from: OrderState.PaymentFailed, event: OrderEvent.StartPayment, to: OrderState.PendingPayment, actors: [OrderActor.Buyer] },
119
+ { from: OrderState.PaymentFailed, event: OrderEvent.ConfirmPayment, to: OrderState.Paid, actors: CALLBACK },
120
+ { from: OrderState.PaymentFailed, event: OrderEvent.Cancel, to: OrderState.Cancelled, actors: OWNER },
121
+ { from: OrderState.PaymentFailed, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
122
+ { from: OrderState.Paid, event: OrderEvent.Fulfil, to: OrderState.Fulfilled, actors: OWNER },
123
+ { from: OrderState.PartiallyRefunded, event: OrderEvent.Fulfil, to: OrderState.Fulfilled, actors: OWNER },
124
+ { from: OrderState.Fulfilled, event: OrderEvent.Deliver, to: OrderState.Delivered, actors: OWNER },
125
+ ...REFUNDABLE.map(from => ({ from, event: OrderEvent.Refund, to: OrderState.Refunded, actors: REFUNDERS })),
126
+ ...REFUNDABLE.map(from => ({ from, event: OrderEvent.PartialRefund, to: OrderState.PartiallyRefunded, actors: REFUNDERS })),
127
+ ]);
128
+
129
+ export type OrderMove =
130
+ | { ok: true; state: OrderState; stock: StockEffect }
131
+ | { ok: false; refusal: OrderRefusal };
132
+
133
+ export function stockEffect(from: OrderState | null, to: OrderState): StockEffect {
134
+ return STOCK_EFFECTS[from === null ? StockHold.None : ORDER_STOCK_HOLD[from]][ORDER_STOCK_HOLD[to]];
135
+ }
136
+
137
+ /** The ONE place an order moves: the next state and what to do to the stock, or why not. */
138
+ export function nextOrderState(state: OrderState, event: OrderEvent, actor: OrderActor): OrderMove {
139
+ const transition = ORDER_TRANSITIONS.find(each => each.from === state && each.event === event);
140
+ if (!transition) {
141
+ return { ok: false, refusal: FINAL_ORDER_STATES.includes(state) ? OrderRefusal.OrderFinal : OrderRefusal.InvalidTransition };
142
+ }
143
+ if (!transition.actors.includes(actor)) return { ok: false, refusal: OrderRefusal.ActorNotAllowed };
144
+ return { ok: true, state: transition.to, stock: stockEffect(state, transition.to) };
145
+ }
146
+
147
+ const OPENING_STATE: Readonly<Record<PaymentChannel, OrderState>> = Object.freeze({
148
+ [PaymentChannel.Manual]: OrderState.AwaitingPayment,
149
+ [PaymentChannel.Online]: OrderState.PendingPayment,
150
+ });
151
+
152
+ /** A new order's state and stock effect: a manual order takes its stock at once, an online one reserves it. */
153
+ export function openingOrderState(kind: PaymentMethodKind): { state: OrderState; stock: StockEffect } {
154
+ const state = OPENING_STATE[paymentChannelOf(kind)];
155
+ return { state, stock: stockEffect(null, state) };
156
+ }
157
+
158
+ export function reservationExpiresAt(now: Date): Date {
159
+ return new Date(now.getTime() + STOCK_RESERVATION_MINUTES * 60000);
160
+ }
161
+
162
+ export const ORDER_STATE_LABELS: Readonly<Record<OrderState, CommerceLabel>> = Object.freeze({
163
+ [OrderState.AwaitingPayment]: { en: 'Awaiting payment', he: 'ממתינה לתשלום' },
164
+ [OrderState.PendingPayment]: { en: 'Payment in progress', he: 'תשלום בתהליך' },
165
+ [OrderState.Paid]: { en: 'Paid', he: 'שולמה' },
166
+ [OrderState.Fulfilled]: { en: 'Fulfilled', he: 'טופלה' },
167
+ [OrderState.Delivered]: { en: 'Delivered', he: 'נמסרה' },
168
+ [OrderState.Cancelled]: { en: 'Cancelled', he: 'בוטלה' },
169
+ [OrderState.PaymentFailed]: { en: 'Payment failed', he: 'התשלום נכשל' },
170
+ [OrderState.Refunded]: { en: 'Refunded', he: 'זוכתה' },
171
+ [OrderState.PartiallyRefunded]: { en: 'Partly refunded', he: 'זוכתה חלקית' },
172
+ });