@wix/himalaya-cli 0.1807.0 → 0.1808.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/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/site-shell.d.ts +62 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +124 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +12 -0
- package/dist/cli.mjs +14 -1
- package/package.json +2 -2
- package/templates/brandy/README.md +83 -14
- package/templates/brandy/config.ts +42 -34
- package/templates/brandy/dev/index.ts +240 -21
- package/templates/brandy/dev/member-screens.ts +2302 -0
- package/templates/brandy/himalaya.content.json +3 -0
- package/templates/brandy/himalaya.template.json +1 -1
- package/templates/brandy/provisioning.json +4 -1
- package/templates/brandy/provisioning.member.example.json +69 -7
- package/templates/brandy/tier5-src/_shared/exclusive-writes.ts +66 -0
- package/templates/brandy/tier5-src/_shared/header-badges.ts +113 -0
- package/templates/brandy/tier5-src/_shared/himi-store-saved.ts +57 -0
- package/templates/brandy/tier5-src/_shared/iap-presentation.ts +207 -0
- package/templates/brandy/tier5-src/_shared/restaurant-ordering.ts +201 -0
- package/templates/brandy/tier5-src/_shared/source-badges.ts +72 -0
- package/templates/brandy/tier5-src/himi-branded-lite-cart/index.ts +703 -0
- package/templates/brandy/tier5-src/himi-branded-lite-header-badges/index.ts +70 -0
- package/templates/brandy/tier5-src/himi-branded-lite-member-cart/flag.ts +3 -0
- package/templates/brandy/tier5-src/himi-branded-lite-member-cart/index.ts +6 -0
- package/templates/brandy/tier5-src/perks/index.ts +75 -0
- package/templates/brandy/tokens.json +5 -0
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
import { paymentSetupMessage } from "../_shared/payment-setup.js";
|
|
2
|
+
import { withOnlineWrites } from "../_shared/online-actions.js";
|
|
3
|
+
import { defineService as registerState } from "@himalaya/state";
|
|
4
|
+
import { getStoreProduct } from "../_shared/himi-store.js";
|
|
5
|
+
import { RESTAURANTS_ORDERS_APP_ID } from "../_shared/restaurant-ordering.js";
|
|
6
|
+
import { iapPriceCopy } from "../_shared/iap-worker.js";
|
|
7
|
+
import { withIapPresentation } from "../_shared/iap-presentation.js";
|
|
8
|
+
import { type IapCommerce, classifyCart } from "@himalaya/iap-checkout";
|
|
9
|
+
import { addCouponToCurrentCart, calculateCurrentCart, createCheckoutFromCurrentCart, getCurrentCart, removeCouponFromCurrentCart, removeLineItemsFromCurrentCart, updateLineItemsQuantity, type WixCartDetail, type WixCartLineItemDetail } from "@himalaya/wix-ecom";
|
|
10
|
+
import { createRedirectSession } from "@himalaya/wix-redirects";
|
|
11
|
+
import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
|
|
12
|
+
import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
|
|
13
|
+
import { formatCurrency } from "../_shared/engine-intl.js";
|
|
14
|
+
import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
|
|
15
|
+
import { hostSessionFromGlobal } from "@himalaya/iap";
|
|
16
|
+
|
|
17
|
+
/** The host's session clock (a signed-out stub on a host without one). */
|
|
18
|
+
const hostSession = hostSessionFromGlobal();
|
|
19
|
+
/** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
|
|
20
|
+
* through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
|
|
21
|
+
* identity, so it also bumps the generation the members-only cart's rows are checked against. */
|
|
22
|
+
let webSignedIn: boolean | undefined;
|
|
23
|
+
let webGeneration = 0;
|
|
24
|
+
const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
|
|
25
|
+
/** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
|
|
26
|
+
* (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
|
|
27
|
+
* reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
|
|
28
|
+
let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
|
|
29
|
+
/** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
|
|
30
|
+
* generation: a member switch while a read or write is in flight never lands the previous member's rows. */
|
|
31
|
+
let rowsGeneration = -1;
|
|
32
|
+
const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
|
|
33
|
+
const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
|
|
34
|
+
/** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
|
|
35
|
+
* (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
|
|
36
|
+
let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
|
|
37
|
+
function takeReturnUrl(arg: unknown): void {
|
|
38
|
+
const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
|
|
39
|
+
if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
|
|
43
|
+
* `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
|
|
44
|
+
const WIX_STORES_CATALOG_ID = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
|
|
45
|
+
const WIX_STORES_APP_ID = "1380b703-ce81-ff05-f115-39571d94dfcd";
|
|
46
|
+
|
|
47
|
+
import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
|
|
48
|
+
import { getAll, upsert, remove as dbRemove, type DbEntity } from "@himalaya/local-db";
|
|
49
|
+
import { isOfflineFailure, writeMayHaveLanded } from "../_shared/owner-load-error.js";
|
|
50
|
+
import { isProductSaved, readSavedProducts, toggleSavedProduct } from "../_shared/himi-store-saved.js";
|
|
51
|
+
|
|
52
|
+
// Offline-first (data-offline): the cart is READ-THROUGH — paint the last-synced line
|
|
53
|
+
// items from the on-device `cart` entity first (instant, works offline), then
|
|
54
|
+
// revalidate from Wix and refresh the cache.
|
|
55
|
+
// `remove` drops the line from the cache only AFTER Wix confirms it; a failed removal
|
|
56
|
+
// keeps the line on screen and says nothing was removed (no host replays a
|
|
57
|
+
// queued write, so the old "removed offline" promise was a removal that never happened).
|
|
58
|
+
// The checkout redirect path is unchanged. Every local-db call is wrapped so a build
|
|
59
|
+
// without the `local_database` grant behaves exactly as before (online-only).
|
|
60
|
+
const ENTITY = "cart";
|
|
61
|
+
function cachedUnitPrice(total: string, quantity: number): string {
|
|
62
|
+
if (quantity <= 1) return total;
|
|
63
|
+
const match = /\d(?:[\d.,]|[ \u00a0\u202f](?=\d))*/u.exec(total);
|
|
64
|
+
if (!match) return total;
|
|
65
|
+
const raw = match[0];
|
|
66
|
+
const compact = raw.replace(/[ \u00a0\u202f]/g, "");
|
|
67
|
+
const last = Math.max(compact.lastIndexOf("."), compact.lastIndexOf(","));
|
|
68
|
+
const digits = last >= 0 && compact.length - last - 1 <= 2 ? compact.length - last - 1 : 0;
|
|
69
|
+
const decimal = digits ? compact[last] : ".";
|
|
70
|
+
const numeric = digits ? `${compact.slice(0, last).replace(/[,.]/g, "")}.${compact.slice(last + 1)}` : compact.replace(/[,.]/g, "");
|
|
71
|
+
const amount = Number(numeric);
|
|
72
|
+
if (!Number.isFinite(amount)) return total;
|
|
73
|
+
const [whole, fraction] = (amount / quantity).toFixed(digits).split(".");
|
|
74
|
+
const spaceGrouping = raw.match(/[ \u00a0\u202f](?=\d)/u)?.[0];
|
|
75
|
+
const grouped = spaceGrouping ? whole.replace(/\B(?=(\d{3})+(?!\d))/g, spaceGrouping) : whole;
|
|
76
|
+
return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
|
|
77
|
+
}
|
|
78
|
+
async function readCachedItems(): Promise<Row[]> {
|
|
79
|
+
// A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
|
|
80
|
+
// the next member offline.
|
|
81
|
+
if (memberOnlyCart) return [];
|
|
82
|
+
try {
|
|
83
|
+
return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
|
|
84
|
+
const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
|
|
85
|
+
let saved = false;
|
|
86
|
+
try { saved = isProductSaved(item.catalogReference?.catalogItemId ?? item.productId ?? ""); } catch { /* keep the cached line usable */ }
|
|
87
|
+
const unitPrice = item.unitPrice || cachedUnitPrice(item.total || item.commerceTotal || "", quantity);
|
|
88
|
+
return { ...item, catalogItemId: item.catalogReference?.catalogItemId ?? item.productId ?? "", quantity, quantityLabel: String(quantity), atMinQuantity: quantity <= 1, unitPrice,
|
|
89
|
+
wasPrice: item.wasPrice ?? "", swatches: item.swatches ?? [], option1: item.option1 ?? "", option2: item.option2 ?? "", option3: item.option3 ?? "",
|
|
90
|
+
noOption1: !item.option1, noOption2: !item.option2, noOption3: !item.option3,
|
|
91
|
+
stockMessage: item.stockMessage ?? "", noStockMessage: !item.stockMessage,
|
|
92
|
+
inStockMessage: item.inStockMessage ?? "", noInStockMessage: !item.inStockMessage, saved, notSaved: !saved };
|
|
93
|
+
});
|
|
94
|
+
} catch { return []; }
|
|
95
|
+
}
|
|
96
|
+
/** Mirror the cart Wix returned: upsert its lines and drop any cached line it no longer has
|
|
97
|
+
* (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
|
|
98
|
+
* shows a line that is gone. */
|
|
99
|
+
async function writeCachedItems(rows: Row[]): Promise<void> {
|
|
100
|
+
if (memberOnlyCart) return;
|
|
101
|
+
try {
|
|
102
|
+
const keep = new Set(rows.map((r) => r.id));
|
|
103
|
+
for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
|
|
104
|
+
for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity);
|
|
105
|
+
} catch { /* capability not granted → online-only */ }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function cacheDrop(id: string): Promise<void> { try { await dbRemove(ENTITY, id); } catch { /* capability not granted */ } }
|
|
109
|
+
|
|
110
|
+
interface Row {
|
|
111
|
+
catalogReference?: { appId: string; catalogItemId: string; options?: Record<string, unknown> };
|
|
112
|
+
productId?: string;
|
|
113
|
+
catalogItemId?: string;
|
|
114
|
+
id: string;
|
|
115
|
+
name: string;
|
|
116
|
+
title: string;
|
|
117
|
+
subtitle: string;
|
|
118
|
+
/** Numeric line quantity + its display string (the −/+ qty controls). */
|
|
119
|
+
quantity: number;
|
|
120
|
+
quantityLabel: string;
|
|
121
|
+
/** The "−" control at qty 1 removes the line, so it never dead-ends. */
|
|
122
|
+
atMinQuantity: boolean;
|
|
123
|
+
total: string;
|
|
124
|
+
unitPrice: string;
|
|
125
|
+
wasPrice?: string;
|
|
126
|
+
swatches?: string[];
|
|
127
|
+
commerceTotal: string;
|
|
128
|
+
image: string;
|
|
129
|
+
initial: string;
|
|
130
|
+
hasImage: boolean;
|
|
131
|
+
noImage: boolean;
|
|
132
|
+
option1: string; option2: string; option3: string;
|
|
133
|
+
noOption1: boolean; noOption2: boolean; noOption3: boolean;
|
|
134
|
+
stockMessage: string; noStockMessage: boolean;
|
|
135
|
+
inStockMessage: string; noInStockMessage: boolean;
|
|
136
|
+
saved: boolean;
|
|
137
|
+
notSaved: boolean;
|
|
138
|
+
}
|
|
139
|
+
interface State {
|
|
140
|
+
status: "loading" | "ready" | "error";
|
|
141
|
+
errorKind: "offline" | "server" | "";
|
|
142
|
+
items: Row[];
|
|
143
|
+
subtotal: string;
|
|
144
|
+
commerceSubtotal?: string;
|
|
145
|
+
emptyText: string;
|
|
146
|
+
checkoutHint: string;
|
|
147
|
+
itemCount: number;
|
|
148
|
+
promoCode: string;
|
|
149
|
+
promoEditRevision: number;
|
|
150
|
+
appliedCode: string;
|
|
151
|
+
appliedLabel: string;
|
|
152
|
+
couponId: string;
|
|
153
|
+
promoError: string;
|
|
154
|
+
promoBusy: boolean;
|
|
155
|
+
noPromoError: boolean;
|
|
156
|
+
hasCoupon: boolean;
|
|
157
|
+
discount: string;
|
|
158
|
+
noDiscount: boolean;
|
|
159
|
+
noCheckoutHint: boolean;
|
|
160
|
+
showPaidToast: boolean;
|
|
161
|
+
noPaidToast: boolean;
|
|
162
|
+
noCoupon: boolean;
|
|
163
|
+
subtotalLabel: string;
|
|
164
|
+
isLoading: boolean;
|
|
165
|
+
notLoading: boolean;
|
|
166
|
+
/** Standard error quad (the himi-store retryBlock contract): the descriptor
|
|
167
|
+
* gates its error card on notErrored and its content on hideContent, so a
|
|
168
|
+
* failed load shows the retry card instead of a blank list + blank subtotal. */
|
|
169
|
+
isErrored: boolean;
|
|
170
|
+
notErrored: boolean;
|
|
171
|
+
noOfflineError: boolean;
|
|
172
|
+
noServerError: boolean;
|
|
173
|
+
hideContent: boolean;
|
|
174
|
+
noEmpty: boolean;
|
|
175
|
+
noItems: boolean;
|
|
176
|
+
/** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
|
|
177
|
+
* a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
|
|
178
|
+
* (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
|
|
179
|
+
memberOnly?: boolean;
|
|
180
|
+
needsSignIn?: boolean;
|
|
181
|
+
noSignIn?: boolean;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function itemId(arg: unknown): string {
|
|
185
|
+
if (typeof arg === "string") return arg;
|
|
186
|
+
if (!arg || typeof arg !== "object") return "";
|
|
187
|
+
const payload = arg as {
|
|
188
|
+
id?: string;
|
|
189
|
+
item?: { id?: string };
|
|
190
|
+
args?: { id?: string };
|
|
191
|
+
params?: { id?: string };
|
|
192
|
+
};
|
|
193
|
+
return payload.id ?? payload.item?.id ?? payload.args?.id ?? payload.params?.id ?? "";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function mediaUrl(value: unknown): string {
|
|
197
|
+
if (!value || typeof value !== "object") return "";
|
|
198
|
+
const item = value as {
|
|
199
|
+
image?: { url?: string } | string;
|
|
200
|
+
media?: {
|
|
201
|
+
mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string }; url?: string };
|
|
202
|
+
items?: Array<{ image?: { url?: string }; thumbnail?: { url?: string }; url?: string }>;
|
|
203
|
+
};
|
|
204
|
+
product?: {
|
|
205
|
+
image?: { url?: string } | string;
|
|
206
|
+
media?: {
|
|
207
|
+
mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string }; url?: string };
|
|
208
|
+
items?: Array<{ image?: { url?: string }; thumbnail?: { url?: string }; url?: string }>;
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
};
|
|
212
|
+
const directImage = typeof item.image === "string" ? item.image : item.image?.url;
|
|
213
|
+
const productImage = typeof item.product?.image === "string" ? item.product.image : item.product?.image?.url;
|
|
214
|
+
return directImage
|
|
215
|
+
?? item.media?.mainMedia?.image?.url
|
|
216
|
+
?? item.media?.mainMedia?.thumbnail?.url
|
|
217
|
+
?? item.media?.mainMedia?.url
|
|
218
|
+
?? item.media?.items?.[0]?.image?.url
|
|
219
|
+
?? item.media?.items?.[0]?.thumbnail?.url
|
|
220
|
+
?? item.media?.items?.[0]?.url
|
|
221
|
+
?? productImage
|
|
222
|
+
?? item.product?.media?.mainMedia?.image?.url
|
|
223
|
+
?? item.product?.media?.mainMedia?.thumbnail?.url
|
|
224
|
+
?? item.product?.media?.mainMedia?.url
|
|
225
|
+
?? item.product?.media?.items?.[0]?.image?.url
|
|
226
|
+
?? item.product?.media?.items?.[0]?.thumbnail?.url
|
|
227
|
+
?? item.product?.media?.items?.[0]?.url
|
|
228
|
+
?? "";
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function row(item: WixCartLineItemDetail, index: number): Row {
|
|
232
|
+
const raw = item as WixCartLineItemDetail & Record<string, unknown>;
|
|
233
|
+
const quantity = item.quantity ?? 1;
|
|
234
|
+
const name = item.productName?.original || copyParam("cart.itemFallbackName", "Cart item");
|
|
235
|
+
const image = mediaUrl(item);
|
|
236
|
+
const lines = Array.isArray(raw.descriptionLines) ? raw.descriptionLines as Array<{ name?: { original?: string }; plainText?: { original?: string }; colorInfo?: { original?: string; code?: string } }> : [];
|
|
237
|
+
const opts = lines.slice(0, 3).map(line => {
|
|
238
|
+
const label = line.name?.original?.trim() ?? "";
|
|
239
|
+
const name = label && label === label.toUpperCase() ? label.charAt(0) + label.slice(1).toLowerCase() : label;
|
|
240
|
+
const value = line.plainText?.original || line.colorInfo?.original || "";
|
|
241
|
+
return [name, value].filter(Boolean).join(": ");
|
|
242
|
+
});
|
|
243
|
+
const inventory = raw.inventory as { quantity?: number } | undefined;
|
|
244
|
+
const availabilityData = raw.availability as { status?: string; quantityAvailable?: number } | undefined;
|
|
245
|
+
const stockCount = Number(availabilityData?.quantityAvailable ?? raw.inventoryQuantity ?? inventory?.quantity);
|
|
246
|
+
const availability = String(availabilityData?.status ?? raw.availabilityStatus ?? "").toUpperCase();
|
|
247
|
+
const stockMessage = availability === "NOT_AVAILABLE" || availability === "NOT_FOUND" || availability.includes("OUT")
|
|
248
|
+
? copyParam("cart.outOfStock", "Out of stock")
|
|
249
|
+
: availability === "PARTIALLY_AVAILABLE" && Number.isFinite(stockCount) && stockCount > 0
|
|
250
|
+
? copyTemplate("cart.onlyLeft", "Only {count} left", { count: stockCount }) : "";
|
|
251
|
+
const inStock = !stockMessage && (availability === "AVAILABLE" || availability === "IN_STOCK" || availability === "PARTIALLY_AVAILABLE");
|
|
252
|
+
const total = (raw.lineItemPrice as { formattedAmount?: string } | undefined)?.formattedAmount
|
|
253
|
+
?? (raw.totalPriceAfterTax as { formattedAmount?: string } | undefined)?.formattedAmount
|
|
254
|
+
?? (raw.totalPriceBeforeTax as { formattedAmount?: string } | undefined)?.formattedAmount
|
|
255
|
+
?? item.price?.formattedAmount ?? "";
|
|
256
|
+
const unitPrice = item.price?.formattedAmount ?? "";
|
|
257
|
+
const fullPrice = (raw.fullPrice as { formattedAmount?: string } | undefined)?.formattedAmount ?? "";
|
|
258
|
+
const swatches = lines.map(line => line.colorInfo?.code ?? "").filter(code => /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(code)).slice(0, 5);
|
|
259
|
+
const saved = (() => { try { return isProductSaved(String((item as WixCartLineItemDetail & { catalogReference?: { catalogItemId?: string } }).catalogReference?.catalogItemId ?? "")); } catch { return false; } })();
|
|
260
|
+
return {
|
|
261
|
+
catalogReference: (item as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference,
|
|
262
|
+
catalogItemId: (item as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference?.catalogItemId ?? "",
|
|
263
|
+
id: item.id || `line-${index}`,
|
|
264
|
+
name,
|
|
265
|
+
title: name,
|
|
266
|
+
subtitle: copyTemplate("cart.quantityLine", "Qty {quantity}", { quantity }),
|
|
267
|
+
quantity,
|
|
268
|
+
quantityLabel: `${quantity}`,
|
|
269
|
+
atMinQuantity: quantity <= 1,
|
|
270
|
+
total,
|
|
271
|
+
unitPrice,
|
|
272
|
+
wasPrice: fullPrice && fullPrice !== unitPrice ? fullPrice : "",
|
|
273
|
+
swatches,
|
|
274
|
+
commerceTotal: total,
|
|
275
|
+
image,
|
|
276
|
+
initial: (name.trim()[0] || "C").toUpperCase(),
|
|
277
|
+
hasImage: Boolean(image),
|
|
278
|
+
noImage: !image,
|
|
279
|
+
option1: opts[0] ?? "", option2: opts[1] ?? "", option3: opts[2] ?? "",
|
|
280
|
+
noOption1: !opts[0], noOption2: !opts[1], noOption3: !opts[2],
|
|
281
|
+
stockMessage, noStockMessage: !stockMessage,
|
|
282
|
+
inStockMessage: inStock ? copyParam("cart.inStock", "In Stock") : "",
|
|
283
|
+
noInStockMessage: !inStock,
|
|
284
|
+
saved,
|
|
285
|
+
notSaved: !saved,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** POST /ecom/v1/carts/{cartId}/update-line-items-quantity via @himalaya/wix-ecom. */
|
|
290
|
+
function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: number): Promise<{ cart?: WixCartDetail }> {
|
|
291
|
+
return updateLineItemsQuantity(cartId, [{ id: lineItemId, quantity: Math.max(1, quantity) }]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function derive(state: State): State {
|
|
295
|
+
// Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
|
|
296
|
+
// in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
|
|
297
|
+
if (memberOnlyCart && !signedInMember()) {
|
|
298
|
+
state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
|
|
299
|
+
} else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
|
|
300
|
+
// Rows read under another member (a write's result that landed after the switch): hold a loading state, and
|
|
301
|
+
// reload for this member once the write has settled.
|
|
302
|
+
state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
|
|
303
|
+
queueSessionReload();
|
|
304
|
+
}
|
|
305
|
+
let savedIds: Set<string> | null = null;
|
|
306
|
+
try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
|
|
307
|
+
catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
|
|
308
|
+
const items = savedIds ? state.items.map(item => {
|
|
309
|
+
const productId = item.catalogReference?.catalogItemId ?? item.productId;
|
|
310
|
+
if (!productId) return item;
|
|
311
|
+
const saved = savedIds.has(productId);
|
|
312
|
+
return { ...item, saved, notSaved: !saved };
|
|
313
|
+
}) : state.items;
|
|
314
|
+
const itemCount = items.reduce((n, item) => n + item.quantity, 0);
|
|
315
|
+
return {
|
|
316
|
+
...state,
|
|
317
|
+
items,
|
|
318
|
+
promoBusy: promoInFlight && state.promoBusy,
|
|
319
|
+
isLoading: state.status === "loading",
|
|
320
|
+
notLoading: state.status !== "loading",
|
|
321
|
+
isErrored: state.status === "error",
|
|
322
|
+
notErrored: state.status !== "error",
|
|
323
|
+
noOfflineError: state.status !== "error" || state.errorKind !== "offline",
|
|
324
|
+
noServerError: state.status !== "error" || state.errorKind !== "server",
|
|
325
|
+
// Exactly one of {content, error card, empty card} renders: content only on
|
|
326
|
+
// "ready" (an errored cart must not paint a blank subtotal), the error card
|
|
327
|
+
// on "error", the empty card on ready + no items.
|
|
328
|
+
hideContent: state.status !== "ready",
|
|
329
|
+
noEmpty: state.status !== "ready" || items.length > 0,
|
|
330
|
+
noItems: items.length === 0,
|
|
331
|
+
itemCount,
|
|
332
|
+
hasCoupon: Boolean(state.appliedCode),
|
|
333
|
+
appliedLabel: state.appliedCode ? copyTemplate("cart.promoApplied", "Promo code {code}", { code: state.appliedCode }) : "",
|
|
334
|
+
noPromoError: !state.promoError,
|
|
335
|
+
noDiscount: !state.discount,
|
|
336
|
+
noCheckoutHint: !state.checkoutHint || state.showPaidToast,
|
|
337
|
+
noPaidToast: !state.showPaidToast,
|
|
338
|
+
noCoupon: !state.appliedCode,
|
|
339
|
+
subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
|
|
340
|
+
noSignIn: !state.needsSignIn,
|
|
341
|
+
// Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
|
|
342
|
+
...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Remove one line (the trash button, and "−" at quantity 1). The cache drops it only once
|
|
347
|
+
* Wix confirms; a failure keeps it on screen and says why. */
|
|
348
|
+
/** Remove one line (the trash button, and "−" at quantity 1). The cache drops it only once
|
|
349
|
+
* Wix confirms; a failure keeps it on screen and says why. */
|
|
350
|
+
async function removeLine(state: State, id: string): Promise<State> {
|
|
351
|
+
try {
|
|
352
|
+
await removeLineItemsFromCurrentCart([id]);
|
|
353
|
+
} catch (e) {
|
|
354
|
+
// The line stays visible (and cached) until a read says otherwise.
|
|
355
|
+
if (isOfflineFailure(e)) {
|
|
356
|
+
return derive({ ...state, checkoutHint: copyParam("cart.removeOfflineFailedMessage", "You’re offline — nothing was removed. Try again when you reconnect.") });
|
|
357
|
+
}
|
|
358
|
+
// It may have landed (mid-request drop, after-send envelope, gateway 5xx): say so,
|
|
359
|
+
// rather than "could not remove".
|
|
360
|
+
if (writeMayHaveLanded(e)) {
|
|
361
|
+
return derive({ ...state, checkoutHint: copyParam("cart.removeUnconfirmedMessage", "The connection dropped, so this item may already be removed. Refresh to check.") });
|
|
362
|
+
}
|
|
363
|
+
return derive({ ...state, checkoutHint: copyParam("cart.removeFailedMessage", "Could not remove this item.") });
|
|
364
|
+
}
|
|
365
|
+
// Wix confirmed it: only now does the line leave the cache, and it stays gone even
|
|
366
|
+
// if the re-fetch below fails.
|
|
367
|
+
await cacheDrop(id);
|
|
368
|
+
const removed = copyParam("cart.itemRemovedMessage", "Item removed.");
|
|
369
|
+
try {
|
|
370
|
+
return await refresh(state, removed);
|
|
371
|
+
} catch {
|
|
372
|
+
// The totals Wix last sent still count the removed line, and the new ones did not
|
|
373
|
+
// arrive: show none rather than a wrong one.
|
|
374
|
+
const items = state.items.filter((it) => it.id !== id);
|
|
375
|
+
return derive({ ...state, status: "ready", items, subtotal: "", commerceSubtotal: "", emptyText: items.length ? "" : copyParam("cart.emptyText", "Your cart is empty."), checkoutHint: removed });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function refresh(state: State, checkoutHint = "", updatedCart?: WixCartDetail, calculatedCart?: unknown): Promise<State> {
|
|
380
|
+
const cart = updatedCart ?? await getCurrentCart();
|
|
381
|
+
const items = (cart.lineItems ?? []).map(row);
|
|
382
|
+
await writeCachedItems(items);
|
|
383
|
+
const rawCart = cart as unknown as Record<string, unknown>;
|
|
384
|
+
const summary = (rawCart.priceSummary ?? rawCart.totals ?? {}) as Record<string, unknown>;
|
|
385
|
+
const discountRaw = (summary.discount ?? summary.discountAmount) as { formattedAmount?: string } | string | undefined;
|
|
386
|
+
const applied = couponDetails(cart);
|
|
387
|
+
let discount = formattedDiscount(typeof discountRaw === "string" ? discountRaw : discountRaw?.formattedAmount ?? "");
|
|
388
|
+
if (applied.code && !discount) {
|
|
389
|
+
const calculated = calculatedCart ?? await calculateCurrentCart().catch(() => null);
|
|
390
|
+
discount = calculatedDiscount(calculated, String(rawCart.currency ?? rawCart.paymentCurrency ?? "")) || (state.appliedCode === applied.code ? state.discount : "");
|
|
391
|
+
}
|
|
392
|
+
return derive({
|
|
393
|
+
...state,
|
|
394
|
+
status: "ready",
|
|
395
|
+
items,
|
|
396
|
+
subtotal: cart.subtotal?.formattedAmount ?? "",
|
|
397
|
+
commerceSubtotal: cart.subtotal?.formattedAmount ?? "",
|
|
398
|
+
discount,
|
|
399
|
+
appliedCode: applied.code,
|
|
400
|
+
couponId: applied.id,
|
|
401
|
+
emptyText: items.length ? "" : copyParam("cart.emptyText", "Your cart is empty."),
|
|
402
|
+
...(items.length ? {} : { promoCode: "", appliedCode: "", couponId: "", discount: "", promoError: "" }),
|
|
403
|
+
checkoutHint,
|
|
404
|
+
showPaidToast: false,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function formattedDiscount(value: string): string {
|
|
409
|
+
if (!value || !/[1-9]/.test(value)) return "";
|
|
410
|
+
return /^[−-]/.test(value.trim()) ? value : `−${value}`;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function calculatedDiscount(result: unknown, currency: string): string {
|
|
414
|
+
const discount = (result as { summary?: { priceSummary?: { discount?: { amount?: string; convertedAmount?: string } } } } | null)?.summary?.priceSummary?.discount;
|
|
415
|
+
const amount = Number(discount?.amount);
|
|
416
|
+
if (!Number.isFinite(amount) || amount === 0 || !currency) return "";
|
|
417
|
+
return formattedDiscount(formatCurrency(Math.abs(amount), currency));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function invalidCouponFailure(error: unknown): boolean {
|
|
421
|
+
const status = Number((error as { status?: unknown; statusCode?: unknown } | null)?.status ?? (error as { statusCode?: unknown } | null)?.statusCode);
|
|
422
|
+
const message = String((error as Error | null)?.message ?? error ?? "");
|
|
423
|
+
return status === 400 || status === 422 || /\bHTTP (?:400|422)\b|INVALID_COUPON|COUPON_(?:NOT_FOUND|EXPIRED)/i.test(message);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function couponDetails(result: unknown): { id: string; code: string } {
|
|
427
|
+
const envelope = result as { cart?: Record<string, unknown> } | null;
|
|
428
|
+
const cart = envelope?.cart ?? result as Record<string, unknown> | null;
|
|
429
|
+
const discounts = cart?.appliedDiscounts as Array<{ coupon?: { id?: string; code?: string }; id?: string; code?: string }> | { discounts?: Array<{ coupon?: { id?: string; code?: string }; id?: string; code?: string }> } | undefined;
|
|
430
|
+
const coupon = (Array.isArray(discounts) ? discounts : discounts?.discounts)?.find(entry => entry.coupon?.code || entry.code);
|
|
431
|
+
return { id: coupon?.coupon?.id ?? coupon?.id ?? "", code: coupon?.coupon?.code ?? coupon?.code ?? "" };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
|
|
435
|
+
|
|
436
|
+
let cartPricing: IapCommerce;
|
|
437
|
+
const defineService = withIapPresentation<State>({
|
|
438
|
+
register: withExclusiveWrites<State>(withOnlineWrites(registerState, ["remove", "increment", "decrement", "checkout", "beginPromo", "applyPromo", "removePromo"], { derive, messageFields: action => action.includes("Promo") ? ["promoError"] : ["checkoutHint"] }), ["load", "remove", "increment", "decrement", "checkout", "applyPromo", "removePromo", "save"], {
|
|
439
|
+
prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
|
|
440
|
+
coalesce: ["load"],
|
|
441
|
+
// Full cart reloads share the transaction, since they also replace rows and
|
|
442
|
+
// reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
|
|
443
|
+
// must not masquerade as a user edit when a rejected code is retried.
|
|
444
|
+
settle: (before, next, live) => {
|
|
445
|
+
if ((before.promoEditRevision ?? 0) === (live.promoEditRevision ?? 0)) return next;
|
|
446
|
+
return derive({ ...next, promoEditRevision: live.promoEditRevision,
|
|
447
|
+
...(next.items.length ? { promoCode: live.promoCode, promoError: live.promoError } : {}) });
|
|
448
|
+
},
|
|
449
|
+
}),
|
|
450
|
+
onCreate: commerce => { cartPricing = commerce; },
|
|
451
|
+
prefix: "cart", transientKeys: ["items", "subtotal", "promoBusy", "promoEditRevision"], contentActions: ["load", "remove", "increment", "decrement"],
|
|
452
|
+
items: state => state.items.flatMap(row => row.catalogReference?.catalogItemId ? [{ reference: { kind: "storesProduct", id: row.catalogReference.catalogItemId }, commerceDisplayPrice: row.commerceTotal ?? row.total }] : []),
|
|
453
|
+
present: (state, price, allowed) => ({ ...state,
|
|
454
|
+
items: state.items.map(row => ({ ...row, total: row.catalogReference?.catalogItemId ? price(row.catalogReference.catalogItemId, row.commerceTotal ?? row.total) : row.total })),
|
|
455
|
+
subtotal: state.items.length > 0 && state.items.every(row => row.catalogReference?.catalogItemId && allowed(row.catalogReference.catalogItemId)) ? state.commerceSubtotal ?? state.subtotal : "" }),
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
let promoInFlight = false;
|
|
459
|
+
const svc = defineService<State, {
|
|
460
|
+
load: (state: State, arg?: unknown) => Promise<State>;
|
|
461
|
+
setPromo: (state: State, arg?: unknown) => State;
|
|
462
|
+
beginPromo: (state: State) => State;
|
|
463
|
+
applyPromo: (state: State) => Promise<State>;
|
|
464
|
+
removePromo: (state: State) => Promise<State>;
|
|
465
|
+
remove: (state: State, arg?: unknown) => Promise<State>;
|
|
466
|
+
save: (state: State, arg?: unknown) => State;
|
|
467
|
+
increment: (state: State, arg?: unknown) => Promise<State>;
|
|
468
|
+
decrement: (state: State, arg?: unknown) => Promise<State>;
|
|
469
|
+
checkout: (state: State) => Promise<State>;
|
|
470
|
+
dropForSession: (state: State) => State;
|
|
471
|
+
onIdentityChange: (state: State, change?: unknown) => State;
|
|
472
|
+
}>("himiStoreCart", {
|
|
473
|
+
state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true, memberOnly: false, needsSignIn: false, noSignIn: true }),
|
|
474
|
+
actions: {
|
|
475
|
+
// Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
|
|
476
|
+
dropForSession: (state) => derive(state),
|
|
477
|
+
// The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
|
|
478
|
+
onIdentityChange: (state, change) => {
|
|
479
|
+
webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
|
|
480
|
+
webGeneration++;
|
|
481
|
+
if (memberOnlyCart) queueSessionReload();
|
|
482
|
+
return derive(state);
|
|
483
|
+
},
|
|
484
|
+
load: async (state, arg) => {
|
|
485
|
+
// A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
|
|
486
|
+
// before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
|
|
487
|
+
if (memberOnlyArg(arg)) memberOnlyCart = true;
|
|
488
|
+
const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
|
|
489
|
+
if (memberOnlyCart && !signedInMember()) return gated();
|
|
490
|
+
if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
|
|
491
|
+
const readUnder = sessionGeneration();
|
|
492
|
+
// This read is for the current member: rows it derives stand until the generation moves on.
|
|
493
|
+
if (memberOnlyCart) rowsGeneration = readUnder;
|
|
494
|
+
const landed = (next: State): State => {
|
|
495
|
+
if (!memberOnlyCart) return next;
|
|
496
|
+
if (!signedInMember()) return gated();
|
|
497
|
+
if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
|
|
498
|
+
return derive({ ...next, memberOnly: true, needsSignIn: false });
|
|
499
|
+
};
|
|
500
|
+
// 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
|
|
501
|
+
const cached = await readCachedItems();
|
|
502
|
+
const base = cached.length
|
|
503
|
+
? derive({ ...state, status: "ready", items: cached, emptyText: "" })
|
|
504
|
+
: state;
|
|
505
|
+
// 2) Revalidate from Wix and refresh the cache.
|
|
506
|
+
try {
|
|
507
|
+
return landed(await refresh(state));
|
|
508
|
+
} catch (error) {
|
|
509
|
+
// Offline / fetch failure: keep the cached items instead of a blank error state.
|
|
510
|
+
return landed(cached.length
|
|
511
|
+
? base
|
|
512
|
+
: derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
setPromo: (state, arg) => derive({ ...state, promoEditRevision: (state.promoEditRevision ?? 0) + 1, promoCode: (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? "")).slice(0, 100), promoError: "" }),
|
|
516
|
+
beginPromo: state => derive({ ...state, promoBusy: true, promoError: "" }),
|
|
517
|
+
applyPromo: async (state): Promise<State> => {
|
|
518
|
+
const code = state.promoCode.trim();
|
|
519
|
+
if (promoInFlight) return svc.getState() as State;
|
|
520
|
+
if (!code) return derive({ ...state, promoError: copyParam("cart.promoEmpty", "Enter a promo code.") });
|
|
521
|
+
promoInFlight = true;
|
|
522
|
+
let added = false;
|
|
523
|
+
try {
|
|
524
|
+
await svc.beginPromo();
|
|
525
|
+
state = svc.getState() as State;
|
|
526
|
+
await addCouponToCurrentCart(code);
|
|
527
|
+
added = true;
|
|
528
|
+
const calculated = await calculateCurrentCart().catch(() => null);
|
|
529
|
+
const refreshed = await refresh(state, "", undefined, calculated);
|
|
530
|
+
return refreshed.appliedCode
|
|
531
|
+
? derive({ ...refreshed, promoBusy: false, promoCode: "", promoError: "" })
|
|
532
|
+
: derive({ ...refreshed, promoBusy: false, promoCode: state.promoCode, promoError: copyParam("cart.promoInvalid", "This promo code is not valid.") });
|
|
533
|
+
} catch (error) {
|
|
534
|
+
const mayHaveLanded = added || writeMayHaveLanded(error);
|
|
535
|
+
const refreshed = mayHaveLanded ? await refresh(state).catch(() => null) : null;
|
|
536
|
+
if (refreshed?.appliedCode === code) return derive({ ...refreshed, promoBusy: false, promoCode: "", promoError: "" });
|
|
537
|
+
// 130:117 couponApplyingFailed (ecom-platform bi/storefront.ts:448, sent from cartActions.ts:345 when
|
|
538
|
+
// the add-coupon call throws). errorCode is RN's serializeError(e).code, the Wix application error code.
|
|
539
|
+
// Only the add-coupon call itself: once it answered, the coupon is on the cart, and a later step that
|
|
540
|
+
// throws (the cart refresh) is not a coupon that failed to apply.
|
|
541
|
+
if (!added) {
|
|
542
|
+
const errorCode = wixErrorCode(error);
|
|
543
|
+
logBi({ evid: 117, src: 130, endpoint: "ec-site", params: { origin: "checkout", couponCode: code, ...(errorCode ? { errorCode } : {}) } });
|
|
544
|
+
}
|
|
545
|
+
return derive({ ...state, promoBusy: false, promoError: mayHaveLanded
|
|
546
|
+
? copyParam("cart.promoUnconfirmed", "Could not confirm the promo code. Refresh your cart.")
|
|
547
|
+
: isOfflineFailure(error)
|
|
548
|
+
? copyParam("cart.promoOffline", "Connect to the internet to use a promo code.")
|
|
549
|
+
: invalidCouponFailure(error)
|
|
550
|
+
? copyParam("cart.promoInvalid", "This promo code is not valid.")
|
|
551
|
+
: copyParam("cart.promoUnavailable", "Could not apply the promo code. Try again.") });
|
|
552
|
+
} finally {
|
|
553
|
+
promoInFlight = false;
|
|
554
|
+
}
|
|
555
|
+
},
|
|
556
|
+
removePromo: async state => {
|
|
557
|
+
if (!state.couponId) return derive({ ...state, appliedCode: "", discount: "" });
|
|
558
|
+
let removed = false;
|
|
559
|
+
try {
|
|
560
|
+
await removeCouponFromCurrentCart(state.couponId);
|
|
561
|
+
removed = true;
|
|
562
|
+
await calculateCurrentCart().catch(() => null);
|
|
563
|
+
return derive({ ...(await refresh(state)), appliedCode: "", couponId: "", promoError: "" });
|
|
564
|
+
} catch (error) {
|
|
565
|
+
const mayHaveLanded = removed || writeMayHaveLanded(error);
|
|
566
|
+
const refreshed = mayHaveLanded ? await refresh(state).catch(() => null) : null;
|
|
567
|
+
if (refreshed && !refreshed.appliedCode) return derive({ ...refreshed, promoError: "" });
|
|
568
|
+
return derive({ ...state, promoError: mayHaveLanded
|
|
569
|
+
? copyParam("cart.promoRemoveUnconfirmed", "Could not confirm promo removal. Refresh your cart.")
|
|
570
|
+
: copyParam("cart.promoRemoveFailed", "Could not remove the promo code.") });
|
|
571
|
+
}
|
|
572
|
+
},
|
|
573
|
+
remove: async (state, arg) => {
|
|
574
|
+
const id = itemId(arg);
|
|
575
|
+
if (!id) return state;
|
|
576
|
+
return removeLine(state, id);
|
|
577
|
+
},
|
|
578
|
+
save: (state, arg) => {
|
|
579
|
+
const id = itemId(arg);
|
|
580
|
+
const item = state.items.find(candidate => candidate.id === id);
|
|
581
|
+
const productId = item?.catalogReference?.catalogItemId ?? item?.productId;
|
|
582
|
+
if (!item || !productId) return state;
|
|
583
|
+
try {
|
|
584
|
+
const saved = toggleSavedProduct({ id: productId, name: item.name, price: item.unitPrice, wasPrice: item.wasPrice, image: item.image, swatches: item.swatches });
|
|
585
|
+
return derive({ ...state, items: state.items.map(candidate => (candidate.catalogReference?.catalogItemId ?? candidate.productId) === productId ? { ...candidate, saved, notSaved: !saved } : candidate) });
|
|
586
|
+
} catch { return derive({ ...state, checkoutHint: copyParam("cart.saveError", "Could not save this item.") }); }
|
|
587
|
+
},
|
|
588
|
+
increment: async (state, arg) => {
|
|
589
|
+
const id = itemId(arg);
|
|
590
|
+
const line = state.items.find((candidate) => candidate.id === id);
|
|
591
|
+
if (!line) return state;
|
|
592
|
+
try {
|
|
593
|
+
const cartId = (await getCurrentCart()).id || "";
|
|
594
|
+
const updated = await updateLineItemQuantity(cartId, id, line.quantity + 1);
|
|
595
|
+
return await refresh(state, "", updated.cart);
|
|
596
|
+
} catch {
|
|
597
|
+
return derive({ ...state, checkoutHint: copyParam("cart.quantityFailedMessage", "Could not update the quantity.") });
|
|
598
|
+
}
|
|
599
|
+
},
|
|
600
|
+
decrement: async (state, arg) => {
|
|
601
|
+
const id = itemId(arg);
|
|
602
|
+
const line = state.items.find((candidate) => candidate.id === id);
|
|
603
|
+
if (!line) return state;
|
|
604
|
+
// Qty 1 − ⇒ remove the line (the control never dead-ends), with remove's handling.
|
|
605
|
+
if (line.quantity <= 1) return removeLine(state, id);
|
|
606
|
+
try {
|
|
607
|
+
const cartId = (await getCurrentCart()).id || "";
|
|
608
|
+
const updated = await updateLineItemQuantity(cartId, id, line.quantity - 1);
|
|
609
|
+
return await refresh(state, "", updated.cart);
|
|
610
|
+
} catch {
|
|
611
|
+
return derive({ ...state, checkoutHint: copyParam("cart.quantityFailedMessage", "Could not update the quantity.") });
|
|
612
|
+
}
|
|
613
|
+
},
|
|
614
|
+
// Physical checkout collects shipping before the site's checkout creates the order.
|
|
615
|
+
checkout: async (state) => {
|
|
616
|
+
let validatedLines: WixCartLineItemDetail[] = [];
|
|
617
|
+
const signature = (lines: WixCartLineItemDetail[]) => JSON.stringify(lines.map(line => [line.id, line.quantity, (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference]));
|
|
618
|
+
try {
|
|
619
|
+
const cart = await getCurrentCart();
|
|
620
|
+
const lines = cart.lineItems ?? [];
|
|
621
|
+
if (!lines.length) return derive({ ...state, checkoutHint: copyParam("cart.checkoutEmptyMessage", "Add an item before checkout.") });
|
|
622
|
+
const commerce = cartPricing;
|
|
623
|
+
const items = lines.map(line => (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference);
|
|
624
|
+
if (items.some(item => !item?.catalogItemId || !item.appId)) return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable });
|
|
625
|
+
// Restaurant dishes share this Wix cart but check out on the food order screen; this checkout
|
|
626
|
+
// takes Stores products only, so say which lines are in the way rather than "unavailable".
|
|
627
|
+
if (items.some(item => item!.appId === RESTAURANTS_ORDERS_APP_ID)) {
|
|
628
|
+
return derive({ ...state, checkoutHint: copyParam("cart.restaurantItemsHint", "This cart also has restaurant dishes. Remove them here to check out your store items.") });
|
|
629
|
+
}
|
|
630
|
+
await commerce.loadPrices(items.map((item, index) => ({ reference: { kind: "storesProduct", id: item!.catalogItemId }, commerceDisplayPrice: lines[index].price?.formattedAmount })));
|
|
631
|
+
const classification = classifyCart(items.map((item, index) => ({ route: commerce.pricing.view({ kind: "storesProduct", id: item!.catalogItemId }).route, quantity: lines[index].quantity ?? 1 })));
|
|
632
|
+
if (classification !== "regular") return derive({ ...state, checkoutHint: classification === "mixedRefused" ? copyParam("cart.iapSingleItemOnly", "Buy digital items individually, with quantity 1 and no options.") : iapPriceCopy("cart").purchaseUnavailable });
|
|
633
|
+
const products = await Promise.all(items.map(async item => item!.appId === WIX_STORES_CATALOG_ID ? (await getStoreProduct(item!.catalogItemId)).product : undefined));
|
|
634
|
+
if (products.some(product => product?.productType?.toLowerCase() !== "physical")) return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable });
|
|
635
|
+
const latest = await getCurrentCart();
|
|
636
|
+
if (signature(latest.lineItems ?? []) !== signature(lines)) return derive({ ...state, checkoutHint: copyParam("cart.changedBeforeCheckout", "Your cart changed. Review it before checking out.") });
|
|
637
|
+
validatedLines = lines;
|
|
638
|
+
} catch { return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable }); }
|
|
639
|
+
|
|
640
|
+
if (!state.items.length) return derive({ ...state, checkoutHint: copyParam("cart.checkoutEmptyMessage", "Add an item before checkout.") });
|
|
641
|
+
try {
|
|
642
|
+
const checkout = await createCheckoutFromCurrentCart();
|
|
643
|
+
if (!checkout.checkoutId) return derive({ ...state, checkoutHint: copyParam("cart.checkoutIdMissingMessage", "Wix did not return a checkout id.") });
|
|
644
|
+
const checkoutId = checkout.checkoutId;
|
|
645
|
+
|
|
646
|
+
const hosted = isHostedWorker();
|
|
647
|
+
const pay = await payCashierOrder({
|
|
648
|
+
appId: WIX_STORES_APP_ID,
|
|
649
|
+
snapshotId: "",
|
|
650
|
+
msid: "",
|
|
651
|
+
mayCharge: async () => {
|
|
652
|
+
const latest = await getCurrentCart();
|
|
653
|
+
if (signature(latest.lineItems ?? []) !== signature(validatedLines)) return false;
|
|
654
|
+
return validatedLines.every(line => {
|
|
655
|
+
const reference = (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference;
|
|
656
|
+
return !!reference && cartPricing.pricing.continueCheckoutGuard({ kind: "storesProduct", id: reference.catalogItemId }).allowed;
|
|
657
|
+
});
|
|
658
|
+
},
|
|
659
|
+
// Hosted (Spaces): the host opens the checkout as the lent member — Headless redirect
|
|
660
|
+
// sessions do not take a Member instance.
|
|
661
|
+
...(hosted ? { openCashier: hostedCheckoutOpener(checkoutId) } : {}),
|
|
662
|
+
cashierUrl: async () => {
|
|
663
|
+
const redirect = await createRedirectSession({
|
|
664
|
+
ecomCheckout: { checkoutId },
|
|
665
|
+
callbacks: { postFlowUrl: cashierReturnUrl },
|
|
666
|
+
});
|
|
667
|
+
return redirect.redirectSession?.fullUrl;
|
|
668
|
+
},
|
|
669
|
+
});
|
|
670
|
+
if (pay.kind === "handoff") {
|
|
671
|
+
// Do NOT clear the cart: payment completes in the cashier and the order is
|
|
672
|
+
// only confirmed once it lands, so the cart must survive a bail-out.
|
|
673
|
+
return derive({ ...state, checkoutHint: copyParam("cart.checkoutOpenedMessage", "Checkout opened.") });
|
|
674
|
+
}
|
|
675
|
+
if (isPaymentSetupFailure(pay)) return derive({ ...state, checkoutHint: paymentSetupMessage("cart") });
|
|
676
|
+
return derive({ ...state, checkoutHint: copyParam("cart.checkoutFailedMessage", "Checkout could not start.") });
|
|
677
|
+
} catch (error) {
|
|
678
|
+
if (isPaymentSetupFailure(error)) return derive({ ...state, checkoutHint: paymentSetupMessage("cart") });
|
|
679
|
+
return derive({ ...state, checkoutHint: copyParam("cart.checkoutFailedMessage", "Checkout could not start.") });
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
},
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
/** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
|
|
686
|
+
* (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
|
|
687
|
+
/** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
|
|
688
|
+
let sessionReloadQueued = false;
|
|
689
|
+
function queueSessionReload(): void {
|
|
690
|
+
if (sessionReloadQueued) return;
|
|
691
|
+
sessionReloadQueued = true;
|
|
692
|
+
void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
|
|
693
|
+
}
|
|
694
|
+
function reloadForSession(tries = 4): void {
|
|
695
|
+
void Promise.resolve(svc.load()).finally(() => {
|
|
696
|
+
if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
svc.load();
|
|
700
|
+
// A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
|
|
701
|
+
// The host clock notifies at once on subscribe, which the boot load above already covers.
|
|
702
|
+
hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
|
|
703
|
+
export { svc };
|