@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,305 @@
1
+ import { CatalogEntry, catalogKey, sellableQuantity } from './catalog';
2
+ import { CurrencyCode, currencyExponent } from './currency';
3
+ import { CommerceLabel } from './labels';
4
+ import { MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY } from './limits';
5
+ import { addMoney, isMoney, money, Money, subtractMoney, timesMoney } from './money';
6
+ import { quoteShipping, ShippingMethod, ShippingQuote } from './shipping';
7
+ import { includedVat, isVatPercent } from './vat';
8
+
9
+ /** A cart names what and how many — never a price (C-D16, trap T1): every read prices it again. */
10
+ export interface CartLine {
11
+ productId: string;
12
+ variantId?: string | null;
13
+ quantity: number;
14
+ }
15
+
16
+ export interface Cart {
17
+ lines: readonly CartLine[];
18
+ }
19
+
20
+ export interface StudioCommerce {
21
+ currency: CurrencyCode;
22
+ /** Prices INCLUDE it (C-D8). */
23
+ vatPercent: number;
24
+ shippingMethods: readonly ShippingMethod[];
25
+ }
26
+
27
+ export interface PricingChoice {
28
+ shippingMethodId?: string | null;
29
+ }
30
+
31
+ export enum CartIssueCode {
32
+ /** Not a whole number ≥ 1: the line is dropped. */
33
+ InvalidQuantity = 'invalid-quantity',
34
+ /** The same product and variant twice: merged into the first. */
35
+ DuplicateLine = 'duplicate-line',
36
+ TooManyLines = 'too-many-lines',
37
+ QuantityCapped = 'quantity-capped',
38
+ UnknownProduct = 'unknown-product',
39
+ /** The product exists, this variant does not (or the product needs a variant chosen). */
40
+ UnknownVariant = 'unknown-variant',
41
+ Unpublished = 'unpublished',
42
+ VariantDisabled = 'variant-disabled',
43
+ NoPrice = 'no-price',
44
+ CurrencyMismatch = 'currency-mismatch',
45
+ OutOfStock = 'out-of-stock',
46
+ /** Fewer left than asked: the line keeps what is left. */
47
+ QuantityClamped = 'quantity-clamped',
48
+ /** The line would push the subtotal past `MAX_CART_AMOUNT`: dropped. */
49
+ AmountTooLarge = 'amount-too-large',
50
+ /** The chosen shipping method is not offered for this cart: no shipping is priced. */
51
+ ShippingUnavailable = 'shipping-unavailable',
52
+ /** The studio's VAT is not a usable rate: the VAT line reads 0. */
53
+ VatInvalid = 'vat-invalid',
54
+ }
55
+
56
+ export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> = Object.freeze({
57
+ [CartIssueCode.InvalidQuantity]: { en: 'A quantity was not a whole number, so the item was removed.', he: 'כמות שאינה מספר שלם — הפריט הוסר.' },
58
+ [CartIssueCode.DuplicateLine]: { en: 'The same item appeared twice and was combined.', he: 'אותו פריט הופיע פעמיים ואוחד.' },
59
+ [CartIssueCode.TooManyLines]: { en: 'Your cart has too many different items; the last ones were removed.', he: 'יש בעגלה יותר מדי פריטים שונים; האחרונים הוסרו.' },
60
+ [CartIssueCode.QuantityCapped]: { en: 'That is more than one order can hold; the quantity was lowered.', he: 'הכמות גדולה מהמותר בהזמנה אחת, והיא הוקטנה.' },
61
+ [CartIssueCode.UnknownProduct]: { en: 'An item is no longer sold and was removed.', he: 'פריט כבר לא נמכר והוסר.' },
62
+ [CartIssueCode.UnknownVariant]: { en: 'An option of an item is no longer sold and was removed.', he: 'אפשרות של פריט כבר לא נמכרת והוסרה.' },
63
+ [CartIssueCode.Unpublished]: { en: 'An item is not on sale right now and was removed.', he: 'פריט אינו למכירה כרגע והוסר.' },
64
+ [CartIssueCode.VariantDisabled]: { en: 'An option of an item is not available and was removed.', he: 'אפשרות של פריט אינה זמינה והוסרה.' },
65
+ [CartIssueCode.NoPrice]: { en: 'An item has no price yet and was removed.', he: 'לפריט עדיין אין מחיר, והוא הוסר.' },
66
+ [CartIssueCode.CurrencyMismatch]: { en: 'An item is priced in another currency and was removed.', he: 'פריט מתומחר במטבע אחר והוסר.' },
67
+ [CartIssueCode.OutOfStock]: { en: 'An item is out of stock and was removed.', he: 'פריט אזל מהמלאי והוסר.' },
68
+ [CartIssueCode.QuantityClamped]: { en: 'Fewer are left than you asked for; your cart holds what is left.', he: 'נשארו פחות ממה שביקשתם; בעגלה מה שנשאר.' },
69
+ [CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
70
+ [CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
71
+ [CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
72
+ });
73
+
74
+ export interface CartIssue {
75
+ code: CartIssueCode;
76
+ productId?: string;
77
+ variantId?: string | null;
78
+ /** What the cart asked for. */
79
+ requested?: number;
80
+ /** What the priced line holds now (clamped / capped). */
81
+ quantity?: number;
82
+ shippingMethodId?: string;
83
+ }
84
+
85
+ export interface PricedLine {
86
+ productId: string;
87
+ variantId: string | null;
88
+ title: string;
89
+ variantName: string | null;
90
+ quantity: number;
91
+ unitPrice: Money;
92
+ /** Shown struck through — only when it is above the price. */
93
+ compareAt: Money | null;
94
+ lineTotal: Money;
95
+ requiresShipping: boolean;
96
+ image: string | null;
97
+ }
98
+
99
+ export interface PricedCart {
100
+ currency: CurrencyCode;
101
+ lines: PricedLine[];
102
+ subtotal: Money;
103
+ /** Zero until coupons (E4); `total` already subtracts it. */
104
+ discount: Money;
105
+ shipping: Money;
106
+ shippingMethod: ShippingQuote | null;
107
+ requiresShipping: boolean;
108
+ /** subtotal − discount + shipping: what the buyer pays. VAT is INSIDE it. */
109
+ total: Money;
110
+ /** The VAT `total` includes: total × v / (100 + v), rounded once half-to-even (`includedVat`). */
111
+ vat: Money;
112
+ vatPercent: number;
113
+ issues: CartIssue[];
114
+ }
115
+
116
+ interface LineRefusal {
117
+ readonly code: CartIssueCode;
118
+ readonly refuses: (entry: CatalogEntry, currency: CurrencyCode) => boolean;
119
+ }
120
+
121
+ /** Checked in order; the first that refuses drops the line. */
122
+ const LINE_REFUSALS: readonly LineRefusal[] = Object.freeze([
123
+ { code: CartIssueCode.Unpublished, refuses: (entry: CatalogEntry) => entry.published !== true },
124
+ { code: CartIssueCode.VariantDisabled, refuses: (entry: CatalogEntry) => entry.enabled !== true },
125
+ { code: CartIssueCode.NoPrice, refuses: (entry: CatalogEntry) => !isMoney(entry.unitPrice) || entry.unitPrice.amount < 0 },
126
+ { code: CartIssueCode.CurrencyMismatch, refuses: (entry: CatalogEntry, currency: CurrencyCode) => (entry.unitPrice as Money).currency !== currency },
127
+ { code: CartIssueCode.OutOfStock, refuses: (entry: CatalogEntry) => sellableQuantity(entry) === 0 },
128
+ ]);
129
+
130
+ const isText = (value: unknown): value is string => typeof value === 'string' && value !== '';
131
+ const variantOf = (line: CartLine): string | null => (isText(line.variantId) ? line.variantId : null);
132
+ const validQuantity = (quantity: unknown): quantity is number =>
133
+ typeof quantity === 'number' && Number.isSafeInteger(quantity) && quantity >= 1;
134
+
135
+ interface WantedLine {
136
+ productId: string;
137
+ variantId: string | null;
138
+ quantity: number;
139
+ }
140
+
141
+ /** Drops malformed lines, merges duplicates, keeps the first `MAX_CART_LINES` distinct ones. */
142
+ function wantedLines(cart: Cart, issues: CartIssue[]): WantedLine[] {
143
+ const lines: readonly CartLine[] = cart && Array.isArray(cart.lines) ? cart.lines : [];
144
+ const byKey = new Map<string, WantedLine>();
145
+ for (const line of lines) {
146
+ const productId = line && isText(line.productId) ? line.productId : '';
147
+ const variantId = line ? variantOf(line) : null;
148
+ if (!productId) {
149
+ issues.push({ code: CartIssueCode.UnknownProduct });
150
+ continue;
151
+ }
152
+ if (!validQuantity(line.quantity)) {
153
+ issues.push({ code: CartIssueCode.InvalidQuantity, productId, variantId });
154
+ continue;
155
+ }
156
+ const key = catalogKey(productId, variantId);
157
+ const same = byKey.get(key);
158
+ if (same) {
159
+ same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
160
+ issues.push({ code: CartIssueCode.DuplicateLine, productId, variantId });
161
+ continue;
162
+ }
163
+ if (byKey.size >= MAX_CART_LINES) {
164
+ issues.push({ code: CartIssueCode.TooManyLines, productId, variantId });
165
+ continue;
166
+ }
167
+ byKey.set(key, { productId, variantId, quantity: line.quantity });
168
+ }
169
+ return [...byKey.values()];
170
+ }
171
+
172
+ function indexCatalog(catalog: readonly CatalogEntry[]): { entries: Map<string, CatalogEntry>; products: Set<string> } {
173
+ const entries = new Map<string, CatalogEntry>();
174
+ const products = new Set<string>();
175
+ const list: readonly CatalogEntry[] = Array.isArray(catalog) ? catalog : [];
176
+ for (const entry of list) {
177
+ if (!entry || !isText(entry.productId)) continue;
178
+ products.add(entry.productId);
179
+ const key = catalogKey(entry.productId, isText(entry.variantId) ? entry.variantId : null);
180
+ if (!entries.has(key)) entries.set(key, entry);
181
+ }
182
+ return { entries, products };
183
+ }
184
+
185
+ const compareAtOf = (entry: CatalogEntry, unitPrice: Money): Money | null =>
186
+ isMoney(entry.compareAt) && entry.compareAt.currency === unitPrice.currency && entry.compareAt.amount > unitPrice.amount
187
+ ? money(entry.compareAt.amount, entry.compareAt.currency)
188
+ : null;
189
+
190
+ function lineTotalWithin(unitPrice: Money, quantity: number, subtotal: Money): Money | null {
191
+ try {
192
+ const lineTotal = timesMoney(unitPrice, quantity);
193
+ return subtotal.amount + lineTotal.amount <= MAX_CART_AMOUNT ? lineTotal : null;
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
201
+ * payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
202
+ * out is whole minor units in the studio currency. An unusable line is dropped or adjusted and SAID in `issues`.
203
+ */
204
+ export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio: StudioCommerce, choice?: PricingChoice | null): PricedCart {
205
+ const currency = studio.currency;
206
+ currencyExponent(currency);
207
+ const issues: CartIssue[] = [];
208
+ const { entries, products } = indexCatalog(catalog);
209
+ const lines: PricedLine[] = [];
210
+ let subtotal = money(0, currency);
211
+
212
+ for (const wanted of wantedLines(cart, issues)) {
213
+ const { productId, variantId } = wanted;
214
+ const entry = entries.get(catalogKey(productId, variantId));
215
+ if (!entry) {
216
+ issues.push({ code: products.has(productId) ? CartIssueCode.UnknownVariant : CartIssueCode.UnknownProduct, productId, variantId });
217
+ continue;
218
+ }
219
+ const refusal = LINE_REFUSALS.find(rule => rule.refuses(entry, currency));
220
+ if (refusal) {
221
+ issues.push({ code: refusal.code, productId, variantId, requested: wanted.quantity });
222
+ continue;
223
+ }
224
+ let quantity = wanted.quantity;
225
+ if (quantity > MAX_LINE_QUANTITY) {
226
+ quantity = MAX_LINE_QUANTITY;
227
+ issues.push({ code: CartIssueCode.QuantityCapped, productId, variantId, requested: wanted.quantity, quantity });
228
+ }
229
+ const left = sellableQuantity(entry);
230
+ if (left !== null && quantity > left) {
231
+ const requested = quantity;
232
+ quantity = left;
233
+ issues.push({ code: CartIssueCode.QuantityClamped, productId, variantId, requested, quantity });
234
+ }
235
+ const unitPrice = money((entry.unitPrice as Money).amount, currency);
236
+ const lineTotal = lineTotalWithin(unitPrice, quantity, subtotal);
237
+ if (!lineTotal) {
238
+ issues.push({ code: CartIssueCode.AmountTooLarge, productId, variantId, requested: wanted.quantity });
239
+ continue;
240
+ }
241
+ subtotal = addMoney(subtotal, lineTotal);
242
+ lines.push({
243
+ productId,
244
+ variantId,
245
+ title: String(entry.title ?? ''),
246
+ variantName: isText(entry.variantName) ? entry.variantName : null,
247
+ quantity,
248
+ unitPrice,
249
+ compareAt: compareAtOf(entry, unitPrice),
250
+ lineTotal,
251
+ requiresShipping: entry.requiresShipping !== false,
252
+ image: isText(entry.image) ? entry.image : null,
253
+ });
254
+ }
255
+
256
+ const discount = money(0, currency);
257
+ const goods = subtractMoney(subtotal, discount);
258
+ const requiresShipping = lines.some(line => line.requiresShipping);
259
+ const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
260
+ const quotes = chosenId ? quoteShipping(studio.shippingMethods, { currency, goods, requiresShipping, lineCount: lines.length }) : [];
261
+ const shippingMethod = chosenId ? quotes.find(quote => quote.methodId === chosenId) ?? null : null;
262
+ if (chosenId && !shippingMethod) issues.push({ code: CartIssueCode.ShippingUnavailable, shippingMethodId: chosenId });
263
+ const shipping = shippingMethod ? shippingMethod.price : money(0, currency);
264
+ const total = addMoney(goods, shipping);
265
+ const vatUsable = isVatPercent(studio.vatPercent);
266
+ if (!vatUsable) issues.push({ code: CartIssueCode.VatInvalid });
267
+
268
+ return {
269
+ currency,
270
+ lines,
271
+ subtotal,
272
+ discount,
273
+ shipping,
274
+ shippingMethod,
275
+ requiresShipping,
276
+ total,
277
+ vat: vatUsable ? includedVat(total, studio.vatPercent) : money(0, currency),
278
+ vatPercent: vatUsable ? studio.vatPercent : 0,
279
+ issues,
280
+ };
281
+ }
282
+
283
+ /** The cart a priced cart stands for — what to store back once the buyer has seen the issues. */
284
+ export function cartOf(priced: PricedCart): Cart {
285
+ return { lines: priced.lines.map(line => ({ productId: line.productId, variantId: line.variantId, quantity: line.quantity })) };
286
+ }
287
+
288
+ /** Sign-in merge (E3): b's lines join a's; the same product and variant add up. priceCart caps and clamps later. */
289
+ export function mergeCarts(a: Cart, b: Cart): Cart {
290
+ const merged: CartLine[] = [];
291
+ const byKey = new Map<string, CartLine>();
292
+ const all: CartLine[] = [...(Array.isArray(a?.lines) ? a.lines : []), ...(Array.isArray(b?.lines) ? b.lines : [])];
293
+ for (const line of all.filter(each => !!each && isText(each.productId))) {
294
+ const key = catalogKey(line.productId, variantOf(line));
295
+ const same = byKey.get(key);
296
+ if (same && validQuantity(same.quantity) && validQuantity(line.quantity)) {
297
+ same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
298
+ continue;
299
+ }
300
+ const copy = { productId: line.productId, variantId: variantOf(line), quantity: line.quantity };
301
+ if (!same) byKey.set(key, copy);
302
+ merged.push(copy);
303
+ }
304
+ return { lines: merged };
305
+ }
@@ -0,0 +1,42 @@
1
+ import { Money } from './money';
2
+
3
+ /** The storefront's stock word (iox-cms `storefront-projection.ts` speaks the same values). */
4
+ export enum Availability {
5
+ InStock = 'in_stock',
6
+ Low = 'low',
7
+ Out = 'out',
8
+ }
9
+
10
+ /**
11
+ * One sellable unit as the seller knows it, in minor units: a product with no options is ONE entry with no
12
+ * `variantId`; a product with options is one entry per variant. iox-cms builds it from the product row (with the
13
+ * stock COUNT); the engine builds it from the storefront projection (with the availability WORD only).
14
+ */
15
+ export interface CatalogEntry {
16
+ productId: string;
17
+ variantId?: string | null;
18
+ title: string;
19
+ variantName?: string | null;
20
+ /** null = no price set yet (a sample's placeholder): never sold. */
21
+ unitPrice: Money | null;
22
+ compareAt?: Money | null;
23
+ /** The count, where the caller knows it (iox-cms). Wins over `availability`. */
24
+ stock?: number | null;
25
+ /** The word, where only it is known (the engine). */
26
+ availability?: Availability | null;
27
+ /** A variant's switch; a product with no options is `true`. */
28
+ enabled: boolean;
29
+ published: boolean;
30
+ /** false = a digital product: no delivery address, no shipping method. */
31
+ requiresShipping: boolean;
32
+ image?: string | null;
33
+ }
34
+
35
+ /** How many units may be sold: the count, else 0 for `out` or nothing known, else null = unbounded here (the server checks the count). */
36
+ export function sellableQuantity(entry: CatalogEntry): number | null {
37
+ if (typeof entry.stock === 'number') return Number.isSafeInteger(entry.stock) && entry.stock > 0 ? entry.stock : 0;
38
+ if (entry.availability === Availability.InStock || entry.availability === Availability.Low) return null;
39
+ return 0;
40
+ }
41
+
42
+ export const catalogKey = (productId: string, variantId?: string | null): string => `${productId}\u0000${variantId ?? ''}`;
@@ -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
+ }
@@ -0,0 +1,99 @@
1
+ import { MoneyError, MoneyErrorCode } from './money-error';
2
+
3
+ export enum CurrencyCode {
4
+ ILS = 'ILS',
5
+ USD = 'USD',
6
+ EUR = 'EUR',
7
+ GBP = 'GBP',
8
+ CHF = 'CHF',
9
+ CAD = 'CAD',
10
+ AUD = 'AUD',
11
+ NZD = 'NZD',
12
+ SEK = 'SEK',
13
+ NOK = 'NOK',
14
+ DKK = 'DKK',
15
+ PLN = 'PLN',
16
+ CZK = 'CZK',
17
+ HUF = 'HUF',
18
+ RON = 'RON',
19
+ TRY = 'TRY',
20
+ AED = 'AED',
21
+ SAR = 'SAR',
22
+ QAR = 'QAR',
23
+ EGP = 'EGP',
24
+ MAD = 'MAD',
25
+ ZAR = 'ZAR',
26
+ INR = 'INR',
27
+ CNY = 'CNY',
28
+ HKD = 'HKD',
29
+ SGD = 'SGD',
30
+ THB = 'THB',
31
+ MXN = 'MXN',
32
+ BRL = 'BRL',
33
+ JPY = 'JPY',
34
+ KRW = 'KRW',
35
+ VND = 'VND',
36
+ CLP = 'CLP',
37
+ ISK = 'ISK',
38
+ BHD = 'BHD',
39
+ KWD = 'KWD',
40
+ JOD = 'JOD',
41
+ OMR = 'OMR',
42
+ TND = 'TND',
43
+ }
44
+
45
+ /** ISO-4217 minor units — our own table, never Intl's CLDR digits (they differ for some codes). */
46
+ export const CURRENCY_EXPONENTS: Readonly<Record<CurrencyCode, number>> = Object.freeze({
47
+ [CurrencyCode.ILS]: 2,
48
+ [CurrencyCode.USD]: 2,
49
+ [CurrencyCode.EUR]: 2,
50
+ [CurrencyCode.GBP]: 2,
51
+ [CurrencyCode.CHF]: 2,
52
+ [CurrencyCode.CAD]: 2,
53
+ [CurrencyCode.AUD]: 2,
54
+ [CurrencyCode.NZD]: 2,
55
+ [CurrencyCode.SEK]: 2,
56
+ [CurrencyCode.NOK]: 2,
57
+ [CurrencyCode.DKK]: 2,
58
+ [CurrencyCode.PLN]: 2,
59
+ [CurrencyCode.CZK]: 2,
60
+ [CurrencyCode.HUF]: 2,
61
+ [CurrencyCode.RON]: 2,
62
+ [CurrencyCode.TRY]: 2,
63
+ [CurrencyCode.AED]: 2,
64
+ [CurrencyCode.SAR]: 2,
65
+ [CurrencyCode.QAR]: 2,
66
+ [CurrencyCode.EGP]: 2,
67
+ [CurrencyCode.MAD]: 2,
68
+ [CurrencyCode.ZAR]: 2,
69
+ [CurrencyCode.INR]: 2,
70
+ [CurrencyCode.CNY]: 2,
71
+ [CurrencyCode.HKD]: 2,
72
+ [CurrencyCode.SGD]: 2,
73
+ [CurrencyCode.THB]: 2,
74
+ [CurrencyCode.MXN]: 2,
75
+ [CurrencyCode.BRL]: 2,
76
+ [CurrencyCode.JPY]: 0,
77
+ [CurrencyCode.KRW]: 0,
78
+ [CurrencyCode.VND]: 0,
79
+ [CurrencyCode.CLP]: 0,
80
+ [CurrencyCode.ISK]: 0,
81
+ [CurrencyCode.BHD]: 3,
82
+ [CurrencyCode.KWD]: 3,
83
+ [CurrencyCode.JOD]: 3,
84
+ [CurrencyCode.OMR]: 3,
85
+ [CurrencyCode.TND]: 3,
86
+ });
87
+
88
+ export const CURRENCY_CODES: readonly CurrencyCode[] = Object.freeze(Object.values(CurrencyCode));
89
+
90
+ export function isCurrencyCode(value: unknown): value is CurrencyCode {
91
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(CURRENCY_EXPONENTS, value);
92
+ }
93
+
94
+ export function currencyExponent(currency: CurrencyCode): number {
95
+ if (!isCurrencyCode(currency)) {
96
+ throw new MoneyError(MoneyErrorCode.UnknownCurrency, `Unknown currency: ${String(currency)}`);
97
+ }
98
+ return CURRENCY_EXPONENTS[currency];
99
+ }