@vectoriox/iox-ui 5.93.0 → 5.95.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.
Files changed (46) hide show
  1. package/actions-core/index.d.ts +7 -2
  2. package/commerce-core/index.d.ts +863 -3
  3. package/composite-core/index.d.ts +290 -2
  4. package/design-core/index.d.ts +1049 -105
  5. package/fesm2022/vectoriox-iox-ui-actions-core.mjs +15 -4
  6. package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
  7. package/fesm2022/vectoriox-iox-ui-commerce-core.mjs +1509 -5
  8. package/fesm2022/vectoriox-iox-ui-commerce-core.mjs.map +1 -1
  9. package/fesm2022/vectoriox-iox-ui-composite-core.mjs +1170 -177
  10. package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
  11. package/fesm2022/vectoriox-iox-ui-design-core.mjs +1147 -43
  12. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  13. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +2 -2
  14. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  15. package/fesm2022/vectoriox-iox-ui.mjs +8 -1
  16. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  17. package/generation-core/index.d.ts +2 -2
  18. package/index.d.ts +2 -0
  19. package/package.json +1 -1
  20. package/src/actions-core/action.model.ts +1 -1
  21. package/src/actions-core/element-actions.ts +17 -3
  22. package/src/commerce-core/cart-transport.ts +211 -0
  23. package/src/commerce-core/cart.ts +305 -0
  24. package/src/commerce-core/catalog.ts +42 -0
  25. package/src/commerce-core/checkout.ts +202 -0
  26. package/src/commerce-core/decimal.ts +28 -0
  27. package/src/commerce-core/labels.ts +29 -0
  28. package/src/commerce-core/limits.ts +9 -0
  29. package/src/commerce-core/money-error.ts +1 -0
  30. package/src/commerce-core/order-snapshot.ts +151 -0
  31. package/src/commerce-core/orders.ts +172 -0
  32. package/src/commerce-core/payments.ts +196 -0
  33. package/src/commerce-core/public-api.ts +19 -4
  34. package/src/commerce-core/quantity.ts +56 -0
  35. package/src/commerce-core/shipping.ts +168 -0
  36. package/src/commerce-core/shop-display.ts +117 -0
  37. package/src/commerce-core/text.ts +13 -0
  38. package/src/commerce-core/variants.ts +296 -0
  39. package/src/commerce-core/vat.ts +38 -0
  40. package/src/composite-core/exclusive-runtime.ts +20 -7
  41. package/src/composite-core/public-api.ts +2 -0
  42. package/src/composite-core/shop-runtime.ts +626 -0
  43. package/src/composite-core/shop.ts +433 -0
  44. package/src/design-core/flavor-spec.generated.ts +1147 -43
  45. package/src/generation-core/site-spec.generated.ts +2 -2
  46. package/styles/iox-design.css +95 -0
@@ -0,0 +1,202 @@
1
+ import { CurrencyCode, isCurrencyCode } from './currency';
2
+ import { CommerceLabel } from './labels';
3
+ import { paymentMethodReady, PaymentMethodConfig } from './payments';
4
+ import { ShippingMethod, shippingMethodReady, SHIPPING_KINDS } from './shipping';
5
+ import { filled, looksLikeEmail, looksLikePhone } from './text';
6
+ import { isVatPercent } from './vat';
7
+
8
+ /** The fixed checkout's steps, in order (C-D3); a checkout keeps the FURTHEST it reached (the journey, §3g). */
9
+ export enum CheckoutStep {
10
+ Contact = 'contact',
11
+ Delivery = 'delivery',
12
+ Payment = 'payment',
13
+ Paid = 'paid',
14
+ }
15
+
16
+ export const CHECKOUT_STEPS: readonly CheckoutStep[] = Object.freeze([
17
+ CheckoutStep.Contact,
18
+ CheckoutStep.Delivery,
19
+ CheckoutStep.Payment,
20
+ CheckoutStep.Paid,
21
+ ]);
22
+
23
+ export const CHECKOUT_STEP_LABELS: Readonly<Record<CheckoutStep, CommerceLabel>> = Object.freeze({
24
+ [CheckoutStep.Contact]: { en: 'Contact', he: 'פרטי קשר' },
25
+ [CheckoutStep.Delivery]: { en: 'Delivery', he: 'משלוח' },
26
+ [CheckoutStep.Payment]: { en: 'Payment', he: 'תשלום' },
27
+ [CheckoutStep.Paid]: { en: 'Paid', he: 'שולם' },
28
+ });
29
+
30
+ export function furthestStep(a: CheckoutStep | null | undefined, b: CheckoutStep | null | undefined): CheckoutStep {
31
+ const rank = (step: CheckoutStep | null | undefined) => (step ? CHECKOUT_STEPS.indexOf(step) : -1);
32
+ const best = rank(a) >= rank(b) ? a : b;
33
+ return best && CHECKOUT_STEPS.includes(best) ? best : CheckoutStep.Contact;
34
+ }
35
+
36
+ /** The pages the OWNER writes and links from checkout (§3k). IOX never writes their text (T14). */
37
+ export enum LegalPage {
38
+ Terms = 'terms',
39
+ Returns = 'returns',
40
+ Shipping = 'shipping',
41
+ Privacy = 'privacy',
42
+ }
43
+
44
+ /** Who sells, as Israel's Consumer Protection Law asks a distance seller to say (§3k). */
45
+ export interface BusinessIdentity {
46
+ legalName?: string | null;
47
+ /** עוסק מורשה / ח.פ / ת.ז */
48
+ businessNumber?: string | null;
49
+ address?: string | null;
50
+ email?: string | null;
51
+ phone?: string | null;
52
+ }
53
+
54
+ export interface CheckoutGateFacts {
55
+ currency: unknown;
56
+ vatPercent: unknown;
57
+ paymentMethods: readonly PaymentMethodConfig[];
58
+ shippingMethods: readonly ShippingMethod[];
59
+ /** Any product of the studio that is not digital. */
60
+ anyProductShips: boolean;
61
+ business: BusinessIdentity;
62
+ /** Each page exists and checkout links it. */
63
+ legalPages: Partial<Record<LegalPage, boolean>>;
64
+ }
65
+
66
+ export enum CheckoutGateArea {
67
+ Payment = 'payment',
68
+ Money = 'money',
69
+ Shipping = 'shipping',
70
+ Business = 'business',
71
+ LegalPages = 'legalPages',
72
+ }
73
+
74
+ export enum CheckoutGateCode {
75
+ NoPaymentMethod = 'no-payment-method',
76
+ CurrencyNotSet = 'currency-not-set',
77
+ VatNotSet = 'vat-not-set',
78
+ NoShippingMethod = 'no-shipping-method',
79
+ BusinessNameMissing = 'business-name-missing',
80
+ BusinessNumberMissing = 'business-number-missing',
81
+ BusinessAddressMissing = 'business-address-missing',
82
+ BusinessEmailMissing = 'business-email-missing',
83
+ BusinessPhoneMissing = 'business-phone-missing',
84
+ TermsPageMissing = 'terms-page-missing',
85
+ ReturnsPageMissing = 'returns-page-missing',
86
+ ShippingPageMissing = 'shipping-page-missing',
87
+ PrivacyPageMissing = 'privacy-page-missing',
88
+ }
89
+
90
+ interface CheckoutGateRule {
91
+ readonly code: CheckoutGateCode;
92
+ readonly area: CheckoutGateArea;
93
+ readonly refuses: (facts: CheckoutGateFacts) => boolean;
94
+ readonly label: CommerceLabel;
95
+ }
96
+
97
+ const ships = (facts: CheckoutGateFacts) => facts.anyProductShips === true;
98
+ const page = (facts: CheckoutGateFacts, which: LegalPage) => facts.legalPages?.[which] === true;
99
+ const business = (facts: CheckoutGateFacts): BusinessIdentity => facts.business ?? {};
100
+
101
+ /** THE checkout gate (C-D19), in the order the owner fixes things. The server refuses with it; the admin shows the same rows. */
102
+ export const CHECKOUT_GATE_RULES: readonly CheckoutGateRule[] = Object.freeze([
103
+ {
104
+ code: CheckoutGateCode.NoPaymentMethod,
105
+ area: CheckoutGateArea.Payment,
106
+ refuses: (facts: CheckoutGateFacts) => !(facts.paymentMethods ?? []).some(paymentMethodReady),
107
+ label: { en: 'Turn on a way to get paid', he: 'הפעילו אמצעי תשלום' },
108
+ },
109
+ {
110
+ code: CheckoutGateCode.CurrencyNotSet,
111
+ area: CheckoutGateArea.Money,
112
+ refuses: (facts: CheckoutGateFacts) => !isCurrencyCode(facts.currency),
113
+ label: { en: 'Set the shop\'s currency', he: 'הגדירו את מטבע החנות' },
114
+ },
115
+ {
116
+ code: CheckoutGateCode.VatNotSet,
117
+ area: CheckoutGateArea.Money,
118
+ refuses: (facts: CheckoutGateFacts) => !isVatPercent(facts.vatPercent),
119
+ label: { en: 'Set the VAT rate', he: 'הגדירו את שיעור המע"מ' },
120
+ },
121
+ {
122
+ code: CheckoutGateCode.NoShippingMethod,
123
+ area: CheckoutGateArea.Shipping,
124
+ refuses: (facts: CheckoutGateFacts) => ships(facts) && !(isCurrencyCode(facts.currency)
125
+ && (facts.shippingMethods ?? []).some(method => shippingMethodReady(method, facts.currency as CurrencyCode)
126
+ && SHIPPING_KINDS[method.kind].forPhysical)),
127
+ label: { en: 'Add a delivery or pickup method', he: 'הוסיפו שיטת משלוח או איסוף' },
128
+ },
129
+ {
130
+ code: CheckoutGateCode.BusinessNameMissing,
131
+ area: CheckoutGateArea.Business,
132
+ refuses: (facts: CheckoutGateFacts) => !filled(business(facts).legalName),
133
+ label: { en: 'Add the business\'s legal name', he: 'הוסיפו את השם הרשמי של העסק' },
134
+ },
135
+ {
136
+ code: CheckoutGateCode.BusinessNumberMissing,
137
+ area: CheckoutGateArea.Business,
138
+ refuses: (facts: CheckoutGateFacts) => !filled(business(facts).businessNumber),
139
+ label: { en: 'Add the business number (company or VAT dealer number)', he: 'הוסיפו מספר עוסק או ח.פ' },
140
+ },
141
+ {
142
+ code: CheckoutGateCode.BusinessAddressMissing,
143
+ area: CheckoutGateArea.Business,
144
+ refuses: (facts: CheckoutGateFacts) => !filled(business(facts).address),
145
+ label: { en: 'Add the business address', he: 'הוסיפו את כתובת העסק' },
146
+ },
147
+ {
148
+ code: CheckoutGateCode.BusinessEmailMissing,
149
+ area: CheckoutGateArea.Business,
150
+ refuses: (facts: CheckoutGateFacts) => !looksLikeEmail(business(facts).email),
151
+ label: { en: 'Add an email buyers can write to', he: 'הוסיפו כתובת אימייל לפניות קונים' },
152
+ },
153
+ {
154
+ code: CheckoutGateCode.BusinessPhoneMissing,
155
+ area: CheckoutGateArea.Business,
156
+ refuses: (facts: CheckoutGateFacts) => !looksLikePhone(business(facts).phone),
157
+ label: { en: 'Add a phone number buyers can call', he: 'הוסיפו מספר טלפון לפניות קונים' },
158
+ },
159
+ {
160
+ code: CheckoutGateCode.TermsPageMissing,
161
+ area: CheckoutGateArea.LegalPages,
162
+ refuses: (facts: CheckoutGateFacts) => !page(facts, LegalPage.Terms),
163
+ label: { en: 'Write your terms of sale page', he: 'כתבו עמוד תקנון ותנאי מכירה' },
164
+ },
165
+ {
166
+ code: CheckoutGateCode.ReturnsPageMissing,
167
+ area: CheckoutGateArea.LegalPages,
168
+ refuses: (facts: CheckoutGateFacts) => !page(facts, LegalPage.Returns),
169
+ label: { en: 'Write your returns and cancellation page', he: 'כתבו עמוד מדיניות החזרות וביטולים' },
170
+ },
171
+ {
172
+ code: CheckoutGateCode.ShippingPageMissing,
173
+ area: CheckoutGateArea.LegalPages,
174
+ refuses: (facts: CheckoutGateFacts) => ships(facts) && !page(facts, LegalPage.Shipping),
175
+ label: { en: 'Write your shipping page', he: 'כתבו עמוד מדיניות משלוחים' },
176
+ },
177
+ {
178
+ code: CheckoutGateCode.PrivacyPageMissing,
179
+ area: CheckoutGateArea.LegalPages,
180
+ refuses: (facts: CheckoutGateFacts) => !page(facts, LegalPage.Privacy),
181
+ label: { en: 'Write your privacy page', he: 'כתבו עמוד מדיניות פרטיות' },
182
+ },
183
+ ]);
184
+
185
+ export interface CheckoutGateRefusal {
186
+ code: CheckoutGateCode;
187
+ area: CheckoutGateArea;
188
+ label: CommerceLabel;
189
+ }
190
+
191
+ export interface CheckoutGateResult {
192
+ open: boolean;
193
+ refusals: CheckoutGateRefusal[];
194
+ }
195
+
196
+ /** Checkout opens only when no rule refuses (C-D19, trap T9: the server's, never a hidden button). */
197
+ export function checkoutGate(facts: CheckoutGateFacts): CheckoutGateResult {
198
+ const refusals = CHECKOUT_GATE_RULES
199
+ .filter(rule => rule.refuses(facts))
200
+ .map(rule => ({ code: rule.code, area: rule.area, label: rule.label }));
201
+ return { open: refusals.length === 0, refusals };
202
+ }
@@ -76,3 +76,31 @@ export function divideHalfEven(numerator: number, denominator: number): number {
76
76
  if (twice > denominator || (twice === denominator && quotient % 2 === 1)) quotient += 1;
77
77
  return quotient;
78
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;
@@ -8,6 +8,7 @@ export enum MoneyErrorCode {
8
8
  NotWhole = 'not-whole',
9
9
  Negative = 'negative',
10
10
  Overflow = 'overflow',
11
+ OutOfRange = 'out-of-range',
11
12
  }
12
13
 
13
14
  export class MoneyError extends Error {
@@ -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
+ });