@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.
- package/actions-core/index.d.ts +7 -2
- package/commerce-core/index.d.ts +863 -3
- package/composite-core/index.d.ts +290 -2
- package/design-core/index.d.ts +1049 -105
- package/fesm2022/vectoriox-iox-ui-actions-core.mjs +15 -4
- package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-commerce-core.mjs +1509 -5
- package/fesm2022/vectoriox-iox-ui-commerce-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-composite-core.mjs +1170 -177
- package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-design-core.mjs +1147 -43
- package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs +2 -2
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
- package/fesm2022/vectoriox-iox-ui.mjs +8 -1
- package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
- package/generation-core/index.d.ts +2 -2
- package/index.d.ts +2 -0
- package/package.json +1 -1
- package/src/actions-core/action.model.ts +1 -1
- package/src/actions-core/element-actions.ts +17 -3
- package/src/commerce-core/cart-transport.ts +211 -0
- package/src/commerce-core/cart.ts +305 -0
- package/src/commerce-core/catalog.ts +42 -0
- package/src/commerce-core/checkout.ts +202 -0
- package/src/commerce-core/decimal.ts +28 -0
- package/src/commerce-core/labels.ts +29 -0
- package/src/commerce-core/limits.ts +9 -0
- package/src/commerce-core/money-error.ts +1 -0
- package/src/commerce-core/order-snapshot.ts +151 -0
- package/src/commerce-core/orders.ts +172 -0
- package/src/commerce-core/payments.ts +196 -0
- package/src/commerce-core/public-api.ts +19 -4
- package/src/commerce-core/quantity.ts +56 -0
- package/src/commerce-core/shipping.ts +168 -0
- package/src/commerce-core/shop-display.ts +117 -0
- package/src/commerce-core/text.ts +13 -0
- package/src/commerce-core/variants.ts +296 -0
- package/src/commerce-core/vat.ts +38 -0
- package/src/composite-core/exclusive-runtime.ts +20 -7
- package/src/composite-core/public-api.ts +2 -0
- package/src/composite-core/shop-runtime.ts +626 -0
- package/src/composite-core/shop.ts +433 -0
- package/src/design-core/flavor-spec.generated.ts +1147 -43
- package/src/generation-core/site-spec.generated.ts +2 -2
- package/styles/iox-design.css +95 -0
|
@@ -9,6 +9,7 @@ var MoneyErrorCode;
|
|
|
9
9
|
MoneyErrorCode["NotWhole"] = "not-whole";
|
|
10
10
|
MoneyErrorCode["Negative"] = "negative";
|
|
11
11
|
MoneyErrorCode["Overflow"] = "overflow";
|
|
12
|
+
MoneyErrorCode["OutOfRange"] = "out-of-range";
|
|
12
13
|
})(MoneyErrorCode || (MoneyErrorCode = {}));
|
|
13
14
|
class MoneyError extends Error {
|
|
14
15
|
constructor(code, message) {
|
|
@@ -183,6 +184,33 @@ function divideHalfEven(numerator, denominator) {
|
|
|
183
184
|
quotient += 1;
|
|
184
185
|
return quotient;
|
|
185
186
|
}
|
|
187
|
+
/** Integer division that never trusts the float quotient: trunc, then corrected by the remainder. */
|
|
188
|
+
function divMod(numerator, denominator) {
|
|
189
|
+
let quotient = Math.trunc(numerator / denominator);
|
|
190
|
+
let remainder = numerator - quotient * denominator;
|
|
191
|
+
while (remainder < 0) {
|
|
192
|
+
quotient -= 1;
|
|
193
|
+
remainder += denominator;
|
|
194
|
+
}
|
|
195
|
+
while (remainder >= denominator) {
|
|
196
|
+
quotient += 1;
|
|
197
|
+
remainder -= denominator;
|
|
198
|
+
}
|
|
199
|
+
return [quotient, remainder];
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* 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
|
|
203
|
+
* a·b/d = q·b + r·b/d, where q·b < a and r·b < d·b — callers keep d·b a safe integer.
|
|
204
|
+
*/
|
|
205
|
+
function mulDivHalfEven(a, b, d) {
|
|
206
|
+
const [q, r] = divMod(a, d);
|
|
207
|
+
const [f, rest] = divMod(r * b, d);
|
|
208
|
+
let result = q * b + f;
|
|
209
|
+
const twice = rest * 2;
|
|
210
|
+
if (twice > d || (twice === d && result % 2 === 1))
|
|
211
|
+
result += 1;
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
186
214
|
|
|
187
215
|
const MAX_PERCENT_DECIMALS = 6;
|
|
188
216
|
function isMoney(value) {
|
|
@@ -325,11 +353,1487 @@ function migrateMajorPrice(value, currency) {
|
|
|
325
353
|
}
|
|
326
354
|
|
|
327
355
|
/**
|
|
328
|
-
*
|
|
356
|
+
* The words a refusal or a state is shown with. A string-rendered site and iox-cms's emails have no translation
|
|
357
|
+
* service, so the core carries English and Hebrew itself (the `blurbHe` / `sentWord` precedent); a host with its
|
|
358
|
+
* own translations may key them by the stable code instead.
|
|
359
|
+
*/
|
|
360
|
+
var CommerceLanguage;
|
|
361
|
+
(function (CommerceLanguage) {
|
|
362
|
+
CommerceLanguage["En"] = "en";
|
|
363
|
+
CommerceLanguage["He"] = "he";
|
|
364
|
+
})(CommerceLanguage || (CommerceLanguage = {}));
|
|
365
|
+
const LANGUAGE_ALIASES = Object.freeze({
|
|
366
|
+
en: CommerceLanguage.En,
|
|
367
|
+
he: CommerceLanguage.He,
|
|
368
|
+
iw: CommerceLanguage.He,
|
|
369
|
+
});
|
|
370
|
+
function commerceLanguage(lang) {
|
|
371
|
+
const primary = String(lang ?? '').trim().toLowerCase().split(/[-_]/)[0];
|
|
372
|
+
return LANGUAGE_ALIASES[primary] ?? CommerceLanguage.En;
|
|
373
|
+
}
|
|
374
|
+
function labelIn(label, lang) {
|
|
375
|
+
return label[commerceLanguage(lang)];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** A cart holds at most this many distinct lines; more are dropped (`too-many-lines`). */
|
|
379
|
+
const MAX_CART_LINES = 100;
|
|
380
|
+
/** One line's quantity is capped here (`quantity-capped`), before stock. */
|
|
381
|
+
const MAX_LINE_QUANTITY = 999;
|
|
382
|
+
/**
|
|
383
|
+
* The largest subtotal, shipping price or threshold, in minor units. Subtotal + shipping stays far below 2^53, and
|
|
384
|
+
* the included-VAT arithmetic never forms a product past it.
|
|
385
|
+
*/
|
|
386
|
+
const MAX_CART_AMOUNT = 10 ** 15;
|
|
387
|
+
|
|
388
|
+
const MAX_VAT_PERCENT = 100;
|
|
389
|
+
/** 17, 18, 7.7, 8.1 — four decimals is more than any rate in force; it also keeps the arithmetic below 2^53. */
|
|
390
|
+
const VAT_PERCENT_MAX_DECIMALS = 4;
|
|
391
|
+
function isVatPercent(value) {
|
|
392
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > MAX_VAT_PERCENT)
|
|
393
|
+
return false;
|
|
394
|
+
const decimal = parseDecimal(String(value));
|
|
395
|
+
return !!decimal && decimal.frac.length <= VAT_PERCENT_MAX_DECIMALS;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* The VAT a VAT-INCLUSIVE amount already holds (C-D8): amount × v / (100 + v), rounded ONCE to a minor unit,
|
|
399
|
+
* half-to-even. Exact: v is read as the integer R = v·10^s (s ≤ 4 decimals), so the share is
|
|
400
|
+
* amount × R / (100·10^s + R) in whole numbers. 118.00 at 18 % → 18.00; 100.00 at 17 % → 14.53.
|
|
401
|
+
*/
|
|
402
|
+
function includedVat(total, vatPercent) {
|
|
403
|
+
currencyExponent(total.currency);
|
|
404
|
+
if (typeof total.amount !== 'number' || !Number.isSafeInteger(total.amount)) {
|
|
405
|
+
throw new MoneyError(MoneyErrorCode.NotInteger, `total must be a whole number of minor units, got ${String(total.amount)}`);
|
|
406
|
+
}
|
|
407
|
+
if (!isVatPercent(vatPercent)) {
|
|
408
|
+
throw new MoneyError(MoneyErrorCode.OutOfRange, `VAT must be 0–${MAX_VAT_PERCENT} with at most ${VAT_PERCENT_MAX_DECIMALS} decimals, got ${String(vatPercent)}`);
|
|
409
|
+
}
|
|
410
|
+
const decimal = parseDecimal(String(vatPercent));
|
|
411
|
+
const scale = decimal.frac.length;
|
|
412
|
+
const rate = decimalToScaledInteger(decimal, scale, DecimalRounding.Exact);
|
|
413
|
+
const magnitude = Math.abs(total.amount);
|
|
414
|
+
if (magnitude > Number.MAX_SAFE_INTEGER / 2) {
|
|
415
|
+
throw new MoneyError(MoneyErrorCode.Overflow, 'Amount is beyond the range VAT is computed for');
|
|
416
|
+
}
|
|
417
|
+
const share = mulDivHalfEven(magnitude, rate, 100 * 10 ** scale + rate);
|
|
418
|
+
return { amount: total.amount < 0 && share !== 0 ? -share : share, currency: total.currency };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** The storefront's stock word (iox-cms `storefront-projection.ts` speaks the same values). */
|
|
422
|
+
var Availability;
|
|
423
|
+
(function (Availability) {
|
|
424
|
+
Availability["InStock"] = "in_stock";
|
|
425
|
+
Availability["Low"] = "low";
|
|
426
|
+
Availability["Out"] = "out";
|
|
427
|
+
})(Availability || (Availability = {}));
|
|
428
|
+
/** How many units may be sold: the count, else 0 for `out` or nothing known, else null = unbounded here (the server checks the count). */
|
|
429
|
+
function sellableQuantity(entry) {
|
|
430
|
+
if (typeof entry.stock === 'number')
|
|
431
|
+
return Number.isSafeInteger(entry.stock) && entry.stock > 0 ? entry.stock : 0;
|
|
432
|
+
if (entry.availability === Availability.InStock || entry.availability === Availability.Low)
|
|
433
|
+
return null;
|
|
434
|
+
return 0;
|
|
435
|
+
}
|
|
436
|
+
const catalogKey = (productId, variantId) => `${productId}\u0000${variantId ?? ''}`;
|
|
437
|
+
|
|
438
|
+
const filled = (value) => typeof value === 'string' && value.trim() !== '';
|
|
439
|
+
const looksLikeEmail = (value) => filled(value) && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
|
|
440
|
+
const digitsOf = (value) => (typeof value === 'string' ? value.replace(/\D/g, '') : '');
|
|
441
|
+
/** A phone a person can be called on: 7–15 digits once spaces, dashes, brackets and a leading + are dropped. */
|
|
442
|
+
const looksLikePhone = (value) => filled(value) && /^\+?[\d\s\-().]+$/.test(value.trim()) && digitsOf(value).length >= 7 && digitsOf(value).length <= 15;
|
|
443
|
+
/** An Israeli mobile number (Bit sends to one): 05X-XXXXXXX, or +972 5X-XXXXXXX. */
|
|
444
|
+
const looksLikeIsraeliMobile = (value) => filled(value) && /^\+?[\d\s\-().]+$/.test(value.trim()) && /^(?:9725|05)\d{8}$/.test(digitsOf(value));
|
|
445
|
+
|
|
446
|
+
/** Shipping v1 (C-D9): methods per studio, one country. Zones and weights come later. */
|
|
447
|
+
var ShippingMethodKind;
|
|
448
|
+
(function (ShippingMethodKind) {
|
|
449
|
+
ShippingMethodKind["Pickup"] = "pickup";
|
|
450
|
+
ShippingMethodKind["Flat"] = "flat";
|
|
451
|
+
/** A flat price that becomes free once the goods reach `freeOver`. */
|
|
452
|
+
ShippingMethodKind["FreeOver"] = "freeOver";
|
|
453
|
+
/** No address, nothing shipped — offered only when nothing in the cart ships. */
|
|
454
|
+
ShippingMethodKind["Digital"] = "digital";
|
|
455
|
+
})(ShippingMethodKind || (ShippingMethodKind = {}));
|
|
456
|
+
/** What an owner must fill for a method of a kind. */
|
|
457
|
+
var ShippingField;
|
|
458
|
+
(function (ShippingField) {
|
|
459
|
+
ShippingField["Price"] = "price";
|
|
460
|
+
ShippingField["FreeOver"] = "freeOver";
|
|
461
|
+
ShippingField["PickupAddress"] = "pickupAddress";
|
|
462
|
+
})(ShippingField || (ShippingField = {}));
|
|
463
|
+
const zero = (goods) => money(0, goods.currency);
|
|
464
|
+
const SHIPPING_KINDS = Object.freeze({
|
|
465
|
+
[ShippingMethodKind.Pickup]: {
|
|
466
|
+
needsAddress: false,
|
|
467
|
+
forPhysical: true,
|
|
468
|
+
requires: [ShippingField.PickupAddress],
|
|
469
|
+
price: (_method, goods) => zero(goods),
|
|
470
|
+
label: { en: 'Pickup', he: 'איסוף עצמי' },
|
|
471
|
+
},
|
|
472
|
+
[ShippingMethodKind.Flat]: {
|
|
473
|
+
needsAddress: true,
|
|
474
|
+
forPhysical: true,
|
|
475
|
+
requires: [ShippingField.Price],
|
|
476
|
+
price: (method) => method.price,
|
|
477
|
+
label: { en: 'Flat-rate delivery', he: 'משלוח במחיר קבוע' },
|
|
478
|
+
},
|
|
479
|
+
[ShippingMethodKind.FreeOver]: {
|
|
480
|
+
needsAddress: true,
|
|
481
|
+
forPhysical: true,
|
|
482
|
+
requires: [ShippingField.Price, ShippingField.FreeOver],
|
|
483
|
+
price: (method, goods) => goods.amount >= method.freeOver.amount ? zero(goods) : method.price,
|
|
484
|
+
label: { en: 'Delivery, free over an amount', he: 'משלוח, חינם מעל סכום' },
|
|
485
|
+
},
|
|
486
|
+
[ShippingMethodKind.Digital]: {
|
|
487
|
+
needsAddress: false,
|
|
488
|
+
forPhysical: false,
|
|
489
|
+
requires: [],
|
|
490
|
+
price: (_method, goods) => zero(goods),
|
|
491
|
+
label: { en: 'Digital — nothing shipped', he: 'דיגיטלי — ללא משלוח' },
|
|
492
|
+
},
|
|
493
|
+
});
|
|
494
|
+
const validAmount = (value, currency) => isMoney(value) && value.currency === currency && value.amount >= 0 && value.amount <= MAX_CART_AMOUNT;
|
|
495
|
+
const SHIPPING_FIELD_CHECKS = Object.freeze({
|
|
496
|
+
[ShippingField.Price]: (method, currency) => validAmount(method.price, currency),
|
|
497
|
+
[ShippingField.FreeOver]: (method, currency) => validAmount(method.freeOver, currency),
|
|
498
|
+
[ShippingField.PickupAddress]: (method) => filled(method.pickupAddress),
|
|
499
|
+
});
|
|
500
|
+
const isShippingMethodKind = (value) => typeof value === 'string' && Object.prototype.hasOwnProperty.call(SHIPPING_KINDS, value);
|
|
501
|
+
function shippingNeedsAddress(kind) {
|
|
502
|
+
return isShippingMethodKind(kind) && SHIPPING_KINDS[kind].needsAddress;
|
|
503
|
+
}
|
|
504
|
+
/** The fields a method lacks (or holds in another currency) — empty = it can be offered. */
|
|
505
|
+
function shippingMethodProblems(method, currency) {
|
|
506
|
+
if (!method || !isShippingMethodKind(method.kind))
|
|
507
|
+
return [ShippingField.Price];
|
|
508
|
+
return SHIPPING_KINDS[method.kind].requires.filter(field => !SHIPPING_FIELD_CHECKS[field](method, currency));
|
|
509
|
+
}
|
|
510
|
+
/** Enabled, complete, with an id and a name: the ONE rule both the offer and the checkout gate read. */
|
|
511
|
+
function shippingMethodReady(method, currency) {
|
|
512
|
+
return !!method && method.enabled === true && filled(method.id) && filled(method.name)
|
|
513
|
+
&& shippingMethodProblems(method, currency).length === 0;
|
|
514
|
+
}
|
|
515
|
+
function quoteShipping(methods, cart) {
|
|
516
|
+
const list = Array.isArray(methods) ? methods : [];
|
|
517
|
+
if (!cart.lineCount)
|
|
518
|
+
return [];
|
|
519
|
+
const seen = new Set();
|
|
520
|
+
return list
|
|
521
|
+
.filter(method => shippingMethodReady(method, cart.currency)
|
|
522
|
+
&& SHIPPING_KINDS[method.kind].forPhysical === cart.requiresShipping
|
|
523
|
+
&& !seen.has(method.id) && !!seen.add(method.id))
|
|
524
|
+
.map(method => {
|
|
525
|
+
const rule = SHIPPING_KINDS[method.kind];
|
|
526
|
+
const price = rule.price(method, cart.goods);
|
|
527
|
+
return {
|
|
528
|
+
methodId: method.id,
|
|
529
|
+
kind: method.kind,
|
|
530
|
+
name: method.name,
|
|
531
|
+
price: money(price.amount, price.currency),
|
|
532
|
+
free: method.kind === ShippingMethodKind.FreeOver && price.amount === 0,
|
|
533
|
+
needsAddress: rule.needsAddress,
|
|
534
|
+
};
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* The methods a buyer may choose for this cart, each priced for it (free over: free when the goods after
|
|
539
|
+
* discounts are AT or above the threshold). A cart where nothing ships is offered Digital methods only; a cart
|
|
540
|
+
* where anything ships never is.
|
|
541
|
+
*/
|
|
542
|
+
function availableShippingMethods(methods, pricedCart) {
|
|
543
|
+
return quoteShipping(methods, {
|
|
544
|
+
currency: pricedCart.currency,
|
|
545
|
+
goods: subtractMoney(pricedCart.subtotal, pricedCart.discount),
|
|
546
|
+
requiresShipping: pricedCart.requiresShipping,
|
|
547
|
+
lineCount: pricedCart.lines.length,
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
var CartIssueCode;
|
|
552
|
+
(function (CartIssueCode) {
|
|
553
|
+
/** Not a whole number ≥ 1: the line is dropped. */
|
|
554
|
+
CartIssueCode["InvalidQuantity"] = "invalid-quantity";
|
|
555
|
+
/** The same product and variant twice: merged into the first. */
|
|
556
|
+
CartIssueCode["DuplicateLine"] = "duplicate-line";
|
|
557
|
+
CartIssueCode["TooManyLines"] = "too-many-lines";
|
|
558
|
+
CartIssueCode["QuantityCapped"] = "quantity-capped";
|
|
559
|
+
CartIssueCode["UnknownProduct"] = "unknown-product";
|
|
560
|
+
/** The product exists, this variant does not (or the product needs a variant chosen). */
|
|
561
|
+
CartIssueCode["UnknownVariant"] = "unknown-variant";
|
|
562
|
+
CartIssueCode["Unpublished"] = "unpublished";
|
|
563
|
+
CartIssueCode["VariantDisabled"] = "variant-disabled";
|
|
564
|
+
CartIssueCode["NoPrice"] = "no-price";
|
|
565
|
+
CartIssueCode["CurrencyMismatch"] = "currency-mismatch";
|
|
566
|
+
CartIssueCode["OutOfStock"] = "out-of-stock";
|
|
567
|
+
/** Fewer left than asked: the line keeps what is left. */
|
|
568
|
+
CartIssueCode["QuantityClamped"] = "quantity-clamped";
|
|
569
|
+
/** The line would push the subtotal past `MAX_CART_AMOUNT`: dropped. */
|
|
570
|
+
CartIssueCode["AmountTooLarge"] = "amount-too-large";
|
|
571
|
+
/** The chosen shipping method is not offered for this cart: no shipping is priced. */
|
|
572
|
+
CartIssueCode["ShippingUnavailable"] = "shipping-unavailable";
|
|
573
|
+
/** The studio's VAT is not a usable rate: the VAT line reads 0. */
|
|
574
|
+
CartIssueCode["VatInvalid"] = "vat-invalid";
|
|
575
|
+
})(CartIssueCode || (CartIssueCode = {}));
|
|
576
|
+
const CART_ISSUE_LABELS = Object.freeze({
|
|
577
|
+
[CartIssueCode.InvalidQuantity]: { en: 'A quantity was not a whole number, so the item was removed.', he: 'כמות שאינה מספר שלם — הפריט הוסר.' },
|
|
578
|
+
[CartIssueCode.DuplicateLine]: { en: 'The same item appeared twice and was combined.', he: 'אותו פריט הופיע פעמיים ואוחד.' },
|
|
579
|
+
[CartIssueCode.TooManyLines]: { en: 'Your cart has too many different items; the last ones were removed.', he: 'יש בעגלה יותר מדי פריטים שונים; האחרונים הוסרו.' },
|
|
580
|
+
[CartIssueCode.QuantityCapped]: { en: 'That is more than one order can hold; the quantity was lowered.', he: 'הכמות גדולה מהמותר בהזמנה אחת, והיא הוקטנה.' },
|
|
581
|
+
[CartIssueCode.UnknownProduct]: { en: 'An item is no longer sold and was removed.', he: 'פריט כבר לא נמכר והוסר.' },
|
|
582
|
+
[CartIssueCode.UnknownVariant]: { en: 'An option of an item is no longer sold and was removed.', he: 'אפשרות של פריט כבר לא נמכרת והוסרה.' },
|
|
583
|
+
[CartIssueCode.Unpublished]: { en: 'An item is not on sale right now and was removed.', he: 'פריט אינו למכירה כרגע והוסר.' },
|
|
584
|
+
[CartIssueCode.VariantDisabled]: { en: 'An option of an item is not available and was removed.', he: 'אפשרות של פריט אינה זמינה והוסרה.' },
|
|
585
|
+
[CartIssueCode.NoPrice]: { en: 'An item has no price yet and was removed.', he: 'לפריט עדיין אין מחיר, והוא הוסר.' },
|
|
586
|
+
[CartIssueCode.CurrencyMismatch]: { en: 'An item is priced in another currency and was removed.', he: 'פריט מתומחר במטבע אחר והוסר.' },
|
|
587
|
+
[CartIssueCode.OutOfStock]: { en: 'An item is out of stock and was removed.', he: 'פריט אזל מהמלאי והוסר.' },
|
|
588
|
+
[CartIssueCode.QuantityClamped]: { en: 'Fewer are left than you asked for; your cart holds what is left.', he: 'נשארו פחות ממה שביקשתם; בעגלה מה שנשאר.' },
|
|
589
|
+
[CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
|
|
590
|
+
[CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
|
|
591
|
+
[CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
|
|
592
|
+
});
|
|
593
|
+
/** Checked in order; the first that refuses drops the line. */
|
|
594
|
+
const LINE_REFUSALS = Object.freeze([
|
|
595
|
+
{ code: CartIssueCode.Unpublished, refuses: (entry) => entry.published !== true },
|
|
596
|
+
{ code: CartIssueCode.VariantDisabled, refuses: (entry) => entry.enabled !== true },
|
|
597
|
+
{ code: CartIssueCode.NoPrice, refuses: (entry) => !isMoney(entry.unitPrice) || entry.unitPrice.amount < 0 },
|
|
598
|
+
{ code: CartIssueCode.CurrencyMismatch, refuses: (entry, currency) => entry.unitPrice.currency !== currency },
|
|
599
|
+
{ code: CartIssueCode.OutOfStock, refuses: (entry) => sellableQuantity(entry) === 0 },
|
|
600
|
+
]);
|
|
601
|
+
const isText = (value) => typeof value === 'string' && value !== '';
|
|
602
|
+
const variantOf = (line) => (isText(line.variantId) ? line.variantId : null);
|
|
603
|
+
const validQuantity = (quantity) => typeof quantity === 'number' && Number.isSafeInteger(quantity) && quantity >= 1;
|
|
604
|
+
/** Drops malformed lines, merges duplicates, keeps the first `MAX_CART_LINES` distinct ones. */
|
|
605
|
+
function wantedLines(cart, issues) {
|
|
606
|
+
const lines = cart && Array.isArray(cart.lines) ? cart.lines : [];
|
|
607
|
+
const byKey = new Map();
|
|
608
|
+
for (const line of lines) {
|
|
609
|
+
const productId = line && isText(line.productId) ? line.productId : '';
|
|
610
|
+
const variantId = line ? variantOf(line) : null;
|
|
611
|
+
if (!productId) {
|
|
612
|
+
issues.push({ code: CartIssueCode.UnknownProduct });
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
if (!validQuantity(line.quantity)) {
|
|
616
|
+
issues.push({ code: CartIssueCode.InvalidQuantity, productId, variantId });
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const key = catalogKey(productId, variantId);
|
|
620
|
+
const same = byKey.get(key);
|
|
621
|
+
if (same) {
|
|
622
|
+
same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
|
|
623
|
+
issues.push({ code: CartIssueCode.DuplicateLine, productId, variantId });
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
if (byKey.size >= MAX_CART_LINES) {
|
|
627
|
+
issues.push({ code: CartIssueCode.TooManyLines, productId, variantId });
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
byKey.set(key, { productId, variantId, quantity: line.quantity });
|
|
631
|
+
}
|
|
632
|
+
return [...byKey.values()];
|
|
633
|
+
}
|
|
634
|
+
function indexCatalog(catalog) {
|
|
635
|
+
const entries = new Map();
|
|
636
|
+
const products = new Set();
|
|
637
|
+
const list = Array.isArray(catalog) ? catalog : [];
|
|
638
|
+
for (const entry of list) {
|
|
639
|
+
if (!entry || !isText(entry.productId))
|
|
640
|
+
continue;
|
|
641
|
+
products.add(entry.productId);
|
|
642
|
+
const key = catalogKey(entry.productId, isText(entry.variantId) ? entry.variantId : null);
|
|
643
|
+
if (!entries.has(key))
|
|
644
|
+
entries.set(key, entry);
|
|
645
|
+
}
|
|
646
|
+
return { entries, products };
|
|
647
|
+
}
|
|
648
|
+
const compareAtOf = (entry, unitPrice) => isMoney(entry.compareAt) && entry.compareAt.currency === unitPrice.currency && entry.compareAt.amount > unitPrice.amount
|
|
649
|
+
? money(entry.compareAt.amount, entry.compareAt.currency)
|
|
650
|
+
: null;
|
|
651
|
+
function lineTotalWithin(unitPrice, quantity, subtotal) {
|
|
652
|
+
try {
|
|
653
|
+
const lineTotal = timesMoney(unitPrice, quantity);
|
|
654
|
+
return subtotal.amount + lineTotal.amount <= MAX_CART_AMOUNT ? lineTotal : null;
|
|
655
|
+
}
|
|
656
|
+
catch {
|
|
657
|
+
return null;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
|
|
662
|
+
* payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
|
|
663
|
+
* out is whole minor units in the studio currency. An unusable line is dropped or adjusted and SAID in `issues`.
|
|
664
|
+
*/
|
|
665
|
+
function priceCart(cart, catalog, studio, choice) {
|
|
666
|
+
const currency = studio.currency;
|
|
667
|
+
currencyExponent(currency);
|
|
668
|
+
const issues = [];
|
|
669
|
+
const { entries, products } = indexCatalog(catalog);
|
|
670
|
+
const lines = [];
|
|
671
|
+
let subtotal = money(0, currency);
|
|
672
|
+
for (const wanted of wantedLines(cart, issues)) {
|
|
673
|
+
const { productId, variantId } = wanted;
|
|
674
|
+
const entry = entries.get(catalogKey(productId, variantId));
|
|
675
|
+
if (!entry) {
|
|
676
|
+
issues.push({ code: products.has(productId) ? CartIssueCode.UnknownVariant : CartIssueCode.UnknownProduct, productId, variantId });
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
const refusal = LINE_REFUSALS.find(rule => rule.refuses(entry, currency));
|
|
680
|
+
if (refusal) {
|
|
681
|
+
issues.push({ code: refusal.code, productId, variantId, requested: wanted.quantity });
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
let quantity = wanted.quantity;
|
|
685
|
+
if (quantity > MAX_LINE_QUANTITY) {
|
|
686
|
+
quantity = MAX_LINE_QUANTITY;
|
|
687
|
+
issues.push({ code: CartIssueCode.QuantityCapped, productId, variantId, requested: wanted.quantity, quantity });
|
|
688
|
+
}
|
|
689
|
+
const left = sellableQuantity(entry);
|
|
690
|
+
if (left !== null && quantity > left) {
|
|
691
|
+
const requested = quantity;
|
|
692
|
+
quantity = left;
|
|
693
|
+
issues.push({ code: CartIssueCode.QuantityClamped, productId, variantId, requested, quantity });
|
|
694
|
+
}
|
|
695
|
+
const unitPrice = money(entry.unitPrice.amount, currency);
|
|
696
|
+
const lineTotal = lineTotalWithin(unitPrice, quantity, subtotal);
|
|
697
|
+
if (!lineTotal) {
|
|
698
|
+
issues.push({ code: CartIssueCode.AmountTooLarge, productId, variantId, requested: wanted.quantity });
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
subtotal = addMoney(subtotal, lineTotal);
|
|
702
|
+
lines.push({
|
|
703
|
+
productId,
|
|
704
|
+
variantId,
|
|
705
|
+
title: String(entry.title ?? ''),
|
|
706
|
+
variantName: isText(entry.variantName) ? entry.variantName : null,
|
|
707
|
+
quantity,
|
|
708
|
+
unitPrice,
|
|
709
|
+
compareAt: compareAtOf(entry, unitPrice),
|
|
710
|
+
lineTotal,
|
|
711
|
+
requiresShipping: entry.requiresShipping !== false,
|
|
712
|
+
image: isText(entry.image) ? entry.image : null,
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
const discount = money(0, currency);
|
|
716
|
+
const goods = subtractMoney(subtotal, discount);
|
|
717
|
+
const requiresShipping = lines.some(line => line.requiresShipping);
|
|
718
|
+
const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
|
|
719
|
+
const quotes = chosenId ? quoteShipping(studio.shippingMethods, { currency, goods, requiresShipping, lineCount: lines.length }) : [];
|
|
720
|
+
const shippingMethod = chosenId ? quotes.find(quote => quote.methodId === chosenId) ?? null : null;
|
|
721
|
+
if (chosenId && !shippingMethod)
|
|
722
|
+
issues.push({ code: CartIssueCode.ShippingUnavailable, shippingMethodId: chosenId });
|
|
723
|
+
const shipping = shippingMethod ? shippingMethod.price : money(0, currency);
|
|
724
|
+
const total = addMoney(goods, shipping);
|
|
725
|
+
const vatUsable = isVatPercent(studio.vatPercent);
|
|
726
|
+
if (!vatUsable)
|
|
727
|
+
issues.push({ code: CartIssueCode.VatInvalid });
|
|
728
|
+
return {
|
|
729
|
+
currency,
|
|
730
|
+
lines,
|
|
731
|
+
subtotal,
|
|
732
|
+
discount,
|
|
733
|
+
shipping,
|
|
734
|
+
shippingMethod,
|
|
735
|
+
requiresShipping,
|
|
736
|
+
total,
|
|
737
|
+
vat: vatUsable ? includedVat(total, studio.vatPercent) : money(0, currency),
|
|
738
|
+
vatPercent: vatUsable ? studio.vatPercent : 0,
|
|
739
|
+
issues,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
/** The cart a priced cart stands for — what to store back once the buyer has seen the issues. */
|
|
743
|
+
function cartOf(priced) {
|
|
744
|
+
return { lines: priced.lines.map(line => ({ productId: line.productId, variantId: line.variantId, quantity: line.quantity })) };
|
|
745
|
+
}
|
|
746
|
+
/** Sign-in merge (E3): b's lines join a's; the same product and variant add up. priceCart caps and clamps later. */
|
|
747
|
+
function mergeCarts(a, b) {
|
|
748
|
+
const merged = [];
|
|
749
|
+
const byKey = new Map();
|
|
750
|
+
const all = [...(Array.isArray(a?.lines) ? a.lines : []), ...(Array.isArray(b?.lines) ? b.lines : [])];
|
|
751
|
+
for (const line of all.filter(each => !!each && isText(each.productId))) {
|
|
752
|
+
const key = catalogKey(line.productId, variantOf(line));
|
|
753
|
+
const same = byKey.get(key);
|
|
754
|
+
if (same && validQuantity(same.quantity) && validQuantity(line.quantity)) {
|
|
755
|
+
same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
const copy = { productId: line.productId, variantId: variantOf(line), quantity: line.quantity };
|
|
759
|
+
if (!same)
|
|
760
|
+
byKey.set(key, copy);
|
|
761
|
+
merged.push(copy);
|
|
762
|
+
}
|
|
763
|
+
return { lines: merged };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
var PaymentChannel;
|
|
767
|
+
(function (PaymentChannel) {
|
|
768
|
+
/** The owner marks the order paid (C-D11). */
|
|
769
|
+
PaymentChannel["Manual"] = "manual";
|
|
770
|
+
/** The studio's PSP; only its verified callback marks the order paid. */
|
|
771
|
+
PaymentChannel["Online"] = "online";
|
|
772
|
+
})(PaymentChannel || (PaymentChannel = {}));
|
|
773
|
+
var PaymentMethodKind;
|
|
774
|
+
(function (PaymentMethodKind) {
|
|
775
|
+
PaymentMethodKind["BankTransfer"] = "bankTransfer";
|
|
776
|
+
PaymentMethodKind["PayOnPickup"] = "payOnPickup";
|
|
777
|
+
PaymentMethodKind["CashOnDelivery"] = "cashOnDelivery";
|
|
778
|
+
PaymentMethodKind["Bit"] = "bit";
|
|
779
|
+
/** A PSP's hosted page (E2, Cardcom first) — typed now, not offered yet. */
|
|
780
|
+
PaymentMethodKind["Online"] = "online";
|
|
781
|
+
})(PaymentMethodKind || (PaymentMethodKind = {}));
|
|
782
|
+
var PaymentProvider;
|
|
783
|
+
(function (PaymentProvider) {
|
|
784
|
+
PaymentProvider["Cardcom"] = "cardcom";
|
|
785
|
+
})(PaymentProvider || (PaymentProvider = {}));
|
|
786
|
+
/** What an owner fills for a method. */
|
|
787
|
+
var PaymentField;
|
|
788
|
+
(function (PaymentField) {
|
|
789
|
+
PaymentField["AccountName"] = "accountName";
|
|
790
|
+
PaymentField["Bank"] = "bank";
|
|
791
|
+
PaymentField["Branch"] = "branch";
|
|
792
|
+
PaymentField["AccountNumber"] = "accountNumber";
|
|
793
|
+
PaymentField["BitPhone"] = "bitPhone";
|
|
794
|
+
PaymentField["Provider"] = "provider";
|
|
795
|
+
})(PaymentField || (PaymentField = {}));
|
|
796
|
+
/** Which deliveries a method can be used with. */
|
|
797
|
+
var DeliveryFit;
|
|
798
|
+
(function (DeliveryFit) {
|
|
799
|
+
DeliveryFit["Any"] = "any";
|
|
800
|
+
/** Paid at the counter: only with a pickup method. */
|
|
801
|
+
DeliveryFit["PickupOnly"] = "pickupOnly";
|
|
802
|
+
/** Paid to the courier: only with a method that delivers to an address. */
|
|
803
|
+
DeliveryFit["AddressOnly"] = "addressOnly";
|
|
804
|
+
})(DeliveryFit || (DeliveryFit = {}));
|
|
805
|
+
const PAYMENT_METHODS = Object.freeze({
|
|
806
|
+
[PaymentMethodKind.BankTransfer]: {
|
|
807
|
+
channel: PaymentChannel.Manual,
|
|
808
|
+
offered: true,
|
|
809
|
+
fields: [PaymentField.AccountName, PaymentField.Bank, PaymentField.Branch, PaymentField.AccountNumber],
|
|
810
|
+
fit: DeliveryFit.Any,
|
|
811
|
+
label: { en: 'Bank transfer', he: 'העברה בנקאית' },
|
|
812
|
+
instructions: {
|
|
813
|
+
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.',
|
|
814
|
+
he: 'העבירו {total} לחשבון על שם {accountName}, בנק {bank}, סניף {branch}, חשבון {accountNumber}. ציינו את מספר ההזמנה {orderNumber} בפרטי ההעברה. נאשר את ההזמנה כשהכסף יגיע.',
|
|
815
|
+
},
|
|
816
|
+
},
|
|
817
|
+
[PaymentMethodKind.PayOnPickup]: {
|
|
818
|
+
channel: PaymentChannel.Manual,
|
|
819
|
+
offered: true,
|
|
820
|
+
fields: [],
|
|
821
|
+
fit: DeliveryFit.PickupOnly,
|
|
822
|
+
label: { en: 'Pay on pickup', he: 'תשלום באיסוף' },
|
|
823
|
+
instructions: {
|
|
824
|
+
en: 'Pay {total} when you pick up order {orderNumber}.',
|
|
825
|
+
he: 'שלמו {total} כשאתם אוספים את הזמנה {orderNumber}.',
|
|
826
|
+
},
|
|
827
|
+
},
|
|
828
|
+
[PaymentMethodKind.CashOnDelivery]: {
|
|
829
|
+
channel: PaymentChannel.Manual,
|
|
830
|
+
offered: true,
|
|
831
|
+
fields: [],
|
|
832
|
+
fit: DeliveryFit.AddressOnly,
|
|
833
|
+
label: { en: 'Cash on delivery', he: 'מזומן במסירה' },
|
|
834
|
+
instructions: {
|
|
835
|
+
en: 'Pay {total} in cash when order {orderNumber} is delivered.',
|
|
836
|
+
he: 'שלמו {total} במזומן כשהזמנה {orderNumber} נמסרת לכם.',
|
|
837
|
+
},
|
|
838
|
+
},
|
|
839
|
+
[PaymentMethodKind.Bit]: {
|
|
840
|
+
channel: PaymentChannel.Manual,
|
|
841
|
+
offered: true,
|
|
842
|
+
fields: [PaymentField.BitPhone],
|
|
843
|
+
fit: DeliveryFit.Any,
|
|
844
|
+
label: { en: 'Bit', he: 'ביט' },
|
|
845
|
+
instructions: {
|
|
846
|
+
en: 'Send {total} with Bit to {bitPhone}. Write order {orderNumber} in the note. We will confirm your order once the payment arrives.',
|
|
847
|
+
he: 'שלחו {total} בביט למספר {bitPhone}. ציינו את מספר ההזמנה {orderNumber} בהערה. נאשר את ההזמנה כשהתשלום יגיע.',
|
|
848
|
+
},
|
|
849
|
+
},
|
|
850
|
+
[PaymentMethodKind.Online]: {
|
|
851
|
+
channel: PaymentChannel.Online,
|
|
852
|
+
offered: false,
|
|
853
|
+
fields: [PaymentField.Provider],
|
|
854
|
+
fit: DeliveryFit.Any,
|
|
855
|
+
label: { en: 'Card', he: 'כרטיס אשראי' },
|
|
856
|
+
instructions: {
|
|
857
|
+
en: 'You will pay {total} for order {orderNumber} on a secure payment page.',
|
|
858
|
+
he: 'תשלמו {total} עבור הזמנה {orderNumber} בעמוד תשלום מאובטח.',
|
|
859
|
+
},
|
|
860
|
+
},
|
|
861
|
+
});
|
|
862
|
+
const PAYMENT_FIELD_LABELS = Object.freeze({
|
|
863
|
+
[PaymentField.AccountName]: { en: 'Account holder', he: 'שם בעל החשבון' },
|
|
864
|
+
[PaymentField.Bank]: { en: 'Bank', he: 'בנק' },
|
|
865
|
+
[PaymentField.Branch]: { en: 'Branch', he: 'סניף' },
|
|
866
|
+
[PaymentField.AccountNumber]: { en: 'Account number', he: 'מספר חשבון' },
|
|
867
|
+
[PaymentField.BitPhone]: { en: 'Phone number for Bit', he: 'מספר טלפון לביט' },
|
|
868
|
+
[PaymentField.Provider]: { en: 'Payment provider', he: 'ספק סליקה' },
|
|
869
|
+
});
|
|
870
|
+
const isPaymentProvider = (value) => typeof value === 'string' && Object.values(PaymentProvider).includes(value);
|
|
871
|
+
const PAYMENT_FIELD_CHECKS = Object.freeze({
|
|
872
|
+
[PaymentField.AccountName]: filled,
|
|
873
|
+
[PaymentField.Bank]: filled,
|
|
874
|
+
[PaymentField.Branch]: filled,
|
|
875
|
+
[PaymentField.AccountNumber]: filled,
|
|
876
|
+
[PaymentField.BitPhone]: looksLikeIsraeliMobile,
|
|
877
|
+
[PaymentField.Provider]: isPaymentProvider,
|
|
878
|
+
});
|
|
879
|
+
const DELIVERY_FITS = Object.freeze({
|
|
880
|
+
[DeliveryFit.Any]: () => true,
|
|
881
|
+
[DeliveryFit.PickupOnly]: (kind) => kind === ShippingMethodKind.Pickup,
|
|
882
|
+
[DeliveryFit.AddressOnly]: (kind) => !!kind && isShippingMethodKind(kind) && SHIPPING_KINDS[kind].needsAddress,
|
|
883
|
+
});
|
|
884
|
+
const isPaymentMethodKind = (value) => typeof value === 'string' && Object.prototype.hasOwnProperty.call(PAYMENT_METHODS, value);
|
|
885
|
+
function paymentChannelOf(kind) {
|
|
886
|
+
return PAYMENT_METHODS[kind].channel;
|
|
887
|
+
}
|
|
888
|
+
/** The fields a method lacks or holds in a form it cannot be paid with. */
|
|
889
|
+
function paymentMethodProblems(config) {
|
|
890
|
+
if (!config || !isPaymentMethodKind(config.kind))
|
|
891
|
+
return [];
|
|
892
|
+
const details = config.details ?? {};
|
|
893
|
+
return PAYMENT_METHODS[config.kind].fields.filter(field => !PAYMENT_FIELD_CHECKS[field](details[field]));
|
|
894
|
+
}
|
|
895
|
+
/** Enabled, offered in this phase, complete: the ONE rule the checkout and its gate read. */
|
|
896
|
+
function paymentMethodReady(config) {
|
|
897
|
+
return !!config && isPaymentMethodKind(config.kind) && config.enabled === true
|
|
898
|
+
&& PAYMENT_METHODS[config.kind].offered && paymentMethodProblems(config).length === 0;
|
|
899
|
+
}
|
|
900
|
+
/** The methods a buyer may pick with this delivery (null = nothing ships). */
|
|
901
|
+
function usablePaymentMethods(configs, shippingKind) {
|
|
902
|
+
const seen = new Set();
|
|
903
|
+
const list = Array.isArray(configs) ? configs : [];
|
|
904
|
+
return list.filter(config => paymentMethodReady(config)
|
|
905
|
+
&& DELIVERY_FITS[PAYMENT_METHODS[config.kind].fit](shippingKind ?? null)
|
|
906
|
+
&& !seen.has(config.kind) && !!seen.add(config.kind));
|
|
907
|
+
}
|
|
908
|
+
const LOCALES = Object.freeze({ [CommerceLanguage.En]: 'en-US', [CommerceLanguage.He]: 'he-IL' });
|
|
909
|
+
/** 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. */
|
|
910
|
+
function paymentInstructions(config, order, lang, locale) {
|
|
911
|
+
const rule = PAYMENT_METHODS[config.kind];
|
|
912
|
+
const values = {
|
|
913
|
+
...(config.details ?? {}),
|
|
914
|
+
orderNumber: order.orderNumber,
|
|
915
|
+
total: formatMoney(order.total, locale ?? LOCALES[commerceLanguage(lang)]),
|
|
916
|
+
};
|
|
917
|
+
const sentence = labelIn(rule.instructions, lang).replace(/\{(\w+)\}/g, (_match, name) => values[name] ?? '');
|
|
918
|
+
return filled(config.note) ? `${sentence}\n${config.note.trim()}` : sentence;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** C-D11 — the order's closed states. */
|
|
922
|
+
var OrderState;
|
|
923
|
+
(function (OrderState) {
|
|
924
|
+
/** A manual method: waiting for the owner to see the money. */
|
|
925
|
+
OrderState["AwaitingPayment"] = "awaiting_payment";
|
|
926
|
+
/** An online method: the PSP's page is open. */
|
|
927
|
+
OrderState["PendingPayment"] = "pending_payment";
|
|
928
|
+
OrderState["Paid"] = "paid";
|
|
929
|
+
OrderState["Fulfilled"] = "fulfilled";
|
|
930
|
+
OrderState["Delivered"] = "delivered";
|
|
931
|
+
OrderState["Cancelled"] = "cancelled";
|
|
932
|
+
OrderState["PaymentFailed"] = "payment_failed";
|
|
933
|
+
OrderState["Refunded"] = "refunded";
|
|
934
|
+
OrderState["PartiallyRefunded"] = "partially_refunded";
|
|
935
|
+
})(OrderState || (OrderState = {}));
|
|
936
|
+
var OrderEvent;
|
|
937
|
+
(function (OrderEvent) {
|
|
938
|
+
/** The buyer tries to pay again after a failure. */
|
|
939
|
+
OrderEvent["StartPayment"] = "startPayment";
|
|
940
|
+
/** The PSP's verified callback says paid. */
|
|
941
|
+
OrderEvent["ConfirmPayment"] = "confirmPayment";
|
|
942
|
+
OrderEvent["FailPayment"] = "failPayment";
|
|
943
|
+
/** The owner saw the money of a manual method. */
|
|
944
|
+
OrderEvent["MarkPaid"] = "markPaid";
|
|
945
|
+
OrderEvent["Fulfil"] = "fulfil";
|
|
946
|
+
OrderEvent["Deliver"] = "deliver";
|
|
947
|
+
OrderEvent["Cancel"] = "cancel";
|
|
948
|
+
/** Nobody paid in time (the jobs runner). */
|
|
949
|
+
OrderEvent["Expire"] = "expire";
|
|
950
|
+
OrderEvent["Refund"] = "refund";
|
|
951
|
+
OrderEvent["PartialRefund"] = "partialRefund";
|
|
952
|
+
})(OrderEvent || (OrderEvent = {}));
|
|
953
|
+
var OrderActor;
|
|
954
|
+
(function (OrderActor) {
|
|
955
|
+
OrderActor["Buyer"] = "buyer";
|
|
956
|
+
OrderActor["Owner"] = "owner";
|
|
957
|
+
/** A VERIFIED payment callback (trap T2) — never the browser's return redirect. */
|
|
958
|
+
OrderActor["PaymentCallback"] = "paymentCallback";
|
|
959
|
+
OrderActor["System"] = "system";
|
|
960
|
+
})(OrderActor || (OrderActor = {}));
|
|
961
|
+
/** What an order holds of the stock in a state (C-D10). */
|
|
962
|
+
var StockHold;
|
|
963
|
+
(function (StockHold) {
|
|
964
|
+
StockHold["None"] = "none";
|
|
965
|
+
/** Held for `STOCK_RESERVATION_MINUTES` while a PSP payment is open. */
|
|
966
|
+
StockHold["Reserved"] = "reserved";
|
|
967
|
+
/** Decremented: sold, or promised to a manual order. */
|
|
968
|
+
StockHold["Taken"] = "taken";
|
|
969
|
+
})(StockHold || (StockHold = {}));
|
|
970
|
+
/** What the server does to stock when an order moves — read from data, never decided per call site. */
|
|
971
|
+
var StockEffect;
|
|
972
|
+
(function (StockEffect) {
|
|
973
|
+
StockEffect["None"] = "none";
|
|
974
|
+
StockEffect["Reserve"] = "reserve";
|
|
975
|
+
StockEffect["CommitReservation"] = "commitReservation";
|
|
976
|
+
StockEffect["ReleaseReservation"] = "releaseReservation";
|
|
977
|
+
/** The conditional atomic decrement (E0's `takeStock`). */
|
|
978
|
+
StockEffect["Take"] = "take";
|
|
979
|
+
StockEffect["GiveBack"] = "giveBack";
|
|
980
|
+
})(StockEffect || (StockEffect = {}));
|
|
981
|
+
var OrderRefusal;
|
|
982
|
+
(function (OrderRefusal) {
|
|
983
|
+
/** The event does not apply in this state. */
|
|
984
|
+
OrderRefusal["InvalidTransition"] = "invalid-transition";
|
|
985
|
+
/** It applies — but not from this actor (e.g. the owner marking an online payment paid). */
|
|
986
|
+
OrderRefusal["ActorNotAllowed"] = "actor-not-allowed";
|
|
987
|
+
/** Cancelled and refunded orders move no more. */
|
|
988
|
+
OrderRefusal["OrderFinal"] = "order-final";
|
|
989
|
+
})(OrderRefusal || (OrderRefusal = {}));
|
|
990
|
+
const STOCK_RESERVATION_MINUTES = 15;
|
|
991
|
+
const ORDER_STOCK_HOLD = Object.freeze({
|
|
992
|
+
[OrderState.AwaitingPayment]: StockHold.Taken,
|
|
993
|
+
[OrderState.PendingPayment]: StockHold.Reserved,
|
|
994
|
+
[OrderState.Paid]: StockHold.Taken,
|
|
995
|
+
[OrderState.Fulfilled]: StockHold.Taken,
|
|
996
|
+
[OrderState.Delivered]: StockHold.Taken,
|
|
997
|
+
[OrderState.Cancelled]: StockHold.None,
|
|
998
|
+
[OrderState.PaymentFailed]: StockHold.None,
|
|
999
|
+
/** A refund never restocks by itself: whether the goods came back is the owner's to say. */
|
|
1000
|
+
[OrderState.Refunded]: StockHold.Taken,
|
|
1001
|
+
[OrderState.PartiallyRefunded]: StockHold.Taken,
|
|
1002
|
+
});
|
|
1003
|
+
/** from-hold → to-hold → effect. Taken → Reserved never happens (the transitions spec proves it). */
|
|
1004
|
+
const STOCK_EFFECTS = Object.freeze({
|
|
1005
|
+
[StockHold.None]: { [StockHold.None]: StockEffect.None, [StockHold.Reserved]: StockEffect.Reserve, [StockHold.Taken]: StockEffect.Take },
|
|
1006
|
+
[StockHold.Reserved]: { [StockHold.None]: StockEffect.ReleaseReservation, [StockHold.Reserved]: StockEffect.None, [StockHold.Taken]: StockEffect.CommitReservation },
|
|
1007
|
+
[StockHold.Taken]: { [StockHold.None]: StockEffect.GiveBack, [StockHold.Reserved]: StockEffect.None, [StockHold.Taken]: StockEffect.None },
|
|
1008
|
+
});
|
|
1009
|
+
const FINAL_ORDER_STATES = Object.freeze([OrderState.Cancelled, OrderState.Refunded]);
|
|
1010
|
+
const OWNER = [OrderActor.Owner];
|
|
1011
|
+
const CALLBACK = [OrderActor.PaymentCallback];
|
|
1012
|
+
const SYSTEM = [OrderActor.System];
|
|
1013
|
+
const REFUNDERS = [OrderActor.Owner, OrderActor.PaymentCallback];
|
|
1014
|
+
const REFUNDABLE = [OrderState.Paid, OrderState.Fulfilled, OrderState.Delivered, OrderState.PartiallyRefunded];
|
|
1015
|
+
/** THE order state machine (C-D11). Anything not listed is refused. */
|
|
1016
|
+
const ORDER_TRANSITIONS = Object.freeze([
|
|
1017
|
+
{ from: OrderState.AwaitingPayment, event: OrderEvent.MarkPaid, to: OrderState.Paid, actors: OWNER },
|
|
1018
|
+
{ from: OrderState.AwaitingPayment, event: OrderEvent.Cancel, to: OrderState.Cancelled, actors: OWNER },
|
|
1019
|
+
{ from: OrderState.AwaitingPayment, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
|
|
1020
|
+
{ from: OrderState.PendingPayment, event: OrderEvent.ConfirmPayment, to: OrderState.Paid, actors: CALLBACK },
|
|
1021
|
+
{ from: OrderState.PendingPayment, event: OrderEvent.FailPayment, to: OrderState.PaymentFailed, actors: CALLBACK },
|
|
1022
|
+
{ from: OrderState.PendingPayment, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
|
|
1023
|
+
{ from: OrderState.PaymentFailed, event: OrderEvent.StartPayment, to: OrderState.PendingPayment, actors: [OrderActor.Buyer] },
|
|
1024
|
+
{ from: OrderState.PaymentFailed, event: OrderEvent.ConfirmPayment, to: OrderState.Paid, actors: CALLBACK },
|
|
1025
|
+
{ from: OrderState.PaymentFailed, event: OrderEvent.Cancel, to: OrderState.Cancelled, actors: OWNER },
|
|
1026
|
+
{ from: OrderState.PaymentFailed, event: OrderEvent.Expire, to: OrderState.Cancelled, actors: SYSTEM },
|
|
1027
|
+
{ from: OrderState.Paid, event: OrderEvent.Fulfil, to: OrderState.Fulfilled, actors: OWNER },
|
|
1028
|
+
{ from: OrderState.PartiallyRefunded, event: OrderEvent.Fulfil, to: OrderState.Fulfilled, actors: OWNER },
|
|
1029
|
+
{ from: OrderState.Fulfilled, event: OrderEvent.Deliver, to: OrderState.Delivered, actors: OWNER },
|
|
1030
|
+
...REFUNDABLE.map(from => ({ from, event: OrderEvent.Refund, to: OrderState.Refunded, actors: REFUNDERS })),
|
|
1031
|
+
...REFUNDABLE.map(from => ({ from, event: OrderEvent.PartialRefund, to: OrderState.PartiallyRefunded, actors: REFUNDERS })),
|
|
1032
|
+
]);
|
|
1033
|
+
function stockEffect(from, to) {
|
|
1034
|
+
return STOCK_EFFECTS[from === null ? StockHold.None : ORDER_STOCK_HOLD[from]][ORDER_STOCK_HOLD[to]];
|
|
1035
|
+
}
|
|
1036
|
+
/** The ONE place an order moves: the next state and what to do to the stock, or why not. */
|
|
1037
|
+
function nextOrderState(state, event, actor) {
|
|
1038
|
+
const transition = ORDER_TRANSITIONS.find(each => each.from === state && each.event === event);
|
|
1039
|
+
if (!transition) {
|
|
1040
|
+
return { ok: false, refusal: FINAL_ORDER_STATES.includes(state) ? OrderRefusal.OrderFinal : OrderRefusal.InvalidTransition };
|
|
1041
|
+
}
|
|
1042
|
+
if (!transition.actors.includes(actor))
|
|
1043
|
+
return { ok: false, refusal: OrderRefusal.ActorNotAllowed };
|
|
1044
|
+
return { ok: true, state: transition.to, stock: stockEffect(state, transition.to) };
|
|
1045
|
+
}
|
|
1046
|
+
const OPENING_STATE = Object.freeze({
|
|
1047
|
+
[PaymentChannel.Manual]: OrderState.AwaitingPayment,
|
|
1048
|
+
[PaymentChannel.Online]: OrderState.PendingPayment,
|
|
1049
|
+
});
|
|
1050
|
+
/** A new order's state and stock effect: a manual order takes its stock at once, an online one reserves it. */
|
|
1051
|
+
function openingOrderState(kind) {
|
|
1052
|
+
const state = OPENING_STATE[paymentChannelOf(kind)];
|
|
1053
|
+
return { state, stock: stockEffect(null, state) };
|
|
1054
|
+
}
|
|
1055
|
+
function reservationExpiresAt(now) {
|
|
1056
|
+
return new Date(now.getTime() + STOCK_RESERVATION_MINUTES * 60000);
|
|
1057
|
+
}
|
|
1058
|
+
const ORDER_STATE_LABELS = Object.freeze({
|
|
1059
|
+
[OrderState.AwaitingPayment]: { en: 'Awaiting payment', he: 'ממתינה לתשלום' },
|
|
1060
|
+
[OrderState.PendingPayment]: { en: 'Payment in progress', he: 'תשלום בתהליך' },
|
|
1061
|
+
[OrderState.Paid]: { en: 'Paid', he: 'שולמה' },
|
|
1062
|
+
[OrderState.Fulfilled]: { en: 'Fulfilled', he: 'טופלה' },
|
|
1063
|
+
[OrderState.Delivered]: { en: 'Delivered', he: 'נמסרה' },
|
|
1064
|
+
[OrderState.Cancelled]: { en: 'Cancelled', he: 'בוטלה' },
|
|
1065
|
+
[OrderState.PaymentFailed]: { en: 'Payment failed', he: 'התשלום נכשל' },
|
|
1066
|
+
[OrderState.Refunded]: { en: 'Refunded', he: 'זוכתה' },
|
|
1067
|
+
[OrderState.PartiallyRefunded]: { en: 'Partly refunded', he: 'זוכתה חלקית' },
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
/** The fixed checkout's steps, in order (C-D3); a checkout keeps the FURTHEST it reached (the journey, §3g). */
|
|
1071
|
+
var CheckoutStep;
|
|
1072
|
+
(function (CheckoutStep) {
|
|
1073
|
+
CheckoutStep["Contact"] = "contact";
|
|
1074
|
+
CheckoutStep["Delivery"] = "delivery";
|
|
1075
|
+
CheckoutStep["Payment"] = "payment";
|
|
1076
|
+
CheckoutStep["Paid"] = "paid";
|
|
1077
|
+
})(CheckoutStep || (CheckoutStep = {}));
|
|
1078
|
+
const CHECKOUT_STEPS = Object.freeze([
|
|
1079
|
+
CheckoutStep.Contact,
|
|
1080
|
+
CheckoutStep.Delivery,
|
|
1081
|
+
CheckoutStep.Payment,
|
|
1082
|
+
CheckoutStep.Paid,
|
|
1083
|
+
]);
|
|
1084
|
+
const CHECKOUT_STEP_LABELS = Object.freeze({
|
|
1085
|
+
[CheckoutStep.Contact]: { en: 'Contact', he: 'פרטי קשר' },
|
|
1086
|
+
[CheckoutStep.Delivery]: { en: 'Delivery', he: 'משלוח' },
|
|
1087
|
+
[CheckoutStep.Payment]: { en: 'Payment', he: 'תשלום' },
|
|
1088
|
+
[CheckoutStep.Paid]: { en: 'Paid', he: 'שולם' },
|
|
1089
|
+
});
|
|
1090
|
+
function furthestStep(a, b) {
|
|
1091
|
+
const rank = (step) => (step ? CHECKOUT_STEPS.indexOf(step) : -1);
|
|
1092
|
+
const best = rank(a) >= rank(b) ? a : b;
|
|
1093
|
+
return best && CHECKOUT_STEPS.includes(best) ? best : CheckoutStep.Contact;
|
|
1094
|
+
}
|
|
1095
|
+
/** The pages the OWNER writes and links from checkout (§3k). IOX never writes their text (T14). */
|
|
1096
|
+
var LegalPage;
|
|
1097
|
+
(function (LegalPage) {
|
|
1098
|
+
LegalPage["Terms"] = "terms";
|
|
1099
|
+
LegalPage["Returns"] = "returns";
|
|
1100
|
+
LegalPage["Shipping"] = "shipping";
|
|
1101
|
+
LegalPage["Privacy"] = "privacy";
|
|
1102
|
+
})(LegalPage || (LegalPage = {}));
|
|
1103
|
+
var CheckoutGateArea;
|
|
1104
|
+
(function (CheckoutGateArea) {
|
|
1105
|
+
CheckoutGateArea["Payment"] = "payment";
|
|
1106
|
+
CheckoutGateArea["Money"] = "money";
|
|
1107
|
+
CheckoutGateArea["Shipping"] = "shipping";
|
|
1108
|
+
CheckoutGateArea["Business"] = "business";
|
|
1109
|
+
CheckoutGateArea["LegalPages"] = "legalPages";
|
|
1110
|
+
})(CheckoutGateArea || (CheckoutGateArea = {}));
|
|
1111
|
+
var CheckoutGateCode;
|
|
1112
|
+
(function (CheckoutGateCode) {
|
|
1113
|
+
CheckoutGateCode["NoPaymentMethod"] = "no-payment-method";
|
|
1114
|
+
CheckoutGateCode["CurrencyNotSet"] = "currency-not-set";
|
|
1115
|
+
CheckoutGateCode["VatNotSet"] = "vat-not-set";
|
|
1116
|
+
CheckoutGateCode["NoShippingMethod"] = "no-shipping-method";
|
|
1117
|
+
CheckoutGateCode["BusinessNameMissing"] = "business-name-missing";
|
|
1118
|
+
CheckoutGateCode["BusinessNumberMissing"] = "business-number-missing";
|
|
1119
|
+
CheckoutGateCode["BusinessAddressMissing"] = "business-address-missing";
|
|
1120
|
+
CheckoutGateCode["BusinessEmailMissing"] = "business-email-missing";
|
|
1121
|
+
CheckoutGateCode["BusinessPhoneMissing"] = "business-phone-missing";
|
|
1122
|
+
CheckoutGateCode["TermsPageMissing"] = "terms-page-missing";
|
|
1123
|
+
CheckoutGateCode["ReturnsPageMissing"] = "returns-page-missing";
|
|
1124
|
+
CheckoutGateCode["ShippingPageMissing"] = "shipping-page-missing";
|
|
1125
|
+
CheckoutGateCode["PrivacyPageMissing"] = "privacy-page-missing";
|
|
1126
|
+
})(CheckoutGateCode || (CheckoutGateCode = {}));
|
|
1127
|
+
const ships = (facts) => facts.anyProductShips === true;
|
|
1128
|
+
const page = (facts, which) => facts.legalPages?.[which] === true;
|
|
1129
|
+
const business = (facts) => facts.business ?? {};
|
|
1130
|
+
/** THE checkout gate (C-D19), in the order the owner fixes things. The server refuses with it; the admin shows the same rows. */
|
|
1131
|
+
const CHECKOUT_GATE_RULES = Object.freeze([
|
|
1132
|
+
{
|
|
1133
|
+
code: CheckoutGateCode.NoPaymentMethod,
|
|
1134
|
+
area: CheckoutGateArea.Payment,
|
|
1135
|
+
refuses: (facts) => !(facts.paymentMethods ?? []).some(paymentMethodReady),
|
|
1136
|
+
label: { en: 'Turn on a way to get paid', he: 'הפעילו אמצעי תשלום' },
|
|
1137
|
+
},
|
|
1138
|
+
{
|
|
1139
|
+
code: CheckoutGateCode.CurrencyNotSet,
|
|
1140
|
+
area: CheckoutGateArea.Money,
|
|
1141
|
+
refuses: (facts) => !isCurrencyCode(facts.currency),
|
|
1142
|
+
label: { en: 'Set the shop\'s currency', he: 'הגדירו את מטבע החנות' },
|
|
1143
|
+
},
|
|
1144
|
+
{
|
|
1145
|
+
code: CheckoutGateCode.VatNotSet,
|
|
1146
|
+
area: CheckoutGateArea.Money,
|
|
1147
|
+
refuses: (facts) => !isVatPercent(facts.vatPercent),
|
|
1148
|
+
label: { en: 'Set the VAT rate', he: 'הגדירו את שיעור המע"מ' },
|
|
1149
|
+
},
|
|
1150
|
+
{
|
|
1151
|
+
code: CheckoutGateCode.NoShippingMethod,
|
|
1152
|
+
area: CheckoutGateArea.Shipping,
|
|
1153
|
+
refuses: (facts) => ships(facts) && !(isCurrencyCode(facts.currency)
|
|
1154
|
+
&& (facts.shippingMethods ?? []).some(method => shippingMethodReady(method, facts.currency)
|
|
1155
|
+
&& SHIPPING_KINDS[method.kind].forPhysical)),
|
|
1156
|
+
label: { en: 'Add a delivery or pickup method', he: 'הוסיפו שיטת משלוח או איסוף' },
|
|
1157
|
+
},
|
|
1158
|
+
{
|
|
1159
|
+
code: CheckoutGateCode.BusinessNameMissing,
|
|
1160
|
+
area: CheckoutGateArea.Business,
|
|
1161
|
+
refuses: (facts) => !filled(business(facts).legalName),
|
|
1162
|
+
label: { en: 'Add the business\'s legal name', he: 'הוסיפו את השם הרשמי של העסק' },
|
|
1163
|
+
},
|
|
1164
|
+
{
|
|
1165
|
+
code: CheckoutGateCode.BusinessNumberMissing,
|
|
1166
|
+
area: CheckoutGateArea.Business,
|
|
1167
|
+
refuses: (facts) => !filled(business(facts).businessNumber),
|
|
1168
|
+
label: { en: 'Add the business number (company or VAT dealer number)', he: 'הוסיפו מספר עוסק או ח.פ' },
|
|
1169
|
+
},
|
|
1170
|
+
{
|
|
1171
|
+
code: CheckoutGateCode.BusinessAddressMissing,
|
|
1172
|
+
area: CheckoutGateArea.Business,
|
|
1173
|
+
refuses: (facts) => !filled(business(facts).address),
|
|
1174
|
+
label: { en: 'Add the business address', he: 'הוסיפו את כתובת העסק' },
|
|
1175
|
+
},
|
|
1176
|
+
{
|
|
1177
|
+
code: CheckoutGateCode.BusinessEmailMissing,
|
|
1178
|
+
area: CheckoutGateArea.Business,
|
|
1179
|
+
refuses: (facts) => !looksLikeEmail(business(facts).email),
|
|
1180
|
+
label: { en: 'Add an email buyers can write to', he: 'הוסיפו כתובת אימייל לפניות קונים' },
|
|
1181
|
+
},
|
|
1182
|
+
{
|
|
1183
|
+
code: CheckoutGateCode.BusinessPhoneMissing,
|
|
1184
|
+
area: CheckoutGateArea.Business,
|
|
1185
|
+
refuses: (facts) => !looksLikePhone(business(facts).phone),
|
|
1186
|
+
label: { en: 'Add a phone number buyers can call', he: 'הוסיפו מספר טלפון לפניות קונים' },
|
|
1187
|
+
},
|
|
1188
|
+
{
|
|
1189
|
+
code: CheckoutGateCode.TermsPageMissing,
|
|
1190
|
+
area: CheckoutGateArea.LegalPages,
|
|
1191
|
+
refuses: (facts) => !page(facts, LegalPage.Terms),
|
|
1192
|
+
label: { en: 'Write your terms of sale page', he: 'כתבו עמוד תקנון ותנאי מכירה' },
|
|
1193
|
+
},
|
|
1194
|
+
{
|
|
1195
|
+
code: CheckoutGateCode.ReturnsPageMissing,
|
|
1196
|
+
area: CheckoutGateArea.LegalPages,
|
|
1197
|
+
refuses: (facts) => !page(facts, LegalPage.Returns),
|
|
1198
|
+
label: { en: 'Write your returns and cancellation page', he: 'כתבו עמוד מדיניות החזרות וביטולים' },
|
|
1199
|
+
},
|
|
1200
|
+
{
|
|
1201
|
+
code: CheckoutGateCode.ShippingPageMissing,
|
|
1202
|
+
area: CheckoutGateArea.LegalPages,
|
|
1203
|
+
refuses: (facts) => ships(facts) && !page(facts, LegalPage.Shipping),
|
|
1204
|
+
label: { en: 'Write your shipping page', he: 'כתבו עמוד מדיניות משלוחים' },
|
|
1205
|
+
},
|
|
1206
|
+
{
|
|
1207
|
+
code: CheckoutGateCode.PrivacyPageMissing,
|
|
1208
|
+
area: CheckoutGateArea.LegalPages,
|
|
1209
|
+
refuses: (facts) => !page(facts, LegalPage.Privacy),
|
|
1210
|
+
label: { en: 'Write your privacy page', he: 'כתבו עמוד מדיניות פרטיות' },
|
|
1211
|
+
},
|
|
1212
|
+
]);
|
|
1213
|
+
/** Checkout opens only when no rule refuses (C-D19, trap T9: the server's, never a hidden button). */
|
|
1214
|
+
function checkoutGate(facts) {
|
|
1215
|
+
const refusals = CHECKOUT_GATE_RULES
|
|
1216
|
+
.filter(rule => rule.refuses(facts))
|
|
1217
|
+
.map(rule => ({ code: rule.code, area: rule.area, label: rule.label }));
|
|
1218
|
+
return { open: refusals.length === 0, refusals };
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
var OrderSnapshotRefusal;
|
|
1222
|
+
(function (OrderSnapshotRefusal) {
|
|
1223
|
+
OrderSnapshotRefusal["EmptyCart"] = "empty-cart";
|
|
1224
|
+
/** The priced cart has issues the buyer has not seen: show them the priced cart first. */
|
|
1225
|
+
OrderSnapshotRefusal["CartChanged"] = "cart-changed";
|
|
1226
|
+
OrderSnapshotRefusal["ShippingNotChosen"] = "shipping-not-chosen";
|
|
1227
|
+
OrderSnapshotRefusal["AddressRequired"] = "address-required";
|
|
1228
|
+
OrderSnapshotRefusal["EmailRequired"] = "email-required";
|
|
1229
|
+
OrderSnapshotRefusal["NameRequired"] = "name-required";
|
|
1230
|
+
/** Not enabled, not complete, not offered yet, or not usable with this delivery. */
|
|
1231
|
+
OrderSnapshotRefusal["PaymentMethodUnusable"] = "payment-method-unusable";
|
|
1232
|
+
})(OrderSnapshotRefusal || (OrderSnapshotRefusal = {}));
|
|
1233
|
+
function deepFreeze(value) {
|
|
1234
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
1235
|
+
Object.freeze(value);
|
|
1236
|
+
for (const key of Object.keys(value))
|
|
1237
|
+
deepFreeze(value[key]);
|
|
1238
|
+
}
|
|
1239
|
+
return value;
|
|
1240
|
+
}
|
|
1241
|
+
const copyMoney = (value) => money(value.amount, value.currency);
|
|
1242
|
+
const text$1 = (value) => (filled(value) ? value.trim() : null);
|
|
1243
|
+
function copyAddress(address) {
|
|
1244
|
+
if (!address || !filled(address.line1) || !filled(address.city) || !filled(address.country))
|
|
1245
|
+
return null;
|
|
1246
|
+
return {
|
|
1247
|
+
line1: address.line1.trim(),
|
|
1248
|
+
line2: text$1(address.line2),
|
|
1249
|
+
city: address.city.trim(),
|
|
1250
|
+
postalCode: text$1(address.postalCode),
|
|
1251
|
+
country: address.country.trim(),
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
const SNAPSHOT_RULES = Object.freeze([
|
|
1255
|
+
{ refusal: OrderSnapshotRefusal.EmptyCart, refuses: (priced) => !priced.lines.length },
|
|
1256
|
+
{ refusal: OrderSnapshotRefusal.CartChanged, refuses: (priced) => priced.issues.length > 0 },
|
|
1257
|
+
{ refusal: OrderSnapshotRefusal.ShippingNotChosen, refuses: (priced) => priced.requiresShipping && !priced.shippingMethod },
|
|
1258
|
+
{
|
|
1259
|
+
refusal: OrderSnapshotRefusal.AddressRequired,
|
|
1260
|
+
refuses: (priced, _payment, buyer) => !!priced.shippingMethod?.needsAddress && !copyAddress(buyer?.address),
|
|
1261
|
+
},
|
|
1262
|
+
{ refusal: OrderSnapshotRefusal.EmailRequired, refuses: (_priced, _payment, buyer) => !looksLikeEmail(buyer?.email) },
|
|
1263
|
+
{ refusal: OrderSnapshotRefusal.NameRequired, refuses: (_priced, _payment, buyer) => !filled(buyer?.name) },
|
|
1264
|
+
{
|
|
1265
|
+
refusal: OrderSnapshotRefusal.PaymentMethodUnusable,
|
|
1266
|
+
refuses: (priced, payment) => usablePaymentMethods([payment], priced.shippingMethod?.kind ?? null).length === 0,
|
|
1267
|
+
},
|
|
1268
|
+
]);
|
|
1269
|
+
/** Freezes what an order stores (lines, unit prices, totals, VAT, currency, delivery, payment, buyer) — or says why it cannot. */
|
|
1270
|
+
function orderSnapshot(pricedCart, payment, buyer) {
|
|
1271
|
+
const refusals = SNAPSHOT_RULES.filter(rule => rule.refuses(pricedCart, payment, buyer)).map(rule => rule.refusal);
|
|
1272
|
+
if (refusals.length)
|
|
1273
|
+
return { ok: false, refusals };
|
|
1274
|
+
const delivery = pricedCart.shippingMethod;
|
|
1275
|
+
const snapshot = {
|
|
1276
|
+
currency: pricedCart.currency,
|
|
1277
|
+
lines: pricedCart.lines.map(line => ({
|
|
1278
|
+
productId: line.productId,
|
|
1279
|
+
variantId: line.variantId,
|
|
1280
|
+
title: line.title,
|
|
1281
|
+
variantName: line.variantName,
|
|
1282
|
+
quantity: line.quantity,
|
|
1283
|
+
unitPrice: copyMoney(line.unitPrice),
|
|
1284
|
+
lineTotal: copyMoney(line.lineTotal),
|
|
1285
|
+
requiresShipping: line.requiresShipping,
|
|
1286
|
+
})),
|
|
1287
|
+
subtotal: copyMoney(pricedCart.subtotal),
|
|
1288
|
+
discount: copyMoney(pricedCart.discount),
|
|
1289
|
+
shipping: copyMoney(pricedCart.shipping),
|
|
1290
|
+
delivery: delivery ? { methodId: delivery.methodId, kind: delivery.kind, name: delivery.name } : null,
|
|
1291
|
+
total: copyMoney(pricedCart.total),
|
|
1292
|
+
vat: { percent: pricedCart.vatPercent, amount: copyMoney(pricedCart.vat) },
|
|
1293
|
+
payment: {
|
|
1294
|
+
kind: payment.kind,
|
|
1295
|
+
channel: paymentChannelOf(payment.kind),
|
|
1296
|
+
details: { ...(payment.details ?? {}) },
|
|
1297
|
+
note: text$1(payment.note),
|
|
1298
|
+
},
|
|
1299
|
+
buyer: {
|
|
1300
|
+
email: buyer.email.trim(),
|
|
1301
|
+
name: buyer.name.trim(),
|
|
1302
|
+
phone: text$1(buyer.phone),
|
|
1303
|
+
address: delivery?.needsAddress ? copyAddress(buyer.address) : null,
|
|
1304
|
+
},
|
|
1305
|
+
};
|
|
1306
|
+
return { ok: true, snapshot: deepFreeze(snapshot) };
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/**
|
|
1310
|
+
* A product's OPTIONS and its VARIANTS as the storefront serves them (iox-cms `storefront-projection.ts`), read into
|
|
1311
|
+
* what a product page needs (commerce plan §3i, trap T26): which values each option offers, which of them can still be
|
|
1312
|
+
* bought given what is already chosen, and the variant a full choice names.
|
|
1313
|
+
*
|
|
1314
|
+
* A stored variant has no option map, only a flat NAME — the option values in option order joined by `-` (the admin's
|
|
1315
|
+
* `product.component.ts` `generateCombinations`: "Red-M"). A name is matched against every combination of the options'
|
|
1316
|
+
* values, never split on `-`, so a value that holds a `-` ("Off-white") still reads.
|
|
1317
|
+
*/
|
|
1318
|
+
const VARIANT_NAME_SEPARATOR = '-';
|
|
1319
|
+
/** The one variant row a product with no options keeps (iox-cms `DEFAULT_VARIANT_NAME`). */
|
|
1320
|
+
const DEFAULT_VARIANT_NAME = 'Default';
|
|
1321
|
+
const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
1322
|
+
const text = (value) => (typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
|
|
1323
|
+
/** True for something the storefront could have served as a product: a title and a price or variants. */
|
|
1324
|
+
function isStorefrontProduct(value) {
|
|
1325
|
+
return isRecord(value) && typeof value['title'] === 'string' && (isRecord(value['pricing']) || Array.isArray(value['variants']));
|
|
1326
|
+
}
|
|
1327
|
+
/** The product's currency, or null when it names none we know (a price is then never shown — never guessed). */
|
|
1328
|
+
function productCurrency(product) {
|
|
1329
|
+
const code = text(product?.currency).toUpperCase();
|
|
1330
|
+
return isCurrencyCode(code) ? code : null;
|
|
1331
|
+
}
|
|
1332
|
+
/** The options a product offers, cleaned: named, each value once, no empty value. None when it has no variants. */
|
|
1333
|
+
function productOptions(product) {
|
|
1334
|
+
if (!product?.productVariants || !Array.isArray(product.options))
|
|
1335
|
+
return [];
|
|
1336
|
+
const out = [];
|
|
1337
|
+
for (const raw of product.options) {
|
|
1338
|
+
const name = text(raw?.name);
|
|
1339
|
+
if (!name || out.some(o => o.name === name))
|
|
1340
|
+
continue;
|
|
1341
|
+
const values = [];
|
|
1342
|
+
for (const v of Array.isArray(raw?.values) ? raw.values : []) {
|
|
1343
|
+
const value = text(v);
|
|
1344
|
+
if (value && !values.includes(value))
|
|
1345
|
+
values.push(value);
|
|
1346
|
+
}
|
|
1347
|
+
if (values.length)
|
|
1348
|
+
out.push({ name, values });
|
|
1349
|
+
}
|
|
1350
|
+
return out;
|
|
1351
|
+
}
|
|
1352
|
+
/** Every full choice of `options`, in the admin's order, with the variant name it writes. */
|
|
1353
|
+
function combinations(options) {
|
|
1354
|
+
let acc = [{ parts: [], choice: {} }];
|
|
1355
|
+
for (const option of options) {
|
|
1356
|
+
const next = [];
|
|
1357
|
+
for (const partial of acc) {
|
|
1358
|
+
for (const value of option.values)
|
|
1359
|
+
next.push({ parts: [...partial.parts, value], choice: { ...partial.choice, [option.name]: value } });
|
|
1360
|
+
}
|
|
1361
|
+
acc = next;
|
|
1362
|
+
}
|
|
1363
|
+
return acc.map(c => ({ name: c.parts.join(VARIANT_NAME_SEPARATOR), choice: c.choice }));
|
|
1364
|
+
}
|
|
1365
|
+
/** The choice a stored variant's flat name stands for, or null when no combination of the options writes it. */
|
|
1366
|
+
function variantChoiceOf(variant, options) {
|
|
1367
|
+
const name = text(variant?.name);
|
|
1368
|
+
if (!name || !options.length)
|
|
1369
|
+
return null;
|
|
1370
|
+
return combinations(options).find(c => c.name === name)?.choice ?? null;
|
|
1371
|
+
}
|
|
1372
|
+
/** A stored major-unit price as Money, or null (no price, a currency we do not know, a value that is no price). */
|
|
1373
|
+
function storefrontMoney(value, currency) {
|
|
1374
|
+
if (!currency)
|
|
1375
|
+
return null;
|
|
1376
|
+
if (isMoney(value))
|
|
1377
|
+
return value.currency === currency ? value : null;
|
|
1378
|
+
if (typeof value !== 'number' && typeof value !== 'string')
|
|
1379
|
+
return null;
|
|
1380
|
+
if (typeof value === 'string' && value.trim() === '')
|
|
1381
|
+
return null;
|
|
1382
|
+
try {
|
|
1383
|
+
return money(majorToMinor(value, currency), currency);
|
|
1384
|
+
}
|
|
1385
|
+
catch {
|
|
1386
|
+
const minor = migrateMajorPrice(value, currency);
|
|
1387
|
+
return minor === null ? null : money(minor, currency);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
const AVAILABILITIES = Object.values(Availability);
|
|
1391
|
+
function availabilityOf(value, enabled) {
|
|
1392
|
+
if (!enabled)
|
|
1393
|
+
return Availability.Out;
|
|
1394
|
+
return AVAILABILITIES.includes(text(value)) ? text(value) : Availability.InStock;
|
|
1395
|
+
}
|
|
1396
|
+
function aboveOnly(compareAt, price) {
|
|
1397
|
+
return compareAt && price && compareAt.amount > price.amount ? compareAt : null;
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Every variant of a product, read. A product with no options is ONE view: its Default row's id (or null when it has
|
|
1401
|
+
* no row) and the product's own price. A variant whose name matches no combination of the options is left out — the
|
|
1402
|
+
* page cannot offer what it cannot name.
|
|
1403
|
+
*/
|
|
1404
|
+
function productVariants(product) {
|
|
1405
|
+
if (!product)
|
|
1406
|
+
return [];
|
|
1407
|
+
const currency = productCurrency(product);
|
|
1408
|
+
const options = productOptions(product);
|
|
1409
|
+
const rows = Array.isArray(product.variants) ? product.variants.filter(isRecord) : [];
|
|
1410
|
+
const view = (row, choice, priceRaw, compareRaw, image, availability) => {
|
|
1411
|
+
const enabled = row?.enable !== false;
|
|
1412
|
+
const price = storefrontMoney(priceRaw, currency);
|
|
1413
|
+
const state = availabilityOf(availability, enabled);
|
|
1414
|
+
return {
|
|
1415
|
+
variantId: text(row?._id) || null,
|
|
1416
|
+
name: text(row?.name) || null,
|
|
1417
|
+
choice,
|
|
1418
|
+
price,
|
|
1419
|
+
compareAt: aboveOnly(storefrontMoney(compareRaw, currency), price),
|
|
1420
|
+
image: text(image) || null,
|
|
1421
|
+
availability: state,
|
|
1422
|
+
enabled,
|
|
1423
|
+
sellable: enabled && !!price && state !== Availability.Out,
|
|
1424
|
+
};
|
|
1425
|
+
};
|
|
1426
|
+
if (!options.length) {
|
|
1427
|
+
const row = rows.find(r => r.name === DEFAULT_VARIANT_NAME) ?? (rows.length === 1 ? rows[0] : null);
|
|
1428
|
+
const pricing = product.pricing ?? {};
|
|
1429
|
+
return [view(row, {}, row?.price ?? pricing.price, row?.compareat ?? pricing.compareat, row?.image || product.mainImage, row?.availability ?? product.availability)];
|
|
1430
|
+
}
|
|
1431
|
+
const out = [];
|
|
1432
|
+
for (const row of rows) {
|
|
1433
|
+
const choice = variantChoiceOf(row, options);
|
|
1434
|
+
if (choice)
|
|
1435
|
+
out.push(view(row, choice, row.price, row.compareat, row.image || product.mainImage, row.availability));
|
|
1436
|
+
}
|
|
1437
|
+
return out;
|
|
1438
|
+
}
|
|
1439
|
+
const matches = (variant, choice, names) => names.every(name => choice[name] === undefined || variant.choice[name] === choice[name]);
|
|
1440
|
+
/** The variant a FULL choice names, or null (a choice that misses an option, or names no stored variant). */
|
|
1441
|
+
function findVariant(options, variants, choice) {
|
|
1442
|
+
if (!options.length)
|
|
1443
|
+
return variants[0] ?? null;
|
|
1444
|
+
if (options.some(o => !choice[o.name]))
|
|
1445
|
+
return null;
|
|
1446
|
+
return variants.find(v => options.every(o => v.choice[o.name] === choice[o.name])) ?? null;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* What each option offers now. Availability CASCADES in option order (the way a buyer reads the page, top to bottom):
|
|
1450
|
+
* a value of the first option is available when ANY sellable variant has it; a value of a later option, when a
|
|
1451
|
+
* sellable variant has it together with the values chosen for the options before it. So a buyer can always change an
|
|
1452
|
+
* earlier option and the later ones follow (`chooseValue`) — never stuck behind a combination that is sold out.
|
|
1453
|
+
*/
|
|
1454
|
+
function optionValueStates(options, variants, choice) {
|
|
1455
|
+
const sellable = variants.filter(v => v.sellable);
|
|
1456
|
+
return options.map((option, index) => {
|
|
1457
|
+
const before = options.slice(0, index).map(o => o.name);
|
|
1458
|
+
return {
|
|
1459
|
+
name: option.name,
|
|
1460
|
+
values: option.values.map(value => ({
|
|
1461
|
+
value,
|
|
1462
|
+
available: sellable.some(v => v.choice[option.name] === value && matches(v, choice, before)),
|
|
1463
|
+
selected: choice[option.name] === value,
|
|
1464
|
+
})),
|
|
1465
|
+
};
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
/** The choice a page opens with: the first sellable variant's, else the first value of every option. */
|
|
1469
|
+
function defaultChoice(options, variants) {
|
|
1470
|
+
const first = variants.find(v => v.sellable && options.every(o => v.choice[o.name]));
|
|
1471
|
+
if (first)
|
|
1472
|
+
return { ...first.choice };
|
|
1473
|
+
return Object.fromEntries(options.map(o => [o.name, o.values[0]]));
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* The buyer picks `value` for option `name`. The options AFTER it keep their value while it is still available after
|
|
1477
|
+
* the change, else move to their first available value (else keep it — the page then says the combination is sold out).
|
|
1478
|
+
* An unknown option or value changes nothing.
|
|
1479
|
+
*/
|
|
1480
|
+
function chooseValue(options, variants, choice, name, value) {
|
|
1481
|
+
const at = options.findIndex(o => o.name === name);
|
|
1482
|
+
if (at < 0 || !options[at].values.includes(value))
|
|
1483
|
+
return choice;
|
|
1484
|
+
const next = { ...choice, [name]: value };
|
|
1485
|
+
for (let i = at + 1; i < options.length; i++) {
|
|
1486
|
+
const state = optionValueStates(options, variants, next)[i];
|
|
1487
|
+
const keeps = state.values.find(v => v.value === next[options[i].name])?.available;
|
|
1488
|
+
if (keeps)
|
|
1489
|
+
continue;
|
|
1490
|
+
const first = state.values.find(v => v.available);
|
|
1491
|
+
if (first)
|
|
1492
|
+
next[options[i].name] = first.value;
|
|
1493
|
+
}
|
|
1494
|
+
return next;
|
|
1495
|
+
}
|
|
1496
|
+
/** The catalog entries a storefront product sells (one per variant, or one for a product with no options) — what
|
|
1497
|
+
* `priceCart` reads where only the storefront is known (the builder canvas's simulated cart). iox-cms builds its own
|
|
1498
|
+
* from the stored row, with the stock COUNT. */
|
|
1499
|
+
function storefrontCatalog(product) {
|
|
1500
|
+
const productId = text(product?._id);
|
|
1501
|
+
if (!product || !productId)
|
|
1502
|
+
return [];
|
|
1503
|
+
const hasOptions = productOptions(product).length > 0;
|
|
1504
|
+
return productVariants(product).map(v => ({
|
|
1505
|
+
productId,
|
|
1506
|
+
variantId: hasOptions ? v.variantId : null,
|
|
1507
|
+
title: text(product.title),
|
|
1508
|
+
variantName: hasOptions ? Object.values(v.choice).join(' · ') : null,
|
|
1509
|
+
unitPrice: v.price,
|
|
1510
|
+
compareAt: v.compareAt,
|
|
1511
|
+
availability: v.availability,
|
|
1512
|
+
enabled: v.enabled,
|
|
1513
|
+
published: true,
|
|
1514
|
+
requiresShipping: true,
|
|
1515
|
+
image: v.image,
|
|
1516
|
+
}));
|
|
1517
|
+
}
|
|
1518
|
+
/** The words a chosen variant is shown with in a cart line ("Sand · 32 cm"). */
|
|
1519
|
+
function variantWords(choice, options) {
|
|
1520
|
+
return options.map(o => choice[o.name]).filter(Boolean).join(' · ');
|
|
1521
|
+
}
|
|
1522
|
+
// ── the product in scope ─────────────────────────────────────────────────────────────────────
|
|
1523
|
+
/** The data keys a product page's own item sits under (the route's item first — relative data sources). */
|
|
1524
|
+
const ROUTE_KEYS = ['$current', '$route'];
|
|
1525
|
+
/**
|
|
1526
|
+
* The product an element is about, the SAME rule on the builder canvas and the live site: the repeated row it sits in
|
|
1527
|
+
* when that row is a product (a card in a product list), else the page's route item, else the first product the page's
|
|
1528
|
+
* data holds (a product page bound to one product). Null when the page has none.
|
|
1529
|
+
*/
|
|
1530
|
+
function productInScope(rowItem, data) {
|
|
1531
|
+
if (isStorefrontProduct(rowItem))
|
|
1532
|
+
return rowItem;
|
|
1533
|
+
const all = data ?? {};
|
|
1534
|
+
for (const key of ROUTE_KEYS)
|
|
1535
|
+
if (isStorefrontProduct(all[key]))
|
|
1536
|
+
return all[key];
|
|
1537
|
+
for (const value of Object.values(all))
|
|
1538
|
+
if (isStorefrontProduct(value))
|
|
1539
|
+
return value;
|
|
1540
|
+
return null;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/**
|
|
1544
|
+
* The quantity a buyer may ask for — the stepper on a product page and on every cart line (commerce plan §3i). Whole
|
|
1545
|
+
* numbers only, the forms-core number rule: anything that is not a whole number reads as the least. The most is the
|
|
1546
|
+
* one-line cap (`MAX_LINE_QUANTITY`), lowered to the count when the count is known (iox-cms) — the storefront knows only
|
|
1547
|
+
* a word, so it caps at the line cap and the server clamps (`priceCart` QuantityClamped).
|
|
1548
|
+
*/
|
|
1549
|
+
const MIN_LINE_QUANTITY = 1;
|
|
1550
|
+
var QuantityStep;
|
|
1551
|
+
(function (QuantityStep) {
|
|
1552
|
+
QuantityStep[QuantityStep["Down"] = -1] = "Down";
|
|
1553
|
+
QuantityStep[QuantityStep["Up"] = 1] = "Up";
|
|
1554
|
+
})(QuantityStep || (QuantityStep = {}));
|
|
1555
|
+
/** What a stepper allows for a unit with this count / word. `out` (or a count of 0) allows nothing. */
|
|
1556
|
+
function quantityBounds(unit) {
|
|
1557
|
+
if (typeof unit?.stock === 'number') {
|
|
1558
|
+
const left = Number.isSafeInteger(unit.stock) && unit.stock > 0 ? unit.stock : 0;
|
|
1559
|
+
return { min: MIN_LINE_QUANTITY, max: Math.min(MAX_LINE_QUANTITY, left) };
|
|
1560
|
+
}
|
|
1561
|
+
if (unit?.availability === Availability.Out)
|
|
1562
|
+
return { min: MIN_LINE_QUANTITY, max: 0 };
|
|
1563
|
+
return { min: MIN_LINE_QUANTITY, max: MAX_LINE_QUANTITY };
|
|
1564
|
+
}
|
|
1565
|
+
/** True when the bounds allow buying at all. */
|
|
1566
|
+
function canBuy(bounds) {
|
|
1567
|
+
return bounds.max >= bounds.min;
|
|
1568
|
+
}
|
|
1569
|
+
/** A quantity held within the bounds; not a whole number → the least. */
|
|
1570
|
+
function clampQuantity(value, bounds) {
|
|
1571
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
|
1572
|
+
if (!Number.isSafeInteger(n))
|
|
1573
|
+
return bounds.min;
|
|
1574
|
+
if (!canBuy(bounds))
|
|
1575
|
+
return bounds.min;
|
|
1576
|
+
return Math.min(bounds.max, Math.max(bounds.min, n));
|
|
1577
|
+
}
|
|
1578
|
+
/** True when a step in `direction` stays within the bounds. */
|
|
1579
|
+
function canStep(value, direction, bounds) {
|
|
1580
|
+
if (!canBuy(bounds))
|
|
1581
|
+
return false;
|
|
1582
|
+
const next = clampQuantity(value, bounds) + direction;
|
|
1583
|
+
return next >= bounds.min && next <= bounds.max;
|
|
1584
|
+
}
|
|
1585
|
+
/** One step, held within the bounds. */
|
|
1586
|
+
function stepQuantity(value, direction, bounds) {
|
|
1587
|
+
return clampQuantity(clampQuantity(value, bounds) + direction, bounds);
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
var CartTransportErrorCode;
|
|
1591
|
+
(function (CartTransportErrorCode) {
|
|
1592
|
+
/** No cart on this host (the engine before E1d, a site with no shop). */
|
|
1593
|
+
CartTransportErrorCode["Unavailable"] = "unavailable";
|
|
1594
|
+
/** The server said no (a product no longer sold, a rate limit). */
|
|
1595
|
+
CartTransportErrorCode["Refused"] = "refused";
|
|
1596
|
+
/** The call never reached the server. */
|
|
1597
|
+
CartTransportErrorCode["Network"] = "network";
|
|
1598
|
+
})(CartTransportErrorCode || (CartTransportErrorCode = {}));
|
|
1599
|
+
const CART_TRANSPORT_ERROR_LABELS = Object.freeze({
|
|
1600
|
+
[CartTransportErrorCode.Unavailable]: { en: 'The shop is not open yet.', he: 'החנות עוד לא פתוחה.' },
|
|
1601
|
+
[CartTransportErrorCode.Refused]: { en: 'That could not be added to your bag.', he: 'לא ניתן היה להוסיף לסל.' },
|
|
1602
|
+
[CartTransportErrorCode.Network]: { en: 'We could not reach the shop. Try again.', he: 'לא הצלחנו להגיע לחנות. נסו שוב.' },
|
|
1603
|
+
});
|
|
1604
|
+
class CartTransportError extends Error {
|
|
1605
|
+
constructor(code, message) {
|
|
1606
|
+
super(message ?? code);
|
|
1607
|
+
this.code = code;
|
|
1608
|
+
this.name = 'CartTransportError';
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
/** A line's id when the host has none of its own: the product and the variant, URL-safe. */
|
|
1612
|
+
function cartLineId(productId, variantId) {
|
|
1613
|
+
return `${encodeURIComponent(productId)}~${encodeURIComponent(variantId ?? '')}`;
|
|
1614
|
+
}
|
|
1615
|
+
/** The public cart routes (§3d) — ROOT-relative, like the forms submit path (a relative path under the org's
|
|
1616
|
+
* `<base href>` reaches the engine, never iox-cms). `lineId` addresses one line. */
|
|
1617
|
+
function cartEndpointPath(orgId, lineId) {
|
|
1618
|
+
const base = `/api/site/${encodeURIComponent(orgId)}/cart`;
|
|
1619
|
+
return lineId ? `${base}/lines/${encodeURIComponent(lineId)}` : base;
|
|
1620
|
+
}
|
|
1621
|
+
/** The fixed checkout route (C-D3), relative to the site's `<base href="/<orgLabel>/">`. */
|
|
1622
|
+
const CHECKOUT_PATH = 'checkout';
|
|
1623
|
+
/** The checkout's href: `/<orgLabel>/checkout` under a label, else `/checkout`. */
|
|
1624
|
+
function checkoutHref(orgLabel) {
|
|
1625
|
+
const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
|
|
1626
|
+
return label ? `/${encodeURIComponent(label)}/${CHECKOUT_PATH}` : `/${CHECKOUT_PATH}`;
|
|
1627
|
+
}
|
|
1628
|
+
/** A cart with nothing in it. */
|
|
1629
|
+
function emptyCartView(currency = null) {
|
|
1630
|
+
return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
|
|
1631
|
+
}
|
|
1632
|
+
/** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
|
|
1633
|
+
* `maxOf` says how many a line may hold (default the line cap). */
|
|
1634
|
+
function cartViewOf(priced, options = {}) {
|
|
1635
|
+
const lineIdOf = options.lineIdOf ?? (line => cartLineId(line.productId, line.variantId));
|
|
1636
|
+
const maxOf = options.maxOf ?? (() => MAX_LINE_QUANTITY);
|
|
1637
|
+
const lines = priced.lines.map(line => ({ ...line, lineId: lineIdOf(line), maxQuantity: Math.max(line.quantity, maxOf(line)) }));
|
|
1638
|
+
const count = lines.reduce((sum, line) => sum + line.quantity, 0);
|
|
1639
|
+
return {
|
|
1640
|
+
currency: priced.currency,
|
|
1641
|
+
lines,
|
|
1642
|
+
count,
|
|
1643
|
+
empty: lines.length === 0,
|
|
1644
|
+
subtotal: priced.subtotal,
|
|
1645
|
+
total: priced.total,
|
|
1646
|
+
vat: priced.vat,
|
|
1647
|
+
vatPercent: priced.vatPercent,
|
|
1648
|
+
issues: priced.issues,
|
|
1649
|
+
freeShippingRemaining: options.freeShippingRemaining ?? null,
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
/** iox-cms's answer as the view the parts paint — the server's line ids, its prices untouched. */
|
|
1653
|
+
function siteCartView(site, freeShippingRemaining = null) {
|
|
1654
|
+
const ids = new Map(site.lines.map(line => [line, line.id]));
|
|
1655
|
+
return cartViewOf(site, { lineIdOf: line => ids.get(line) ?? cartLineId(line.productId, line.variantId), freeShippingRemaining });
|
|
1656
|
+
}
|
|
1657
|
+
/** How a refused cart call is said: no cart service (501, 503) or a shop off the plan (403) is Unavailable, a
|
|
1658
|
+
* status the server chose is Refused, anything that never got an answer is Network. */
|
|
1659
|
+
function cartTransportErrorFor(status) {
|
|
1660
|
+
if (!status)
|
|
1661
|
+
return new CartTransportError(CartTransportErrorCode.Network);
|
|
1662
|
+
if (status === 501 || status === 503 || status === 403)
|
|
1663
|
+
return new CartTransportError(CartTransportErrorCode.Unavailable, String(status));
|
|
1664
|
+
return new CartTransportError(CartTransportErrorCode.Refused, String(status));
|
|
1665
|
+
}
|
|
1666
|
+
/** The words a cart's issues are said with, once each. */
|
|
1667
|
+
function cartIssueWords(view, lang) {
|
|
1668
|
+
const codes = [...new Set(view.issues.map(i => i.code))];
|
|
1669
|
+
return codes.map(code => labelIn(CART_ISSUE_LABELS[code], lang));
|
|
1670
|
+
}
|
|
1671
|
+
/** The host with no cart yet (the engine until E1d binds its own): every read is an empty cart, every change refused. */
|
|
1672
|
+
const NO_CART_TRANSPORT = Object.freeze({
|
|
1673
|
+
read: () => Promise.resolve(emptyCartView()),
|
|
1674
|
+
add: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
1675
|
+
setQuantity: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
1676
|
+
remove: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
1677
|
+
});
|
|
1678
|
+
function simulatedCartTransport(catalog, studio, initial = { lines: [] }) {
|
|
1679
|
+
const entries = new Map();
|
|
1680
|
+
const known = (list) => list.forEach(e => entries.set(catalogKey(e.productId, e.variantId), e));
|
|
1681
|
+
known(catalog);
|
|
1682
|
+
let cart = { lines: [] };
|
|
1683
|
+
const maxOf = (line) => quantityBounds(entries.get(catalogKey(line.productId, line.variantId))).max;
|
|
1684
|
+
const price = (next) => {
|
|
1685
|
+
const priced = priceCart(next, [...entries.values()], studio);
|
|
1686
|
+
cart = cartOf(priced);
|
|
1687
|
+
return cartViewOf(priced, { maxOf });
|
|
1688
|
+
};
|
|
1689
|
+
price(initial);
|
|
1690
|
+
const lineOf = (lineId) => cart.lines.find(l => cartLineId(l.productId, l.variantId) === lineId);
|
|
1691
|
+
return {
|
|
1692
|
+
addEntries: list => known(list),
|
|
1693
|
+
peek: () => price(cart),
|
|
1694
|
+
read: () => Promise.resolve(price(cart)),
|
|
1695
|
+
add: request => {
|
|
1696
|
+
if (!entries.has(catalogKey(request.productId, request.variantId)))
|
|
1697
|
+
return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
|
|
1698
|
+
const same = cart.lines.find(l => l.productId === request.productId && (l.variantId ?? null) === (request.variantId ?? null));
|
|
1699
|
+
const lines = same
|
|
1700
|
+
? cart.lines.map(l => (l === same ? { ...l, quantity: l.quantity + request.quantity } : l))
|
|
1701
|
+
: [...cart.lines, { productId: request.productId, variantId: request.variantId ?? null, quantity: request.quantity }];
|
|
1702
|
+
return Promise.resolve(price({ lines }));
|
|
1703
|
+
},
|
|
1704
|
+
setQuantity: (lineId, quantity) => {
|
|
1705
|
+
const line = lineOf(lineId);
|
|
1706
|
+
if (!line)
|
|
1707
|
+
return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
|
|
1708
|
+
return Promise.resolve(price({ lines: cart.lines.map(l => (l === line ? { ...l, quantity } : l)) }));
|
|
1709
|
+
},
|
|
1710
|
+
remove: lineId => Promise.resolve(price({ lines: cart.lines.filter(l => l !== lineOf(lineId)) })),
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
/**
|
|
1715
|
+
* How a price READS on a page — the `money` binding pipe (shop-aware plan A-D2, amended by C-D7) on the builder canvas,
|
|
1716
|
+
* the engine's SSR and its hydration: ONE function, so the three never disagree on a digit.
|
|
1717
|
+
*
|
|
1718
|
+
* - a `Money` (minor units + its currency — `$variant.price`, a cart's totals) is formatted as it is;
|
|
1719
|
+
* - a bare number or numeric string (`pricing.price` as the storefront serves it: MAJOR units) needs a currency — the
|
|
1720
|
+
* pipe's own argument, else the studio's (`PipeContext.currency`); with none it is left as it was, never guessed;
|
|
1721
|
+
* - nothing (null, undefined, '') reads as nothing.
|
|
1722
|
+
* The locale is the page's language (`en` when unsaid, so the canvas and the server agree).
|
|
1723
|
+
*/
|
|
1724
|
+
const DEFAULT_MONEY_LOCALE = 'en';
|
|
1725
|
+
function formatMoneyValue(value, currency, locale) {
|
|
1726
|
+
if (value === null || value === undefined || value === '')
|
|
1727
|
+
return '';
|
|
1728
|
+
const lang = locale || DEFAULT_MONEY_LOCALE;
|
|
1729
|
+
if (isMoney(value)) {
|
|
1730
|
+
try {
|
|
1731
|
+
return formatMoney(value, lang);
|
|
1732
|
+
}
|
|
1733
|
+
catch {
|
|
1734
|
+
return value;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
const code = String(currency ?? '').trim().toUpperCase();
|
|
1738
|
+
if (!isCurrencyCode(code))
|
|
1739
|
+
return value;
|
|
1740
|
+
const amount = storefrontMoney(value, code);
|
|
1741
|
+
if (!amount)
|
|
1742
|
+
return value;
|
|
1743
|
+
try {
|
|
1744
|
+
return formatMoney(amount, lang);
|
|
1745
|
+
}
|
|
1746
|
+
catch {
|
|
1747
|
+
return value;
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
/**
|
|
1751
|
+
* The two slots the shop parts write at runtime (the element-context channel — a slot is a `resolvedData` key written
|
|
1752
|
+
* at runtime, element-context-state plan): the variant the buyer has chosen (`$variant.price | money`) and the cart
|
|
1753
|
+
* (`$cart.count` on the cart button's badge). Written by the shop runtime through its host, read by ordinary bindings.
|
|
1754
|
+
*/
|
|
1755
|
+
var ShopSlot;
|
|
1756
|
+
(function (ShopSlot) {
|
|
1757
|
+
ShopSlot["Variant"] = "$variant";
|
|
1758
|
+
ShopSlot["Cart"] = "$cart";
|
|
1759
|
+
})(ShopSlot || (ShopSlot = {}));
|
|
1760
|
+
const SHOP_SLOTS = Object.freeze(Object.values(ShopSlot));
|
|
1761
|
+
// ── the shop parts' words (a string-rendered site has no translation service — the labels.ts rule) ──────────────
|
|
1762
|
+
var ShopWord;
|
|
1763
|
+
(function (ShopWord) {
|
|
1764
|
+
ShopWord["Added"] = "added";
|
|
1765
|
+
ShopWord["SoldOut"] = "soldOut";
|
|
1766
|
+
ShopWord["ValueSoldOut"] = "valueSoldOut";
|
|
1767
|
+
ShopWord["Decrease"] = "decrease";
|
|
1768
|
+
ShopWord["Increase"] = "increase";
|
|
1769
|
+
ShopWord["Remove"] = "remove";
|
|
1770
|
+
ShopWord["Cart"] = "cart";
|
|
1771
|
+
ShopWord["CartCount"] = "cartCount";
|
|
1772
|
+
ShopWord["Quantity"] = "quantity";
|
|
1773
|
+
ShopWord["FreeShippingGap"] = "freeShippingGap";
|
|
1774
|
+
ShopWord["ChooseOption"] = "chooseOption";
|
|
1775
|
+
})(ShopWord || (ShopWord = {}));
|
|
1776
|
+
/** `{name}` / `{n}` / `{amount}` are filled by `shopWord`. */
|
|
1777
|
+
const SHOP_WORDS = Object.freeze({
|
|
1778
|
+
[ShopWord.Added]: { en: 'Added ✓', he: 'נוסף ✓' },
|
|
1779
|
+
[ShopWord.SoldOut]: { en: 'Sold out', he: 'אזל' },
|
|
1780
|
+
[ShopWord.ValueSoldOut]: { en: '{name} is sold out', he: '{name} אזל מהמלאי' },
|
|
1781
|
+
[ShopWord.Decrease]: { en: 'Decrease quantity', he: 'הפחתת כמות' },
|
|
1782
|
+
[ShopWord.Increase]: { en: 'Increase quantity', he: 'הגדלת כמות' },
|
|
1783
|
+
[ShopWord.Remove]: { en: 'Remove {name}', he: 'הסרת {name}' },
|
|
1784
|
+
[ShopWord.Cart]: { en: 'Bag', he: 'סל' },
|
|
1785
|
+
[ShopWord.CartCount]: { en: 'Bag, {n} items', he: 'סל, {n} פריטים' },
|
|
1786
|
+
[ShopWord.Quantity]: { en: 'Quantity', he: 'כמות' },
|
|
1787
|
+
[ShopWord.FreeShippingGap]: { en: 'Add {amount} more for free delivery', he: 'עוד {amount} למשלוח חינם' },
|
|
1788
|
+
[ShopWord.ChooseOption]: { en: 'Choose {name}', he: 'בחירת {name}' },
|
|
1789
|
+
});
|
|
1790
|
+
function shopWord(word, lang, fill = {}) {
|
|
1791
|
+
const primary = String(lang ?? '').toLowerCase().split(/[-_]/)[0];
|
|
1792
|
+
const label = SHOP_WORDS[word];
|
|
1793
|
+
const raw = primary === 'he' || primary === 'iw' ? label.he : label.en;
|
|
1794
|
+
return raw.replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
|
|
1795
|
+
}
|
|
1796
|
+
// ── the sample a canvas shows when no product is bound (commerce board 10, "Studio Kadar") ────────────────────────
|
|
1797
|
+
/** Board 10's tall speckled vase: Glaze (Sand · Ash · Charcoal — Charcoal sold out) × Size (24 · 32 · 40 cm — 40 sold
|
|
1798
|
+
* out), ₪240 against ₪280. Major units, as the storefront serves them. */
|
|
1799
|
+
const SAMPLE_PRODUCT = Object.freeze({
|
|
1800
|
+
_id: 'sample-vase',
|
|
1801
|
+
title: 'Tall speckled vase',
|
|
1802
|
+
slug: 'tall-speckled-vase',
|
|
1803
|
+
mainImage: null,
|
|
1804
|
+
productVariants: true,
|
|
1805
|
+
currency: CurrencyCode.ILS,
|
|
1806
|
+
availability: 'in_stock',
|
|
1807
|
+
pricing: { price: 240, compareat: 280 },
|
|
1808
|
+
options: [
|
|
1809
|
+
{ name: 'Glaze', values: ['Sand', 'Ash', 'Charcoal'] },
|
|
1810
|
+
{ name: 'Size', values: ['24 cm', '32 cm', '40 cm'] },
|
|
1811
|
+
],
|
|
1812
|
+
// Rows in the order a page opens on: Sand · 32 cm first (the first sellable row is the default choice).
|
|
1813
|
+
variants: ['Sand', 'Ash', 'Charcoal'].flatMap(glaze => ['32 cm', '24 cm', '40 cm'].map(size => ({
|
|
1814
|
+
_id: `sample-${glaze}-${size}`.toLowerCase().replace(/\s+/g, ''),
|
|
1815
|
+
name: `${glaze}-${size}`,
|
|
1816
|
+
enable: true,
|
|
1817
|
+
image: null,
|
|
1818
|
+
price: size === '24 cm' ? 190 : 240,
|
|
1819
|
+
compareat: size === '32 cm' ? 280 : null,
|
|
1820
|
+
availability: glaze === 'Charcoal' || size === '40 cm' ? 'out' : 'in_stock',
|
|
1821
|
+
}))),
|
|
1822
|
+
});
|
|
1823
|
+
/** The colours board 10 draws its sample glazes with (a sample value has no colour of its own). */
|
|
1824
|
+
const SAMPLE_SWATCHES = Object.freeze({ Sand: '#D8C6A8', Ash: '#F3F1EC', Charcoal: '#3A3B3D' });
|
|
1825
|
+
/** The sample studio's money (VAT 18 %, ₪). */
|
|
1826
|
+
const SAMPLE_STUDIO = Object.freeze({ currency: CurrencyCode.ILS, vatPercent: 18, shippingMethods: [] });
|
|
1827
|
+
/** The cart the canvas starts with: one sample line, so the drawer has a line to design. */
|
|
1828
|
+
const SAMPLE_CART_LINE = Object.freeze({ productId: 'sample-vase', variantId: 'sample-sand-32cm', quantity: 1 });
|
|
1829
|
+
|
|
1830
|
+
/**
|
|
1831
|
+
* @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7…C-D11, C-D19).
|
|
329
1832
|
*
|
|
330
|
-
* Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms
|
|
331
|
-
*
|
|
332
|
-
*
|
|
1833
|
+
* Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms compute the same
|
|
1834
|
+
* totals (trap T6: never a float). E0 shipped Money; E1a adds the cart and its ONE pricing function, shipping v1,
|
|
1835
|
+
* manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot. No clock is
|
|
1836
|
+
* read anywhere — a caller passes `now`.
|
|
333
1837
|
* ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
|
|
334
1838
|
* jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
|
|
335
1839
|
*/
|
|
@@ -338,5 +1842,5 @@ function migrateMajorPrice(value, currency) {
|
|
|
338
1842
|
* Generated bundle index. Do not edit.
|
|
339
1843
|
*/
|
|
340
1844
|
|
|
341
|
-
export { CURRENCY_CODES, CURRENCY_EXPONENTS, CurrencyCode, MoneyError, MoneyErrorCode, addMoney, currencyExponent, formatMoney, isCurrencyCode, isMoney, majorToMinor, migrateMajorPrice, minorToMajor, money, percentOf, subtractMoney, timesMoney };
|
|
1845
|
+
export { Availability, CART_ISSUE_LABELS, CART_TRANSPORT_ERROR_LABELS, CHECKOUT_GATE_RULES, CHECKOUT_PATH, CHECKOUT_STEPS, CHECKOUT_STEP_LABELS, CURRENCY_CODES, CURRENCY_EXPONENTS, CartIssueCode, CartTransportError, CartTransportErrorCode, CheckoutGateArea, CheckoutGateCode, CheckoutStep, CommerceLanguage, CurrencyCode, DEFAULT_MONEY_LOCALE, DEFAULT_VARIANT_NAME, DeliveryFit, FINAL_ORDER_STATES, LegalPage, MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY, MAX_VAT_PERCENT, MIN_LINE_QUANTITY, MoneyError, MoneyErrorCode, NO_CART_TRANSPORT, ORDER_STATE_LABELS, ORDER_STOCK_HOLD, ORDER_TRANSITIONS, OrderActor, OrderEvent, OrderRefusal, OrderSnapshotRefusal, OrderState, PAYMENT_FIELD_LABELS, PAYMENT_METHODS, PaymentChannel, PaymentField, PaymentMethodKind, PaymentProvider, QuantityStep, SAMPLE_CART_LINE, SAMPLE_PRODUCT, SAMPLE_STUDIO, SAMPLE_SWATCHES, SHIPPING_KINDS, SHOP_SLOTS, SHOP_WORDS, STOCK_EFFECTS, STOCK_RESERVATION_MINUTES, ShippingField, ShippingMethodKind, ShopSlot, ShopWord, StockEffect, StockHold, VARIANT_NAME_SEPARATOR, VAT_PERCENT_MAX_DECIMALS, addMoney, availableShippingMethods, canBuy, canStep, cartEndpointPath, cartIssueWords, cartLineId, cartOf, cartTransportErrorFor, cartViewOf, catalogKey, checkoutGate, checkoutHref, chooseValue, clampQuantity, commerceLanguage, currencyExponent, defaultChoice, emptyCartView, findVariant, formatMoney, formatMoneyValue, furthestStep, includedVat, isCurrencyCode, isMoney, isPaymentMethodKind, isShippingMethodKind, isStorefrontProduct, isVatPercent, labelIn, majorToMinor, mergeCarts, migrateMajorPrice, minorToMajor, money, nextOrderState, openingOrderState, optionValueStates, orderSnapshot, paymentChannelOf, paymentInstructions, paymentMethodProblems, paymentMethodReady, percentOf, priceCart, productCurrency, productInScope, productOptions, productVariants, quantityBounds, quoteShipping, reservationExpiresAt, sellableQuantity, shippingMethodProblems, shippingMethodReady, shippingNeedsAddress, shopWord, simulatedCartTransport, siteCartView, stepQuantity, stockEffect, storefrontCatalog, storefrontMoney, subtractMoney, timesMoney, usablePaymentMethods, variantChoiceOf, variantWords };
|
|
342
1846
|
//# sourceMappingURL=vectoriox-iox-ui-commerce-core.mjs.map
|