@vectoriox/iox-ui 5.93.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,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
+ });
@@ -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
+ }
@@ -1,12 +1,23 @@
1
1
  /**
2
- * @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7).
2
+ * @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7…C-D11, C-D19).
3
3
  *
4
- * Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms
5
- * compute the same totals (trap T6: never a float). E0 ships Money and its helpers; priceCart,
6
- * ORDER_TRANSITIONS and carts arrive with E1.
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`.
7
8
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
8
9
  * jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
9
10
  */
10
11
  export * from './money-error';
11
12
  export * from './currency';
12
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';