@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
|
@@ -4961,7 +4961,7 @@ declare const SPEC_SITE_LAYOUT: {
|
|
|
4961
4961
|
readonly signatures: readonly [{
|
|
4962
4962
|
readonly id: "words-lit";
|
|
4963
4963
|
readonly label: "words lit one by one";
|
|
4964
|
-
readonly how: "a kinetic word or
|
|
4964
|
+
readonly how: "a kinetic word, heading or line of at most seven words in a held section";
|
|
4965
4965
|
}, {
|
|
4966
4966
|
readonly id: "photo-unveiled";
|
|
4967
4967
|
readonly label: "a photo unveiled";
|
|
@@ -4993,7 +4993,7 @@ declare const SPEC_SITE_LAYOUT: {
|
|
|
4993
4993
|
}, {
|
|
4994
4994
|
readonly id: "held-screen";
|
|
4995
4995
|
readonly label: "a held screen";
|
|
4996
|
-
readonly how: "a held section
|
|
4996
|
+
readonly how: "a held section whose layers only fade or push by the scroll — something still moves (a fallback, never the aim)";
|
|
4997
4997
|
}];
|
|
4998
4998
|
readonly daringLevels: readonly ["lively", "expressive"];
|
|
4999
4999
|
readonly looks: readonly [{
|
package/index.d.ts
CHANGED
|
@@ -3112,6 +3112,8 @@ interface IoxPipe {
|
|
|
3112
3112
|
* builder canvas and the SSR engine (both pass the site's language). */
|
|
3113
3113
|
interface PipeContext {
|
|
3114
3114
|
locale?: string;
|
|
3115
|
+
/** The studio's currency (ISO 4217) — what the `money` pipe formats a bare number in when the binding names none. */
|
|
3116
|
+
currency?: string;
|
|
3115
3117
|
}
|
|
3116
3118
|
type PipeFn = (value: any, args: any[], ctx: PipeContext) => any;
|
|
3117
3119
|
/** The registry — adding a pipe here (+ a descriptor below) makes it work on both sides and appear in
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@ export type ActionKind = 'animated' | 'instant' | 'server';
|
|
|
11
11
|
|
|
12
12
|
/** Picker grouping. Flat lists die at ~10 entries; the group is data, never a second list. */
|
|
13
13
|
export type ActionGroup =
|
|
14
|
-
| 'motion' | 'visibility' | 'navigate' | 'dialog' | 'popover' | 'notice' | 'item' | 'form' | 'data' | 'consent' | 'service';
|
|
14
|
+
| 'motion' | 'visibility' | 'navigate' | 'dialog' | 'popover' | 'notice' | 'item' | 'form' | 'data' | 'consent' | 'shop' | 'service';
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* What a step does inside the live builder canvas (the canvas RUNS interactions):
|
|
@@ -29,6 +29,9 @@ const SCROLL_ONLY: ReadonlyArray<string> = Object.freeze([SCROLL_PROGRESS_TRIGGE
|
|
|
29
29
|
* fires on its own — when it comes into view, or with the page in the first screen behind an entrance. Under a click or a
|
|
30
30
|
* hover it would stand at its start value until pressed; it is never armed there, and never offered.
|
|
31
31
|
*/
|
|
32
|
+
/** The plan feature selling sits behind (C-D18: the control plane's `features.shop`). */
|
|
33
|
+
export const SHOP_ENTITLEMENT = 'shop';
|
|
34
|
+
|
|
32
35
|
export const COUNT_UP_TRIGGERS: ReadonlyArray<string> = Object.freeze(['viewportEnter', 'pageLoad']);
|
|
33
36
|
|
|
34
37
|
export const ELEMENT_ACTION_DESCRIPTORS: readonly ActionDescriptor[] = Object.freeze([
|
|
@@ -174,13 +177,24 @@ export const ELEMENT_ACTION_DESCRIPTORS: readonly ActionDescriptor[] = Object.fr
|
|
|
174
177
|
{ name: 'values', type: 'string', label: 'Field values (JSON)' },
|
|
175
178
|
] },
|
|
176
179
|
|
|
180
|
+
// ── Shop (commerce E1c, C-D16): the shop parts' behaviour, run by composite-core's shop runtime through the host's
|
|
181
|
+
// cart transport (forms' transport rule — the part owns no HTTP). Add to cart SIMULATES on the canvas: the drawer opens
|
|
182
|
+
// with a sample line and no cart is written (T8). Buy now is INERT there — it must never take anyone to a payment.
|
|
183
|
+
// Gated by the ONE plan feature `features.shop` (C-D18); a manual payment method needs no payment connector (E1).
|
|
184
|
+
{ type: 'addToCart', labelKey: 'builder.actions.addToCart', kind: 'server', group: 'shop', builderBehaviour: 'simulate',
|
|
185
|
+
entitlement: SHOP_ENTITLEMENT },
|
|
186
|
+
{ type: 'startCheckout', labelKey: 'builder.actions.startCheckout', kind: 'server', group: 'shop', builderBehaviour: 'inert',
|
|
187
|
+
entitlement: SHOP_ENTITLEMENT },
|
|
188
|
+
|
|
177
189
|
// ── Services (D-A5: visible, greyed, with the reason — never hidden, never live) ──
|
|
178
190
|
{ type: 'signIn', labelKey: 'builder.actions.signIn', kind: 'server', group: 'service', builderBehaviour: 'inert',
|
|
179
191
|
planned: true, entitlement: 'visitorIdentity' },
|
|
180
|
-
{ type: 'startCheckout', labelKey: 'builder.actions.startCheckout', kind: 'server', group: 'service', builderBehaviour: 'inert',
|
|
181
|
-
planned: true, connector: 'payment', entitlement: 'commerce' },
|
|
182
192
|
]);
|
|
183
193
|
|
|
194
|
+
/** The shop actions' dispatch set (commerce E1c) — the engines branch on it beside DIALOG / BEHAVIOUR and hand the action
|
|
195
|
+
* to composite-core `runShopAction`, which reads the product, the variant and the quantity around the element. */
|
|
196
|
+
export const SHOP_ACTION_TYPES: ReadonlySet<string> = new Set(['addToCart', 'startCheckout']);
|
|
197
|
+
|
|
184
198
|
/** The A2 server executors' dispatch set — the live engine POSTs these to the public actions
|
|
185
199
|
* route; the canvas simulates them (a server action never runs from the ADMIN's browser). */
|
|
186
200
|
export const SERVER_ELEMENT_ACTION_TYPES: ReadonlySet<string> =
|
|
@@ -219,7 +233,7 @@ export const CONSENT_ACTION_TYPES: ReadonlySet<string> =
|
|
|
219
233
|
|
|
220
234
|
/** Picker order — most-used groups first, services last (they are the shop window, not the shop). */
|
|
221
235
|
export const ELEMENT_ACTION_GROUP_ORDER: readonly string[] =
|
|
222
|
-
Object.freeze(['motion', 'visibility', 'navigate', 'dialog', 'popover', 'notice', 'item', 'form', 'data', 'consent', 'service']);
|
|
236
|
+
Object.freeze(['motion', 'visibility', 'navigate', 'dialog', 'popover', 'notice', 'item', 'form', 'data', 'consent', 'shop', 'service']);
|
|
223
237
|
|
|
224
238
|
/** True when `d` is offered under `trigger` (its `triggers`, else every trigger) — the picker's rule and the runtimes'. */
|
|
225
239
|
export function actionOfferedUnder(d: Pick<ActionDescriptor, 'triggers'>, trigger: string | null | undefined): boolean {
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { CatalogEntry, catalogKey } from './catalog';
|
|
2
|
+
import { Cart, CART_ISSUE_LABELS, cartOf, CartIssue, PricedCart, PricedLine, priceCart, StudioCommerce } from './cart';
|
|
3
|
+
import { CurrencyCode } from './currency';
|
|
4
|
+
import { CommerceLabel, labelIn } from './labels';
|
|
5
|
+
import { MAX_LINE_QUANTITY } from './limits';
|
|
6
|
+
import { Money } from './money';
|
|
7
|
+
import { quantityBounds } from './quantity';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The CART TRANSPORT CONTRACT (commerce plan §3d, C-D16) — what a host provides so the builder's shop parts can show and
|
|
11
|
+
* change a visitor's cart. The parts own no HTTP, exactly like a form (forms-core `transport.ts`, the §6b lesson: a
|
|
12
|
+
* part that emits and a host that never answers ships a dead button behind green tests):
|
|
13
|
+
*
|
|
14
|
+
* - the LIVE SITE (the engine, commerce E1d) implements it over iox-cms's hardened cart routes (`cartEndpointPath`): the
|
|
15
|
+
* server prices every read with `priceCart` and the transport hands back its `CartView` — a browser never computes a
|
|
16
|
+
* price it charges (trap T1);
|
|
17
|
+
* - the BUILDER CANVAS uses `simulatedCartTransport`: an in-memory cart over sample data, never written anywhere
|
|
18
|
+
* (trap T8: the canvas never writes a cart).
|
|
19
|
+
*
|
|
20
|
+
* Every method resolves with the WHOLE cart as it is now, or rejects with a `CartTransportError`.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** One line of the cart a visitor sees: the server's priced line + the id its routes know it by + what it may hold. */
|
|
24
|
+
export interface CartViewLine extends PricedLine {
|
|
25
|
+
lineId: string;
|
|
26
|
+
/** The most this line may hold (the stepper's top). */
|
|
27
|
+
maxQuantity: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CartView {
|
|
31
|
+
/** null only for a cart that has never been priced (the no-transport stub). */
|
|
32
|
+
currency: CurrencyCode | null;
|
|
33
|
+
lines: CartViewLine[];
|
|
34
|
+
/** How many units — the cart button's badge (`$cart.count`). */
|
|
35
|
+
count: number;
|
|
36
|
+
empty: boolean;
|
|
37
|
+
subtotal: Money | null;
|
|
38
|
+
total: Money | null;
|
|
39
|
+
vat: Money | null;
|
|
40
|
+
vatPercent: number;
|
|
41
|
+
issues: CartIssue[];
|
|
42
|
+
/** What is still missing for a free-delivery method, when the studio offers one (the drawer's note); else null. */
|
|
43
|
+
freeShippingRemaining: Money | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface AddToCartRequest {
|
|
47
|
+
productId: string;
|
|
48
|
+
variantId?: string | null;
|
|
49
|
+
quantity: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface CartTransport {
|
|
53
|
+
read(): Promise<CartView>;
|
|
54
|
+
add(request: AddToCartRequest): Promise<CartView>;
|
|
55
|
+
setQuantity(lineId: string, quantity: number): Promise<CartView>;
|
|
56
|
+
remove(lineId: string): Promise<CartView>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export enum CartTransportErrorCode {
|
|
60
|
+
/** No cart on this host (the engine before E1d, a site with no shop). */
|
|
61
|
+
Unavailable = 'unavailable',
|
|
62
|
+
/** The server said no (a product no longer sold, a rate limit). */
|
|
63
|
+
Refused = 'refused',
|
|
64
|
+
/** The call never reached the server. */
|
|
65
|
+
Network = 'network',
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const CART_TRANSPORT_ERROR_LABELS: Readonly<Record<CartTransportErrorCode, CommerceLabel>> = Object.freeze({
|
|
69
|
+
[CartTransportErrorCode.Unavailable]: { en: 'The shop is not open yet.', he: 'החנות עוד לא פתוחה.' },
|
|
70
|
+
[CartTransportErrorCode.Refused]: { en: 'That could not be added to your bag.', he: 'לא ניתן היה להוסיף לסל.' },
|
|
71
|
+
[CartTransportErrorCode.Network]: { en: 'We could not reach the shop. Try again.', he: 'לא הצלחנו להגיע לחנות. נסו שוב.' },
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export class CartTransportError extends Error {
|
|
75
|
+
constructor(readonly code: CartTransportErrorCode, message?: string) {
|
|
76
|
+
super(message ?? code);
|
|
77
|
+
this.name = 'CartTransportError';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A line's id when the host has none of its own: the product and the variant, URL-safe. */
|
|
82
|
+
export function cartLineId(productId: string, variantId?: string | null): string {
|
|
83
|
+
return `${encodeURIComponent(productId)}~${encodeURIComponent(variantId ?? '')}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The public cart routes (§3d) — ROOT-relative, like the forms submit path (a relative path under the org's
|
|
87
|
+
* `<base href>` reaches the engine, never iox-cms). `lineId` addresses one line. */
|
|
88
|
+
export function cartEndpointPath(orgId: string, lineId?: string | null): string {
|
|
89
|
+
const base = `/api/site/${encodeURIComponent(orgId)}/cart`;
|
|
90
|
+
return lineId ? `${base}/lines/${encodeURIComponent(lineId)}` : base;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The fixed checkout route (C-D3), relative to the site's `<base href="/<orgLabel>/">`. */
|
|
94
|
+
export const CHECKOUT_PATH = 'checkout';
|
|
95
|
+
|
|
96
|
+
/** The checkout's href: `/<orgLabel>/checkout` under a label, else `/checkout`. */
|
|
97
|
+
export function checkoutHref(orgLabel?: string | null): string {
|
|
98
|
+
const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
|
|
99
|
+
return label ? `/${encodeURIComponent(label)}/${CHECKOUT_PATH}` : `/${CHECKOUT_PATH}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A cart with nothing in it. */
|
|
103
|
+
export function emptyCartView(currency: CurrencyCode | null = null): CartView {
|
|
104
|
+
return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
|
|
108
|
+
* `maxOf` says how many a line may hold (default the line cap). */
|
|
109
|
+
export function cartViewOf(priced: PricedCart, options: {
|
|
110
|
+
lineIdOf?: (line: PricedLine) => string;
|
|
111
|
+
maxOf?: (line: PricedLine) => number;
|
|
112
|
+
freeShippingRemaining?: Money | null;
|
|
113
|
+
} = {}): CartView {
|
|
114
|
+
const lineIdOf = options.lineIdOf ?? (line => cartLineId(line.productId, line.variantId));
|
|
115
|
+
const maxOf = options.maxOf ?? (() => MAX_LINE_QUANTITY);
|
|
116
|
+
const lines = priced.lines.map(line => ({ ...line, lineId: lineIdOf(line), maxQuantity: Math.max(line.quantity, maxOf(line)) }));
|
|
117
|
+
const count = lines.reduce((sum, line) => sum + line.quantity, 0);
|
|
118
|
+
return {
|
|
119
|
+
currency: priced.currency,
|
|
120
|
+
lines,
|
|
121
|
+
count,
|
|
122
|
+
empty: lines.length === 0,
|
|
123
|
+
subtotal: priced.subtotal,
|
|
124
|
+
total: priced.total,
|
|
125
|
+
vat: priced.vat,
|
|
126
|
+
vatPercent: priced.vatPercent,
|
|
127
|
+
issues: priced.issues,
|
|
128
|
+
freeShippingRemaining: options.freeShippingRemaining ?? null,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The cart iox-cms's public routes answer (E1b, `shop.md` "The cart"): the priced cart, each line under its own id
|
|
133
|
+
* (`ln_…`), and the unit count. */
|
|
134
|
+
export interface SiteCartView extends PricedCart {
|
|
135
|
+
lines: Array<PricedLine & { id: string }>;
|
|
136
|
+
itemCount?: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** iox-cms's answer as the view the parts paint — the server's line ids, its prices untouched. */
|
|
140
|
+
export function siteCartView(site: SiteCartView, freeShippingRemaining: Money | null = null): CartView {
|
|
141
|
+
const ids = new Map(site.lines.map(line => [line, line.id]));
|
|
142
|
+
return cartViewOf(site, { lineIdOf: line => ids.get(line as PricedLine & { id: string }) ?? cartLineId(line.productId, line.variantId), freeShippingRemaining });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** How a refused cart call is said: no cart service (501, 503) or a shop off the plan (403) is Unavailable, a
|
|
146
|
+
* status the server chose is Refused, anything that never got an answer is Network. */
|
|
147
|
+
export function cartTransportErrorFor(status: number | null | undefined): CartTransportError {
|
|
148
|
+
if (!status) return new CartTransportError(CartTransportErrorCode.Network);
|
|
149
|
+
if (status === 501 || status === 503 || status === 403) return new CartTransportError(CartTransportErrorCode.Unavailable, String(status));
|
|
150
|
+
return new CartTransportError(CartTransportErrorCode.Refused, String(status));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The words a cart's issues are said with, once each. */
|
|
154
|
+
export function cartIssueWords(view: Pick<CartView, 'issues'>, lang: string | null | undefined): string[] {
|
|
155
|
+
const codes = [...new Set(view.issues.map(i => i.code))];
|
|
156
|
+
return codes.map(code => labelIn(CART_ISSUE_LABELS[code], lang));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The host with no cart yet (the engine until E1d binds its own): every read is an empty cart, every change refused. */
|
|
160
|
+
export const NO_CART_TRANSPORT: CartTransport = Object.freeze({
|
|
161
|
+
read: () => Promise.resolve(emptyCartView()),
|
|
162
|
+
add: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
163
|
+
setQuantity: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
164
|
+
remove: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The builder canvas's cart: in memory, priced by the ONE `priceCart` over the catalog it is given (sample data, or the
|
|
169
|
+
* product on the canvas), written nowhere. `initial` is what it starts holding (a sample line, so the drawer has one to
|
|
170
|
+
* design). Every product the canvas adds must be in `catalog` — `addEntries` widens it.
|
|
171
|
+
*/
|
|
172
|
+
export interface SimulatedCartTransport extends CartTransport {
|
|
173
|
+
/** Make more units known to the simulation (the product an Add to cart on the canvas names). */
|
|
174
|
+
addEntries(entries: ReadonlyArray<CatalogEntry>): void;
|
|
175
|
+
/** The cart as it stands, priced — no promise (the canvas paints it at once). */
|
|
176
|
+
peek(): CartView;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function simulatedCartTransport(catalog: ReadonlyArray<CatalogEntry>, studio: StudioCommerce, initial: Cart = { lines: [] }): SimulatedCartTransport {
|
|
180
|
+
const entries = new Map<string, CatalogEntry>();
|
|
181
|
+
const known = (list: ReadonlyArray<CatalogEntry>) => list.forEach(e => entries.set(catalogKey(e.productId, e.variantId), e));
|
|
182
|
+
known(catalog);
|
|
183
|
+
let cart: Cart = { lines: [] };
|
|
184
|
+
const maxOf = (line: PricedLine) => quantityBounds(entries.get(catalogKey(line.productId, line.variantId))).max;
|
|
185
|
+
const price = (next: Cart): CartView => {
|
|
186
|
+
const priced = priceCart(next, [...entries.values()], studio);
|
|
187
|
+
cart = cartOf(priced);
|
|
188
|
+
return cartViewOf(priced, { maxOf });
|
|
189
|
+
};
|
|
190
|
+
price(initial);
|
|
191
|
+
const lineOf = (lineId: string) => cart.lines.find(l => cartLineId(l.productId, l.variantId) === lineId);
|
|
192
|
+
return {
|
|
193
|
+
addEntries: list => known(list),
|
|
194
|
+
peek: () => price(cart),
|
|
195
|
+
read: () => Promise.resolve(price(cart)),
|
|
196
|
+
add: request => {
|
|
197
|
+
if (!entries.has(catalogKey(request.productId, request.variantId))) return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
|
|
198
|
+
const same = cart.lines.find(l => l.productId === request.productId && (l.variantId ?? null) === (request.variantId ?? null));
|
|
199
|
+
const lines = same
|
|
200
|
+
? cart.lines.map(l => (l === same ? { ...l, quantity: l.quantity + request.quantity } : l))
|
|
201
|
+
: [...cart.lines, { productId: request.productId, variantId: request.variantId ?? null, quantity: request.quantity }];
|
|
202
|
+
return Promise.resolve(price({ lines }));
|
|
203
|
+
},
|
|
204
|
+
setQuantity: (lineId, quantity) => {
|
|
205
|
+
const line = lineOf(lineId);
|
|
206
|
+
if (!line) return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
|
|
207
|
+
return Promise.resolve(price({ lines: cart.lines.map(l => (l === line ? { ...l, quantity } : l)) }));
|
|
208
|
+
},
|
|
209
|
+
remove: lineId => Promise.resolve(price({ lines: cart.lines.filter(l => l !== lineOf(lineId)) })),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { CatalogEntry, catalogKey, sellableQuantity } from './catalog';
|
|
2
|
+
import { CurrencyCode, currencyExponent } from './currency';
|
|
3
|
+
import { CommerceLabel } from './labels';
|
|
4
|
+
import { MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY } from './limits';
|
|
5
|
+
import { addMoney, isMoney, money, Money, subtractMoney, timesMoney } from './money';
|
|
6
|
+
import { quoteShipping, ShippingMethod, ShippingQuote } from './shipping';
|
|
7
|
+
import { includedVat, isVatPercent } from './vat';
|
|
8
|
+
|
|
9
|
+
/** A cart names what and how many — never a price (C-D16, trap T1): every read prices it again. */
|
|
10
|
+
export interface CartLine {
|
|
11
|
+
productId: string;
|
|
12
|
+
variantId?: string | null;
|
|
13
|
+
quantity: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface Cart {
|
|
17
|
+
lines: readonly CartLine[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface StudioCommerce {
|
|
21
|
+
currency: CurrencyCode;
|
|
22
|
+
/** Prices INCLUDE it (C-D8). */
|
|
23
|
+
vatPercent: number;
|
|
24
|
+
shippingMethods: readonly ShippingMethod[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PricingChoice {
|
|
28
|
+
shippingMethodId?: string | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export enum CartIssueCode {
|
|
32
|
+
/** Not a whole number ≥ 1: the line is dropped. */
|
|
33
|
+
InvalidQuantity = 'invalid-quantity',
|
|
34
|
+
/** The same product and variant twice: merged into the first. */
|
|
35
|
+
DuplicateLine = 'duplicate-line',
|
|
36
|
+
TooManyLines = 'too-many-lines',
|
|
37
|
+
QuantityCapped = 'quantity-capped',
|
|
38
|
+
UnknownProduct = 'unknown-product',
|
|
39
|
+
/** The product exists, this variant does not (or the product needs a variant chosen). */
|
|
40
|
+
UnknownVariant = 'unknown-variant',
|
|
41
|
+
Unpublished = 'unpublished',
|
|
42
|
+
VariantDisabled = 'variant-disabled',
|
|
43
|
+
NoPrice = 'no-price',
|
|
44
|
+
CurrencyMismatch = 'currency-mismatch',
|
|
45
|
+
OutOfStock = 'out-of-stock',
|
|
46
|
+
/** Fewer left than asked: the line keeps what is left. */
|
|
47
|
+
QuantityClamped = 'quantity-clamped',
|
|
48
|
+
/** The line would push the subtotal past `MAX_CART_AMOUNT`: dropped. */
|
|
49
|
+
AmountTooLarge = 'amount-too-large',
|
|
50
|
+
/** The chosen shipping method is not offered for this cart: no shipping is priced. */
|
|
51
|
+
ShippingUnavailable = 'shipping-unavailable',
|
|
52
|
+
/** The studio's VAT is not a usable rate: the VAT line reads 0. */
|
|
53
|
+
VatInvalid = 'vat-invalid',
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> = Object.freeze({
|
|
57
|
+
[CartIssueCode.InvalidQuantity]: { en: 'A quantity was not a whole number, so the item was removed.', he: 'כמות שאינה מספר שלם — הפריט הוסר.' },
|
|
58
|
+
[CartIssueCode.DuplicateLine]: { en: 'The same item appeared twice and was combined.', he: 'אותו פריט הופיע פעמיים ואוחד.' },
|
|
59
|
+
[CartIssueCode.TooManyLines]: { en: 'Your cart has too many different items; the last ones were removed.', he: 'יש בעגלה יותר מדי פריטים שונים; האחרונים הוסרו.' },
|
|
60
|
+
[CartIssueCode.QuantityCapped]: { en: 'That is more than one order can hold; the quantity was lowered.', he: 'הכמות גדולה מהמותר בהזמנה אחת, והיא הוקטנה.' },
|
|
61
|
+
[CartIssueCode.UnknownProduct]: { en: 'An item is no longer sold and was removed.', he: 'פריט כבר לא נמכר והוסר.' },
|
|
62
|
+
[CartIssueCode.UnknownVariant]: { en: 'An option of an item is no longer sold and was removed.', he: 'אפשרות של פריט כבר לא נמכרת והוסרה.' },
|
|
63
|
+
[CartIssueCode.Unpublished]: { en: 'An item is not on sale right now and was removed.', he: 'פריט אינו למכירה כרגע והוסר.' },
|
|
64
|
+
[CartIssueCode.VariantDisabled]: { en: 'An option of an item is not available and was removed.', he: 'אפשרות של פריט אינה זמינה והוסרה.' },
|
|
65
|
+
[CartIssueCode.NoPrice]: { en: 'An item has no price yet and was removed.', he: 'לפריט עדיין אין מחיר, והוא הוסר.' },
|
|
66
|
+
[CartIssueCode.CurrencyMismatch]: { en: 'An item is priced in another currency and was removed.', he: 'פריט מתומחר במטבע אחר והוסר.' },
|
|
67
|
+
[CartIssueCode.OutOfStock]: { en: 'An item is out of stock and was removed.', he: 'פריט אזל מהמלאי והוסר.' },
|
|
68
|
+
[CartIssueCode.QuantityClamped]: { en: 'Fewer are left than you asked for; your cart holds what is left.', he: 'נשארו פחות ממה שביקשתם; בעגלה מה שנשאר.' },
|
|
69
|
+
[CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
|
|
70
|
+
[CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
|
|
71
|
+
[CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export interface CartIssue {
|
|
75
|
+
code: CartIssueCode;
|
|
76
|
+
productId?: string;
|
|
77
|
+
variantId?: string | null;
|
|
78
|
+
/** What the cart asked for. */
|
|
79
|
+
requested?: number;
|
|
80
|
+
/** What the priced line holds now (clamped / capped). */
|
|
81
|
+
quantity?: number;
|
|
82
|
+
shippingMethodId?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface PricedLine {
|
|
86
|
+
productId: string;
|
|
87
|
+
variantId: string | null;
|
|
88
|
+
title: string;
|
|
89
|
+
variantName: string | null;
|
|
90
|
+
quantity: number;
|
|
91
|
+
unitPrice: Money;
|
|
92
|
+
/** Shown struck through — only when it is above the price. */
|
|
93
|
+
compareAt: Money | null;
|
|
94
|
+
lineTotal: Money;
|
|
95
|
+
requiresShipping: boolean;
|
|
96
|
+
image: string | null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface PricedCart {
|
|
100
|
+
currency: CurrencyCode;
|
|
101
|
+
lines: PricedLine[];
|
|
102
|
+
subtotal: Money;
|
|
103
|
+
/** Zero until coupons (E4); `total` already subtracts it. */
|
|
104
|
+
discount: Money;
|
|
105
|
+
shipping: Money;
|
|
106
|
+
shippingMethod: ShippingQuote | null;
|
|
107
|
+
requiresShipping: boolean;
|
|
108
|
+
/** subtotal − discount + shipping: what the buyer pays. VAT is INSIDE it. */
|
|
109
|
+
total: Money;
|
|
110
|
+
/** The VAT `total` includes: total × v / (100 + v), rounded once half-to-even (`includedVat`). */
|
|
111
|
+
vat: Money;
|
|
112
|
+
vatPercent: number;
|
|
113
|
+
issues: CartIssue[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface LineRefusal {
|
|
117
|
+
readonly code: CartIssueCode;
|
|
118
|
+
readonly refuses: (entry: CatalogEntry, currency: CurrencyCode) => boolean;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Checked in order; the first that refuses drops the line. */
|
|
122
|
+
const LINE_REFUSALS: readonly LineRefusal[] = Object.freeze([
|
|
123
|
+
{ code: CartIssueCode.Unpublished, refuses: (entry: CatalogEntry) => entry.published !== true },
|
|
124
|
+
{ code: CartIssueCode.VariantDisabled, refuses: (entry: CatalogEntry) => entry.enabled !== true },
|
|
125
|
+
{ code: CartIssueCode.NoPrice, refuses: (entry: CatalogEntry) => !isMoney(entry.unitPrice) || entry.unitPrice.amount < 0 },
|
|
126
|
+
{ code: CartIssueCode.CurrencyMismatch, refuses: (entry: CatalogEntry, currency: CurrencyCode) => (entry.unitPrice as Money).currency !== currency },
|
|
127
|
+
{ code: CartIssueCode.OutOfStock, refuses: (entry: CatalogEntry) => sellableQuantity(entry) === 0 },
|
|
128
|
+
]);
|
|
129
|
+
|
|
130
|
+
const isText = (value: unknown): value is string => typeof value === 'string' && value !== '';
|
|
131
|
+
const variantOf = (line: CartLine): string | null => (isText(line.variantId) ? line.variantId : null);
|
|
132
|
+
const validQuantity = (quantity: unknown): quantity is number =>
|
|
133
|
+
typeof quantity === 'number' && Number.isSafeInteger(quantity) && quantity >= 1;
|
|
134
|
+
|
|
135
|
+
interface WantedLine {
|
|
136
|
+
productId: string;
|
|
137
|
+
variantId: string | null;
|
|
138
|
+
quantity: number;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Drops malformed lines, merges duplicates, keeps the first `MAX_CART_LINES` distinct ones. */
|
|
142
|
+
function wantedLines(cart: Cart, issues: CartIssue[]): WantedLine[] {
|
|
143
|
+
const lines: readonly CartLine[] = cart && Array.isArray(cart.lines) ? cart.lines : [];
|
|
144
|
+
const byKey = new Map<string, WantedLine>();
|
|
145
|
+
for (const line of lines) {
|
|
146
|
+
const productId = line && isText(line.productId) ? line.productId : '';
|
|
147
|
+
const variantId = line ? variantOf(line) : null;
|
|
148
|
+
if (!productId) {
|
|
149
|
+
issues.push({ code: CartIssueCode.UnknownProduct });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (!validQuantity(line.quantity)) {
|
|
153
|
+
issues.push({ code: CartIssueCode.InvalidQuantity, productId, variantId });
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const key = catalogKey(productId, variantId);
|
|
157
|
+
const same = byKey.get(key);
|
|
158
|
+
if (same) {
|
|
159
|
+
same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
|
|
160
|
+
issues.push({ code: CartIssueCode.DuplicateLine, productId, variantId });
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (byKey.size >= MAX_CART_LINES) {
|
|
164
|
+
issues.push({ code: CartIssueCode.TooManyLines, productId, variantId });
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
byKey.set(key, { productId, variantId, quantity: line.quantity });
|
|
168
|
+
}
|
|
169
|
+
return [...byKey.values()];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function indexCatalog(catalog: readonly CatalogEntry[]): { entries: Map<string, CatalogEntry>; products: Set<string> } {
|
|
173
|
+
const entries = new Map<string, CatalogEntry>();
|
|
174
|
+
const products = new Set<string>();
|
|
175
|
+
const list: readonly CatalogEntry[] = Array.isArray(catalog) ? catalog : [];
|
|
176
|
+
for (const entry of list) {
|
|
177
|
+
if (!entry || !isText(entry.productId)) continue;
|
|
178
|
+
products.add(entry.productId);
|
|
179
|
+
const key = catalogKey(entry.productId, isText(entry.variantId) ? entry.variantId : null);
|
|
180
|
+
if (!entries.has(key)) entries.set(key, entry);
|
|
181
|
+
}
|
|
182
|
+
return { entries, products };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const compareAtOf = (entry: CatalogEntry, unitPrice: Money): Money | null =>
|
|
186
|
+
isMoney(entry.compareAt) && entry.compareAt.currency === unitPrice.currency && entry.compareAt.amount > unitPrice.amount
|
|
187
|
+
? money(entry.compareAt.amount, entry.compareAt.currency)
|
|
188
|
+
: null;
|
|
189
|
+
|
|
190
|
+
function lineTotalWithin(unitPrice: Money, quantity: number, subtotal: Money): Money | null {
|
|
191
|
+
try {
|
|
192
|
+
const lineTotal = timesMoney(unitPrice, quantity);
|
|
193
|
+
return subtotal.amount + lineTotal.amount <= MAX_CART_AMOUNT ? lineTotal : null;
|
|
194
|
+
} catch {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
|
|
201
|
+
* payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
|
|
202
|
+
* out is whole minor units in the studio currency. An unusable line is dropped or adjusted and SAID in `issues`.
|
|
203
|
+
*/
|
|
204
|
+
export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio: StudioCommerce, choice?: PricingChoice | null): PricedCart {
|
|
205
|
+
const currency = studio.currency;
|
|
206
|
+
currencyExponent(currency);
|
|
207
|
+
const issues: CartIssue[] = [];
|
|
208
|
+
const { entries, products } = indexCatalog(catalog);
|
|
209
|
+
const lines: PricedLine[] = [];
|
|
210
|
+
let subtotal = money(0, currency);
|
|
211
|
+
|
|
212
|
+
for (const wanted of wantedLines(cart, issues)) {
|
|
213
|
+
const { productId, variantId } = wanted;
|
|
214
|
+
const entry = entries.get(catalogKey(productId, variantId));
|
|
215
|
+
if (!entry) {
|
|
216
|
+
issues.push({ code: products.has(productId) ? CartIssueCode.UnknownVariant : CartIssueCode.UnknownProduct, productId, variantId });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const refusal = LINE_REFUSALS.find(rule => rule.refuses(entry, currency));
|
|
220
|
+
if (refusal) {
|
|
221
|
+
issues.push({ code: refusal.code, productId, variantId, requested: wanted.quantity });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
let quantity = wanted.quantity;
|
|
225
|
+
if (quantity > MAX_LINE_QUANTITY) {
|
|
226
|
+
quantity = MAX_LINE_QUANTITY;
|
|
227
|
+
issues.push({ code: CartIssueCode.QuantityCapped, productId, variantId, requested: wanted.quantity, quantity });
|
|
228
|
+
}
|
|
229
|
+
const left = sellableQuantity(entry);
|
|
230
|
+
if (left !== null && quantity > left) {
|
|
231
|
+
const requested = quantity;
|
|
232
|
+
quantity = left;
|
|
233
|
+
issues.push({ code: CartIssueCode.QuantityClamped, productId, variantId, requested, quantity });
|
|
234
|
+
}
|
|
235
|
+
const unitPrice = money((entry.unitPrice as Money).amount, currency);
|
|
236
|
+
const lineTotal = lineTotalWithin(unitPrice, quantity, subtotal);
|
|
237
|
+
if (!lineTotal) {
|
|
238
|
+
issues.push({ code: CartIssueCode.AmountTooLarge, productId, variantId, requested: wanted.quantity });
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
subtotal = addMoney(subtotal, lineTotal);
|
|
242
|
+
lines.push({
|
|
243
|
+
productId,
|
|
244
|
+
variantId,
|
|
245
|
+
title: String(entry.title ?? ''),
|
|
246
|
+
variantName: isText(entry.variantName) ? entry.variantName : null,
|
|
247
|
+
quantity,
|
|
248
|
+
unitPrice,
|
|
249
|
+
compareAt: compareAtOf(entry, unitPrice),
|
|
250
|
+
lineTotal,
|
|
251
|
+
requiresShipping: entry.requiresShipping !== false,
|
|
252
|
+
image: isText(entry.image) ? entry.image : null,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const discount = money(0, currency);
|
|
257
|
+
const goods = subtractMoney(subtotal, discount);
|
|
258
|
+
const requiresShipping = lines.some(line => line.requiresShipping);
|
|
259
|
+
const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
|
|
260
|
+
const quotes = chosenId ? quoteShipping(studio.shippingMethods, { currency, goods, requiresShipping, lineCount: lines.length }) : [];
|
|
261
|
+
const shippingMethod = chosenId ? quotes.find(quote => quote.methodId === chosenId) ?? null : null;
|
|
262
|
+
if (chosenId && !shippingMethod) issues.push({ code: CartIssueCode.ShippingUnavailable, shippingMethodId: chosenId });
|
|
263
|
+
const shipping = shippingMethod ? shippingMethod.price : money(0, currency);
|
|
264
|
+
const total = addMoney(goods, shipping);
|
|
265
|
+
const vatUsable = isVatPercent(studio.vatPercent);
|
|
266
|
+
if (!vatUsable) issues.push({ code: CartIssueCode.VatInvalid });
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
currency,
|
|
270
|
+
lines,
|
|
271
|
+
subtotal,
|
|
272
|
+
discount,
|
|
273
|
+
shipping,
|
|
274
|
+
shippingMethod,
|
|
275
|
+
requiresShipping,
|
|
276
|
+
total,
|
|
277
|
+
vat: vatUsable ? includedVat(total, studio.vatPercent) : money(0, currency),
|
|
278
|
+
vatPercent: vatUsable ? studio.vatPercent : 0,
|
|
279
|
+
issues,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The cart a priced cart stands for — what to store back once the buyer has seen the issues. */
|
|
284
|
+
export function cartOf(priced: PricedCart): Cart {
|
|
285
|
+
return { lines: priced.lines.map(line => ({ productId: line.productId, variantId: line.variantId, quantity: line.quantity })) };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Sign-in merge (E3): b's lines join a's; the same product and variant add up. priceCart caps and clamps later. */
|
|
289
|
+
export function mergeCarts(a: Cart, b: Cart): Cart {
|
|
290
|
+
const merged: CartLine[] = [];
|
|
291
|
+
const byKey = new Map<string, CartLine>();
|
|
292
|
+
const all: CartLine[] = [...(Array.isArray(a?.lines) ? a.lines : []), ...(Array.isArray(b?.lines) ? b.lines : [])];
|
|
293
|
+
for (const line of all.filter(each => !!each && isText(each.productId))) {
|
|
294
|
+
const key = catalogKey(line.productId, variantOf(line));
|
|
295
|
+
const same = byKey.get(key);
|
|
296
|
+
if (same && validQuantity(same.quantity) && validQuantity(line.quantity)) {
|
|
297
|
+
same.quantity = Math.min(same.quantity + line.quantity, Number.MAX_SAFE_INTEGER);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const copy = { productId: line.productId, variantId: variantOf(line), quantity: line.quantity };
|
|
301
|
+
if (!same) byKey.set(key, copy);
|
|
302
|
+
merged.push(copy);
|
|
303
|
+
}
|
|
304
|
+
return { lines: merged };
|
|
305
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Money } from './money';
|
|
2
|
+
|
|
3
|
+
/** The storefront's stock word (iox-cms `storefront-projection.ts` speaks the same values). */
|
|
4
|
+
export enum Availability {
|
|
5
|
+
InStock = 'in_stock',
|
|
6
|
+
Low = 'low',
|
|
7
|
+
Out = 'out',
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One sellable unit as the seller knows it, in minor units: a product with no options is ONE entry with no
|
|
12
|
+
* `variantId`; a product with options is one entry per variant. iox-cms builds it from the product row (with the
|
|
13
|
+
* stock COUNT); the engine builds it from the storefront projection (with the availability WORD only).
|
|
14
|
+
*/
|
|
15
|
+
export interface CatalogEntry {
|
|
16
|
+
productId: string;
|
|
17
|
+
variantId?: string | null;
|
|
18
|
+
title: string;
|
|
19
|
+
variantName?: string | null;
|
|
20
|
+
/** null = no price set yet (a sample's placeholder): never sold. */
|
|
21
|
+
unitPrice: Money | null;
|
|
22
|
+
compareAt?: Money | null;
|
|
23
|
+
/** The count, where the caller knows it (iox-cms). Wins over `availability`. */
|
|
24
|
+
stock?: number | null;
|
|
25
|
+
/** The word, where only it is known (the engine). */
|
|
26
|
+
availability?: Availability | null;
|
|
27
|
+
/** A variant's switch; a product with no options is `true`. */
|
|
28
|
+
enabled: boolean;
|
|
29
|
+
published: boolean;
|
|
30
|
+
/** false = a digital product: no delivery address, no shipping method. */
|
|
31
|
+
requiresShipping: boolean;
|
|
32
|
+
image?: string | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** How many units may be sold: the count, else 0 for `out` or nothing known, else null = unbounded here (the server checks the count). */
|
|
36
|
+
export function sellableQuantity(entry: CatalogEntry): number | null {
|
|
37
|
+
if (typeof entry.stock === 'number') return Number.isSafeInteger(entry.stock) && entry.stock > 0 ? entry.stock : 0;
|
|
38
|
+
if (entry.availability === Availability.InStock || entry.availability === Availability.Low) return null;
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const catalogKey = (productId: string, variantId?: string | null): string => `${productId}\u0000${variantId ?? ''}`;
|