@vectoriox/iox-ui 5.96.1 → 5.97.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriox/iox-ui",
3
- "version": "5.96.1",
3
+ "version": "5.97.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -25,3 +25,5 @@ export * from './variants';
25
25
  export * from './quantity';
26
26
  export * from './cart-transport';
27
27
  export * from './shop-display';
28
+ export * from './site-checkout';
29
+ export { looksLikeEmail, looksLikePhone } from './text';
@@ -166,3 +166,25 @@ export function availableShippingMethods(methods: readonly ShippingMethod[], pri
166
166
  lineCount: pricedCart.lines.length,
167
167
  });
168
168
  }
169
+
170
+ /**
171
+ * What the goods still lack before a free-over method delivers free (the drawer's "Add ₪X more for free delivery"):
172
+ * the smallest gap over the methods offered, null when nothing ships, when no method is free-over, or when one already
173
+ * is free. `methods` are the ready ones (the checkout's options answer only those).
174
+ */
175
+ export function freeShippingRemaining(
176
+ methods: ReadonlyArray<Pick<ShippingMethod, 'kind'> & { freeOver?: Money | null }>,
177
+ cart: Pick<ShippingCart, 'currency' | 'subtotal' | 'discount' | 'requiresShipping' | 'lines'>,
178
+ ): Money | null {
179
+ if (!cart.lines.length || !cart.requiresShipping) return null;
180
+ const goods = subtractMoney(cart.subtotal, cart.discount);
181
+ let gap: Money | null = null;
182
+ for (const method of Array.isArray(methods) ? methods : []) {
183
+ const over = method.kind === ShippingMethodKind.FreeOver ? method.freeOver : null;
184
+ if (!isMoney(over) || over.currency !== cart.currency) continue;
185
+ const left = over.amount - goods.amount;
186
+ if (left <= 0) return null;
187
+ if (!gap || left < gap.amount) gap = money(left, cart.currency);
188
+ }
189
+ return gap;
190
+ }
@@ -0,0 +1,406 @@
1
+ import { SiteCartView } from './cart-transport';
2
+ import { BusinessIdentity, CheckoutStep, LegalPage } from './checkout';
3
+ import { CurrencyCode } from './currency';
4
+ import { CommerceLabel, labelIn } from './labels';
5
+ import { Money } from './money';
6
+ import { OrderSnapshot, PostalAddress } from './order-snapshot';
7
+ import { OrderState } from './orders';
8
+ import { DeliveryFit, PaymentMethodKind } from './payments';
9
+ import { ShippingMethodKind, ShippingQuote } from './shipping';
10
+
11
+ /**
12
+ * The fixed checkout (C-D3) and the order page as a SITE reads them over iox-cms's public routes (`shop.md` "E1 site
13
+ * API"): the routes, the answers' shapes, the words, and how a refusal's `code` becomes a sentence on the field it is
14
+ * about. The engine renders; iox-cms prices (trap T1) — nothing here computes a total.
15
+ */
16
+
17
+ export enum SiteCommerceRoute {
18
+ Cart = 'cart',
19
+ CartLines = 'cart/lines',
20
+ CheckoutOptions = 'checkout/options',
21
+ Checkout = 'checkout',
22
+ CheckoutPlace = 'checkout/place',
23
+ Order = 'order',
24
+ }
25
+
26
+ /** A public commerce route of one org, ROOT-relative (the same rule as `cartEndpointPath`). */
27
+ export function siteCommercePath(orgId: string, route: SiteCommerceRoute, id?: string | null): string {
28
+ const base = `/api/site/${encodeURIComponent(orgId)}/${route}`;
29
+ return id ? `${base}/${encodeURIComponent(id)}` : base;
30
+ }
31
+
32
+ /** The cart cookie iox-cms sets for one org (httpOnly — a site script never reads it; SSR forwards it). */
33
+ export const CART_COOKIE_PREFIX = 'iox_cart_';
34
+
35
+ export function cartCookieName(orgId: string): string {
36
+ return `${CART_COOKIE_PREFIX}${orgId}`;
37
+ }
38
+
39
+ /** The order page under the checkout: `/<orgLabel>/checkout/order/<token>`. */
40
+ export const ORDER_PATH = 'order';
41
+
42
+ export function orderHref(orgLabel: string | null | undefined, token: string): string {
43
+ const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
44
+ const tail = `checkout/${ORDER_PATH}/${encodeURIComponent(token)}`;
45
+ return label ? `/${encodeURIComponent(label)}/${tail}` : `/${tail}`;
46
+ }
47
+
48
+ // ── the answers ────────────────────────────────────────────────────────────────────────────────
49
+
50
+ export enum CheckoutFieldMode {
51
+ Hidden = 'hidden',
52
+ Optional = 'optional',
53
+ Required = 'required',
54
+ }
55
+
56
+ /** The contact fields an owner may hide, offer or require. */
57
+ export enum CheckoutAskedField {
58
+ Phone = 'phone',
59
+ Company = 'company',
60
+ Note = 'note',
61
+ }
62
+
63
+ export type CheckoutFieldModes = Readonly<Partial<Record<CheckoutAskedField, CheckoutFieldMode>>>;
64
+
65
+ export interface SitePaymentOption {
66
+ kind: PaymentMethodKind;
67
+ label: CommerceLabel;
68
+ fit: DeliveryFit;
69
+ }
70
+
71
+ export interface SiteShippingMethod {
72
+ id: string;
73
+ kind: ShippingMethodKind;
74
+ name: string;
75
+ price: Money | null;
76
+ freeOver: Money | null;
77
+ pickupAddress: string | null;
78
+ pickupHours: string | null;
79
+ needsAddress: boolean;
80
+ }
81
+
82
+ export interface SiteLegalLink {
83
+ title: string;
84
+ path: string;
85
+ }
86
+
87
+ /** `GET checkout/options` — what the page renders before anything is typed. */
88
+ export interface SiteCheckoutOptions {
89
+ open: boolean;
90
+ plan: string;
91
+ refusals: string[];
92
+ currency: CurrencyCode;
93
+ vatPercent: number;
94
+ country: string | null;
95
+ shippingMethods: SiteShippingMethod[];
96
+ paymentMethods: SitePaymentOption[];
97
+ fields: CheckoutFieldModes;
98
+ legalPages: Readonly<Partial<Record<LegalPage, SiteLegalLink | null>>>;
99
+ business: BusinessIdentity;
100
+ siteName: string | null;
101
+ marketingWording: CommerceLabel;
102
+ }
103
+
104
+ export interface SiteCheckoutContact {
105
+ email: string;
106
+ name: string | null;
107
+ phone: string | null;
108
+ company: string | null;
109
+ }
110
+
111
+ export interface SiteShippingOption extends ShippingQuote {
112
+ pickupAddress: string | null;
113
+ pickupHours: string | null;
114
+ }
115
+
116
+ /** `GET|POST|PATCH checkout` — one checkout, priced by the server. */
117
+ export interface SiteCheckoutView {
118
+ id: string;
119
+ contact: SiteCheckoutContact;
120
+ language: string;
121
+ marketingConsent: { given: boolean; wording: string };
122
+ delivery: { methodId: string; address: PostalAddress | null } | null;
123
+ payment: { kind: PaymentMethodKind; label: string } | null;
124
+ note: string | null;
125
+ furthestStep: CheckoutStep;
126
+ status: string;
127
+ cart: SiteCartView;
128
+ shippingOptions: SiteShippingOption[];
129
+ paymentOptions: SitePaymentOption[];
130
+ fields: CheckoutFieldModes;
131
+ termsRequired: boolean;
132
+ }
133
+
134
+ /** `GET order/:token` — the buyer's own order (instructions only while it waits for the money). */
135
+ export interface SiteBuyerOrder {
136
+ number: string | number;
137
+ state: OrderState;
138
+ stateLabel: string;
139
+ placedAt: string;
140
+ language: string;
141
+ seller: { name: string; business: BusinessIdentity };
142
+ snapshot: OrderSnapshot;
143
+ paymentLabel: string;
144
+ instructions: string | null;
145
+ }
146
+
147
+ /** `POST checkout/place` — 201. */
148
+ export interface SitePlacedOrder {
149
+ order: SiteBuyerOrder;
150
+ viewToken: string;
151
+ }
152
+
153
+ // ── the step a visitor is on ──────────────────────────────────────────────────────────────────
154
+
155
+ /**
156
+ * The step to SHOW: no checkout yet is Contact; then the first step still missing what it needs — a delivery chosen
157
+ * (with an address when it delivers), then a payment. A step already passed stays open only when the buyer asks.
158
+ */
159
+ export function currentCheckoutStep(view: Pick<SiteCheckoutView, 'delivery' | 'payment' | 'shippingOptions'> | null | undefined): CheckoutStep {
160
+ if (!view) return CheckoutStep.Contact;
161
+ const option = view.delivery ? view.shippingOptions.find(o => o.methodId === view.delivery!.methodId) : undefined;
162
+ if (!option || (option.needsAddress && !view.delivery?.address)) return CheckoutStep.Delivery;
163
+ return CheckoutStep.Payment;
164
+ }
165
+
166
+ /** The steps the stepper names (Paid is the order page, never a step a buyer fills). */
167
+ export const CHECKOUT_FORM_STEPS: readonly CheckoutStep[] = Object.freeze([CheckoutStep.Contact, CheckoutStep.Delivery, CheckoutStep.Payment]);
168
+
169
+ export function fieldAsked(fields: CheckoutFieldModes | null | undefined, field: CheckoutAskedField): boolean {
170
+ return (fields?.[field] ?? CheckoutFieldMode.Hidden) !== CheckoutFieldMode.Hidden;
171
+ }
172
+
173
+ export function fieldRequired(fields: CheckoutFieldModes | null | undefined, field: CheckoutAskedField): boolean {
174
+ return fields?.[field] === CheckoutFieldMode.Required;
175
+ }
176
+
177
+ /** One line of a postal address as a buyer reads it. */
178
+ export function addressLine(address: PostalAddress | null | undefined): string {
179
+ if (!address) return '';
180
+ return [address.line1, address.line2, [address.postalCode, address.city].filter(Boolean).join(' ')].filter(part => !!part && String(part).trim()).join(', ');
181
+ }
182
+
183
+ // ── the words ─────────────────────────────────────────────────────────────────────────────────
184
+
185
+ export enum CheckoutWord {
186
+ SecureCheckout = 'secureCheckout',
187
+ Email = 'email',
188
+ Name = 'name',
189
+ Phone = 'phone',
190
+ Company = 'company',
191
+ Optional = 'optional',
192
+ ContinueToDelivery = 'continueToDelivery',
193
+ ContinueToPayment = 'continueToPayment',
194
+ Change = 'change',
195
+ Street = 'street',
196
+ StreetMore = 'streetMore',
197
+ City = 'city',
198
+ PostalCode = 'postalCode',
199
+ DeliverTo = 'deliverTo',
200
+ PickupAt = 'pickupAt',
201
+ Note = 'note',
202
+ AcceptTerms = 'acceptTerms',
203
+ PlaceOrder = 'placeOrder',
204
+ PlaceNote = 'placeNote',
205
+ OrderSummary = 'orderSummary',
206
+ Subtotal = 'subtotal',
207
+ Delivery = 'delivery',
208
+ DeliveryLater = 'deliveryLater',
209
+ Free = 'free',
210
+ Total = 'total',
211
+ IncludesVat = 'includesVat',
212
+ Quantity = 'quantity',
213
+ EmptyBag = 'emptyBag',
214
+ BackToShop = 'backToShop',
215
+ Closed = 'closed',
216
+ ThankYou = 'thankYou',
217
+ ThankYouNamed = 'thankYouNamed',
218
+ OrderSent = 'orderSent',
219
+ OrderNumber = 'orderNumber',
220
+ HowToPay = 'howToPay',
221
+ PaidWith = 'paidWith',
222
+ BusinessNumber = 'businessNumber',
223
+ Working = 'working',
224
+ StepOf = 'stepOf',
225
+ OrderMissing = 'orderMissing',
226
+ Legal = 'legal',
227
+ }
228
+
229
+ /** `{name}`, `{n}`, `{of}`, `{amount}`, `{percent}`, `{number}`, `{email}`, `{total}`, `{place}` are filled by `checkoutWord`. */
230
+ export const CHECKOUT_WORDS: Readonly<Record<CheckoutWord, CommerceLabel>> = Object.freeze({
231
+ [CheckoutWord.SecureCheckout]: { en: 'Secure checkout', he: 'תשלום מאובטח' },
232
+ [CheckoutWord.Email]: { en: 'Email', he: 'אימייל' },
233
+ [CheckoutWord.Name]: { en: 'Full name', he: 'שם מלא' },
234
+ [CheckoutWord.Phone]: { en: 'Phone', he: 'טלפון' },
235
+ [CheckoutWord.Company]: { en: 'Company', he: 'חברה' },
236
+ [CheckoutWord.Optional]: { en: 'Optional', he: 'לא חובה' },
237
+ [CheckoutWord.ContinueToDelivery]: { en: 'Continue to delivery', he: 'המשך למשלוח' },
238
+ [CheckoutWord.ContinueToPayment]: { en: 'Continue to payment', he: 'המשך לתשלום' },
239
+ [CheckoutWord.Change]: { en: 'Change', he: 'שינוי' },
240
+ [CheckoutWord.Street]: { en: 'Street and number', he: 'רחוב ומספר' },
241
+ [CheckoutWord.StreetMore]: { en: 'Apartment, floor', he: 'דירה, קומה' },
242
+ [CheckoutWord.City]: { en: 'City', he: 'עיר' },
243
+ [CheckoutWord.PostalCode]: { en: 'Postal code', he: 'מיקוד' },
244
+ [CheckoutWord.DeliverTo]: { en: 'To {place}', he: 'אל {place}' },
245
+ [CheckoutWord.PickupAt]: { en: 'Pickup at {place}', he: 'איסוף מ{place}' },
246
+ [CheckoutWord.Note]: { en: 'A note for the seller', he: 'הערה למוכר' },
247
+ [CheckoutWord.AcceptTerms]: { en: 'I accept the', he: 'אני מאשר/ת את' },
248
+ [CheckoutWord.PlaceOrder]: { en: 'Place order · {total}', he: 'ביצוע הזמנה · {total}' },
249
+ [CheckoutWord.PlaceNote]: { en: 'How to pay is on the next page.', he: 'פרטי התשלום יופיעו בעמוד הבא.' },
250
+ [CheckoutWord.OrderSummary]: { en: 'Order summary', he: 'סיכום הזמנה' },
251
+ [CheckoutWord.Subtotal]: { en: 'Subtotal', he: 'סכום ביניים' },
252
+ [CheckoutWord.Delivery]: { en: 'Delivery', he: 'משלוח' },
253
+ [CheckoutWord.DeliveryLater]: { en: 'Chosen next', he: 'ייבחר בהמשך' },
254
+ [CheckoutWord.Free]: { en: 'Free', he: 'חינם' },
255
+ [CheckoutWord.Total]: { en: 'Total', he: 'סה״כ' },
256
+ [CheckoutWord.IncludesVat]: { en: 'Includes VAT {percent}% · {amount}', he: 'כולל מע״מ {percent}% · {amount}' },
257
+ [CheckoutWord.Quantity]: { en: 'Qty {n}', he: 'כמות {n}' },
258
+ [CheckoutWord.EmptyBag]: { en: 'Your bag is empty.', he: 'הסל שלך ריק.' },
259
+ [CheckoutWord.BackToShop]: { en: 'Back to the shop', he: 'חזרה לחנות' },
260
+ [CheckoutWord.Closed]: { en: 'The shop is not taking orders right now.', he: 'החנות לא מקבלת הזמנות כרגע.' },
261
+ [CheckoutWord.ThankYou]: { en: 'Thank you! Your order is in.', he: 'תודה! ההזמנה התקבלה' },
262
+ [CheckoutWord.ThankYouNamed]: { en: 'Thank you, {name}! Your order is in.', he: 'תודה, {name}! ההזמנה התקבלה' },
263
+ [CheckoutWord.OrderSent]: { en: 'Order #{number} · a confirmation was sent to {email}', he: 'הזמנה #{number} · אישור נשלח ל־{email}' },
264
+ [CheckoutWord.OrderNumber]: { en: 'Order #{number}', he: 'הזמנה #{number}' },
265
+ [CheckoutWord.HowToPay]: { en: 'How to pay', he: 'איך משלמים' },
266
+ [CheckoutWord.PaidWith]: { en: 'Payment', he: 'תשלום' },
267
+ [CheckoutWord.BusinessNumber]: { en: 'Business no. {number}', he: 'ע.מ {number}' },
268
+ [CheckoutWord.Working]: { en: 'One moment…', he: 'רגע…' },
269
+ [CheckoutWord.StepOf]: { en: 'Step {n} of {of}', he: 'שלב {n} מתוך {of}' },
270
+ [CheckoutWord.OrderMissing]: { en: 'We could not find this order.', he: 'לא מצאנו את ההזמנה הזו.' },
271
+ [CheckoutWord.Legal]: { en: 'Policies', he: 'מדיניות' },
272
+ });
273
+
274
+ export function checkoutWord(word: CheckoutWord, lang: string | null | undefined, fill: Readonly<Record<string, string | number>> = {}): string {
275
+ return labelIn(CHECKOUT_WORDS[word], lang).replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
276
+ }
277
+
278
+ // ── a refusal, said on its field ─────────────────────────────────────────────────────────────
279
+
280
+ /** Where on the checkout a refusal is said. */
281
+ export enum CheckoutSlot {
282
+ Email = 'email',
283
+ Name = 'name',
284
+ Phone = 'phone',
285
+ Company = 'company',
286
+ Delivery = 'delivery',
287
+ Address = 'address',
288
+ Payment = 'payment',
289
+ Terms = 'terms',
290
+ /** The order summary: the bag itself changed. */
291
+ Cart = 'cart',
292
+ /** The whole page: closed, busy, unreachable. */
293
+ Page = 'page',
294
+ }
295
+
296
+ /**
297
+ * Every code a buyer's checkout can hear from iox-cms (`CommerceErrorCode`, the checkout's own refusals and
298
+ * commerce-core's `OrderSnapshotRefusal`), plus `network` for no answer at all.
299
+ */
300
+ export enum SiteRefusalCode {
301
+ InvalidBody = 'invalid-body',
302
+ InvalidEmail = 'invalid-email',
303
+ EmailRequired = 'email-required',
304
+ NameRequired = 'name-required',
305
+ PhoneRequired = 'phone-required',
306
+ CompanyRequired = 'company-required',
307
+ InvalidAddress = 'invalid-address',
308
+ AddressRequired = 'address-required',
309
+ AddressCountry = 'address-country',
310
+ UnknownShippingMethod = 'unknown-shipping-method',
311
+ ShippingNotChosen = 'shipping-not-chosen',
312
+ UnknownPaymentMethod = 'unknown-payment-method',
313
+ PaymentNotChosen = 'payment-not-chosen',
314
+ PaymentMethodUnusable = 'payment-method-unusable',
315
+ TermsNotAccepted = 'terms-not-accepted',
316
+ NoCart = 'no-cart',
317
+ EmptyCart = 'empty-cart',
318
+ NoCheckout = 'no-checkout',
319
+ CartChanged = 'cart-changed',
320
+ OutOfStock = 'out-of-stock',
321
+ OrderChanged = 'order-changed',
322
+ CheckoutClosed = 'checkout-closed',
323
+ ShopNotInPlan = 'shop-not-in-plan',
324
+ ShopPlanUnknown = 'shop-plan-unknown',
325
+ RateLimited = 'rate-limited',
326
+ Busy = 'busy',
327
+ UnknownOrder = 'unknown-order',
328
+ UnknownSite = 'unknown-site',
329
+ Network = 'network',
330
+ }
331
+
332
+ interface RefusalRule {
333
+ readonly slot: CheckoutSlot;
334
+ readonly label: CommerceLabel;
335
+ }
336
+
337
+ const ENTER_EMAIL: CommerceLabel = { en: 'Enter an email address, like name@example.com.', he: 'הקלידו כתובת אימייל, למשל name@example.com.' };
338
+ const ENTER_ADDRESS: CommerceLabel = { en: 'Enter the street, the number and the city.', he: 'הקלידו רחוב, מספר ועיר.' };
339
+ const CHOOSE_DELIVERY: CommerceLabel = { en: 'Choose how to get your order.', he: 'בחרו איך לקבל את ההזמנה.' };
340
+ const CHOOSE_PAYMENT: CommerceLabel = { en: 'Choose how to pay.', he: 'בחרו איך לשלם.' };
341
+ const BAG_EMPTY: CommerceLabel = { en: 'Your bag is empty.', he: 'הסל שלך ריק.' };
342
+ const CLOSED: CommerceLabel = { en: 'The shop is not taking orders right now.', he: 'החנות לא מקבלת הזמנות כרגע.' };
343
+ const TRY_AGAIN: CommerceLabel = { en: 'The shop is busy. Try again in a moment.', he: 'החנות עמוסה. נסו שוב בעוד רגע.' };
344
+
345
+ export const SITE_REFUSALS: Readonly<Record<SiteRefusalCode, RefusalRule>> = Object.freeze({
346
+ [SiteRefusalCode.InvalidBody]: { slot: CheckoutSlot.Page, label: { en: 'Check the details and try again.', he: 'בדקו את הפרטים ונסו שוב.' } },
347
+ [SiteRefusalCode.InvalidEmail]: { slot: CheckoutSlot.Email, label: ENTER_EMAIL },
348
+ [SiteRefusalCode.EmailRequired]: { slot: CheckoutSlot.Email, label: ENTER_EMAIL },
349
+ [SiteRefusalCode.NameRequired]: { slot: CheckoutSlot.Name, label: { en: 'Enter your name.', he: 'הקלידו את שמכם.' } },
350
+ [SiteRefusalCode.PhoneRequired]: { slot: CheckoutSlot.Phone, label: { en: 'Enter a phone number.', he: 'הקלידו מספר טלפון.' } },
351
+ [SiteRefusalCode.CompanyRequired]: { slot: CheckoutSlot.Company, label: { en: 'Enter the company name.', he: 'הקלידו את שם החברה.' } },
352
+ [SiteRefusalCode.InvalidAddress]: { slot: CheckoutSlot.Address, label: ENTER_ADDRESS },
353
+ [SiteRefusalCode.AddressRequired]: { slot: CheckoutSlot.Address, label: ENTER_ADDRESS },
354
+ [SiteRefusalCode.AddressCountry]: { slot: CheckoutSlot.Address, label: { en: 'We do not deliver to this country.', he: 'אנחנו לא שולחים למדינה הזו.' } },
355
+ [SiteRefusalCode.UnknownShippingMethod]: { slot: CheckoutSlot.Delivery, label: CHOOSE_DELIVERY },
356
+ [SiteRefusalCode.ShippingNotChosen]: { slot: CheckoutSlot.Delivery, label: CHOOSE_DELIVERY },
357
+ [SiteRefusalCode.UnknownPaymentMethod]: { slot: CheckoutSlot.Payment, label: CHOOSE_PAYMENT },
358
+ [SiteRefusalCode.PaymentNotChosen]: { slot: CheckoutSlot.Payment, label: CHOOSE_PAYMENT },
359
+ [SiteRefusalCode.PaymentMethodUnusable]: { slot: CheckoutSlot.Payment, label: { en: 'This way to pay does not fit the delivery. Choose another.', he: 'אמצעי התשלום הזה לא מתאים למשלוח. בחרו אחר.' } },
360
+ [SiteRefusalCode.TermsNotAccepted]: { slot: CheckoutSlot.Terms, label: { en: 'Accept the terms to place the order.', he: 'כדי להזמין יש לאשר את התנאים.' } },
361
+ [SiteRefusalCode.NoCart]: { slot: CheckoutSlot.Cart, label: BAG_EMPTY },
362
+ [SiteRefusalCode.EmptyCart]: { slot: CheckoutSlot.Cart, label: BAG_EMPTY },
363
+ [SiteRefusalCode.NoCheckout]: { slot: CheckoutSlot.Email, label: { en: 'Start with your email.', he: 'התחילו באימייל.' } },
364
+ [SiteRefusalCode.CartChanged]: { slot: CheckoutSlot.Cart, label: { en: 'Your bag changed. Check it, then place the order.', he: 'הסל השתנה. בדקו אותו ואז הזמינו.' } },
365
+ [SiteRefusalCode.OutOfStock]: { slot: CheckoutSlot.Cart, label: { en: 'Something in your bag just sold out.', he: 'משהו בסל אזל הרגע מהמלאי.' } },
366
+ [SiteRefusalCode.OrderChanged]: { slot: CheckoutSlot.Page, label: { en: 'This order was already placed.', he: 'ההזמנה הזו כבר בוצעה.' } },
367
+ [SiteRefusalCode.CheckoutClosed]: { slot: CheckoutSlot.Page, label: CLOSED },
368
+ [SiteRefusalCode.ShopNotInPlan]: { slot: CheckoutSlot.Page, label: CLOSED },
369
+ [SiteRefusalCode.ShopPlanUnknown]: { slot: CheckoutSlot.Page, label: TRY_AGAIN },
370
+ [SiteRefusalCode.RateLimited]: { slot: CheckoutSlot.Page, label: { en: 'Too many tries. Wait a minute and try again.', he: 'יותר מדי ניסיונות. המתינו דקה ונסו שוב.' } },
371
+ [SiteRefusalCode.Busy]: { slot: CheckoutSlot.Page, label: TRY_AGAIN },
372
+ [SiteRefusalCode.UnknownOrder]: { slot: CheckoutSlot.Page, label: { en: 'We could not find this order.', he: 'לא מצאנו את ההזמנה הזו.' } },
373
+ [SiteRefusalCode.UnknownSite]: { slot: CheckoutSlot.Page, label: CLOSED },
374
+ [SiteRefusalCode.Network]: { slot: CheckoutSlot.Page, label: { en: 'We could not reach the shop. Try again.', he: 'לא הצלחנו להגיע לחנות. נסו שוב.' } },
375
+ });
376
+
377
+ /** Each refusal of a failed call, on its slot, in the buyer's words. */
378
+ export interface SiteRefusal {
379
+ code: string;
380
+ slot: CheckoutSlot;
381
+ words: string;
382
+ }
383
+
384
+ const isRefusalCode = (code: unknown): code is SiteRefusalCode =>
385
+ typeof code === 'string' && (Object.values(SiteRefusalCode) as string[]).includes(code);
386
+
387
+ const ORDER_REFUSED = 'order-refused';
388
+
389
+ function refusalOf(code: unknown, lang: string | null | undefined): SiteRefusal {
390
+ const known: SiteRefusalCode = isRefusalCode(code) ? code : SiteRefusalCode.InvalidBody;
391
+ const rule = SITE_REFUSALS[known];
392
+ return { code: isRefusalCode(code) ? code : String(code ?? known), slot: rule.slot, words: labelIn(rule.label, lang) };
393
+ }
394
+
395
+ /**
396
+ * A refused call's body (`{ statusCode, code, message, refusals? }`) as sentences: `order-refused` says each of its
397
+ * `refusals` on its own field; any other code is one sentence; no body at all is `network`. `message` is a log line
398
+ * and is never shown. One sentence per slot (the first wins).
399
+ */
400
+ export function siteRefusalsOf(body: unknown, lang: string | null | undefined): SiteRefusal[] {
401
+ const answer = body && typeof body === 'object' ? body as { code?: unknown; refusals?: unknown } : null;
402
+ if (!answer) return [refusalOf(SiteRefusalCode.Network, lang)];
403
+ const codes = answer.code === ORDER_REFUSED && Array.isArray(answer.refusals) && answer.refusals.length ? answer.refusals : [answer.code];
404
+ const seen = new Set<CheckoutSlot>();
405
+ return codes.map(code => refusalOf(code, lang)).filter(r => !seen.has(r.slot) && !!seen.add(r.slot));
406
+ }
@@ -294,3 +294,23 @@ export function productInScope(rowItem: unknown, data: Readonly<Record<string, u
294
294
  for (const value of Object.values(all)) if (isStorefrontProduct(value)) return value;
295
295
  return null;
296
296
  }
297
+
298
+ /** What the `$variant` slot carries: the chosen variant, its product, its words and the quantity a buyer would add. */
299
+ export interface VariantSlot extends ProductVariantView {
300
+ productId: string | undefined;
301
+ words: string;
302
+ quantity: number;
303
+ }
304
+
305
+ /**
306
+ * The `$variant` slot for a product — the SAME value the shop runtime publishes on the canvas and the live site, and
307
+ * the engine seeds during SSR (so the raw HTML already shows the price). `choice` defaults to the first sellable one.
308
+ */
309
+ export function variantSlotOf(product: StorefrontProduct | null | undefined, choice?: VariantChoice | null, quantity = 1): VariantSlot | null {
310
+ if (!product) return null;
311
+ const options = productOptions(product);
312
+ const views = productVariants(product);
313
+ const pick = choice ?? defaultChoice(options, views);
314
+ const variant = options.length ? findVariant(options, views, pick) : views[0] ?? null;
315
+ return variant ? { ...variant, productId: product._id, words: variantWords(variant.choice, options), quantity } : null;
316
+ }
@@ -2,7 +2,7 @@ import {
2
2
  CART_TRANSPORT_ERROR_LABELS, CartTransport, CartTransportError, CartTransportErrorCode, cartIssueWords, CartView, CartViewLine, chooseValue,
3
3
  defaultChoice, emptyCartView, findVariant, formatMoney, optionValueStates, ProductOption, ProductVariantView, productOptions, productVariants,
4
4
  QuantityBounds, quantityBounds, QuantityStep, canStep, clampQuantity, ShopSlot, ShopWord, shopWord, stepQuantity, StorefrontProduct, VariantChoice,
5
- variantWords,
5
+ variantSlotOf,
6
6
  } from '@vectoriox/iox-ui/commerce-core';
7
7
  import { roleClass } from '@vectoriox/iox-ui/design-core';
8
8
 
@@ -281,13 +281,7 @@ export class ShopRuntime {
281
281
  }
282
282
 
283
283
  private publishVariant(state: ProductState): void {
284
- const variant = this.variantOf(state);
285
- this.publish(ShopSlot.Variant, variant ? {
286
- ...variant,
287
- productId: state.product._id,
288
- words: variantWords(variant.choice, state.options),
289
- quantity: state.quantity,
290
- } : null);
284
+ this.publish(ShopSlot.Variant, variantSlotOf(state.product, state.choice, state.quantity));
291
285
  }
292
286
 
293
287
  private publish(slot: ShopSlot, value: unknown): void {
@@ -308,7 +308,7 @@ export function buildVariantPickerRecipe(create: CompositeNodeFactory): Composit
308
308
  export function buildQuantityRecipe(create: CompositeNodeFactory, compact = false, key = 'quantity'): CompositeNode {
309
309
  const size = compact ? '30px' : 'var(--iox-stepper-size)';
310
310
  const root = part(create, key, Type.Container, ShopRole.Quantity, Style.Quantity, {}, SHOP_LABELS.quantity,
311
- { ...ROW, alignItems: 'stretch', gap: '0px', ...(compact ? { minHeight: size } : {}) });
311
+ { ...ROW, alignItems: 'stretch', gap: '0px', minHeight: size });
312
312
  const down = button(create, `${key}-down`, ShopRole.QuantityDown, Style.QuantityButton, 'Decrease', 'Decrease quantity',
313
313
  { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', minWidth: size, padding: ZERO });
314
314
  down.children = [icon(create, `${key}-down-icon`, 'ph ph-minus', compact ? '14px' : '16px')];
@@ -347,7 +347,7 @@ export function buildCartButtonRecipe(create: CompositeNodeFactory): CompositeNo
347
347
  const root = button(create, 'cart-button', ShopRole.CartButton, Style.CartButton, SHOP_LABELS.cartButton, SHOP_RECIPE_WORDS.cart,
348
348
  { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 'auto', height: 'auto', padding: '6px 6px 6px 6px', position: 'relative' });
349
349
  const count = part(create, 'cart-count', Type.Container, ShopRole.CartCount, Style.CartCount, {}, 'Count',
350
- { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 'auto', height: 'auto', minHeight: 'auto', padding: '0px 4px 0px 4px', position: 'absolute', top: '-5px', right: '-5px' });
350
+ { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 'auto', height: 'auto', minHeight: 'var(--iox-cart-count-size)', padding: '0px 4px 0px 4px', position: 'absolute', top: '-5px', right: '-5px' });
351
351
  const words = text(create, 'cart-count-text', null, Style.Label, SHOP_RECIPE_WORDS.count, 'Text', { ...WORDS, lineHeight: '1' }, 'span');
352
352
  bindSlot(words, 'content', '$cart', 'count');
353
353
  count.children = [words];