@usequeek/theme-kit 0.1.28 → 0.1.30
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/README.md +82 -0
- package/apps/storefront-events.ts +277 -0
- package/client.ts +3 -0
- package/components/cart/cart-panel-controller.tsx +5 -1
- package/components/cart/default-cart-shell.tsx +68 -7
- package/hooks/use-add-app-block-lines.ts +258 -0
- package/hooks/use-cart-server-pricing.tsx +33 -0
- package/hooks/use-products.ts +20 -5
- package/hooks/use-shop-cart.ts +15 -1
- package/index.ts +2 -0
- package/locales/en.default.json +2 -1
- package/package.json +1 -1
- package/stores/cart-store.ts +39 -16
- package/types/app-block.ts +86 -0
- package/types/vendor.ts +7 -1
- package/utils/cart-pricing.ts +115 -0
- package/utils/format.ts +45 -0
- package/apps/analytics-events.ts +0 -32
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
4
|
+
import { useStorefront, useStorefrontLocale } from '../provider';
|
|
5
|
+
import { ApiRequestError } from '../sdk/client';
|
|
6
|
+
import { useCartStore } from '../stores/cart-store';
|
|
7
|
+
import type { Product, ProductVariant } from '../types/product';
|
|
8
|
+
import type { AddAppBlockLinesResult, AppBlockLine, AppBlockLineOutcome, AppBlockLineStatus } from '../types/app-block';
|
|
9
|
+
import { requiredAddonsSatisfied } from '../utils/addon-selection';
|
|
10
|
+
import { productRequiresVariant } from '../utils/match-variant';
|
|
11
|
+
import { fetchProductBySlug } from './use-products';
|
|
12
|
+
|
|
13
|
+
/** Lines one press may add; the platform read caps at the same number. */
|
|
14
|
+
export const APP_BLOCK_MAX_LINES = 20;
|
|
15
|
+
|
|
16
|
+
type LoadProduct = (slug: string) => Promise<Product | null>;
|
|
17
|
+
|
|
18
|
+
type Loaded = { product: Product | null } | { failed: true };
|
|
19
|
+
|
|
20
|
+
async function load(loadProduct: LoadProduct, slug: string): Promise<Loaded> {
|
|
21
|
+
try {
|
|
22
|
+
return { product: await loadProduct(slug) };
|
|
23
|
+
} catch (caught) {
|
|
24
|
+
// A product that is gone is "unavailable"; any other failure may pass on a retry.
|
|
25
|
+
return caught instanceof ApiRequestError && caught.code === 'not_found' ? { product: null } : { failed: true };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function validShape(line: AppBlockLine | null | undefined): line is AppBlockLine {
|
|
30
|
+
return (
|
|
31
|
+
typeof line === 'object' &&
|
|
32
|
+
line !== null &&
|
|
33
|
+
typeof line.slug === 'string' &&
|
|
34
|
+
line.slug !== '' &&
|
|
35
|
+
typeof line.product_id === 'string' &&
|
|
36
|
+
Number.isInteger(line.quantity) &&
|
|
37
|
+
line.quantity >= 1 &&
|
|
38
|
+
line.quantity <= 20
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The variant a line names on a variant product, or the status that stops it. */
|
|
43
|
+
function resolveVariant(product: Product, line: AppBlockLine): ProductVariant | AppBlockLineStatus {
|
|
44
|
+
if (!line.variant_id) {
|
|
45
|
+
return 'variant_required';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const variant = product.variants?.find((entry) => entry.id === line.variant_id);
|
|
49
|
+
|
|
50
|
+
// Only `in_stock` is read: the server folds the store's own stock setting into
|
|
51
|
+
// it. `tracking` and `quantity` are raw columns (a store that never enabled
|
|
52
|
+
// tracking sends every variant as tracked with 0 left), and stock is enforced
|
|
53
|
+
// at checkout, not by this helper, so a quantity is never compared with them.
|
|
54
|
+
return !variant || !variant.is_active || variant.inventory?.in_stock === false ? 'unavailable' : variant;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether the server would turn the line away, judged from the product as read.
|
|
59
|
+
* It mirrors the cart write, which adds nothing for a variant product without a
|
|
60
|
+
* valid variant and for a product with a required add-on group. A pack group
|
|
61
|
+
* counts too: the server composes its items, and delivery checkout rejects a
|
|
62
|
+
* line without them, so a bare line is never added. The kit itself cannot see
|
|
63
|
+
* that write (the host app syncs the cart); these are the cases it can know here.
|
|
64
|
+
*/
|
|
65
|
+
function classify(product: Product | null, line: AppBlockLine, shopId: string): ProductVariant | AppBlockLineStatus | null {
|
|
66
|
+
if (!product || product.id !== line.product_id || product.shop_id !== shopId || product.status === 'inactive') {
|
|
67
|
+
return 'unavailable';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (productRequiresVariant(product)) {
|
|
71
|
+
return resolveVariant(product, line);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (line.variant_id || product.inventory?.in_stock === false) {
|
|
75
|
+
return 'unavailable';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return requiredAddonsSatisfied(product.addons ?? [], new Set()) ? null : 'customise';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Adds the lines of an add-to-cart app block through the cart store's own
|
|
83
|
+
* `addItemWithAddons`, one line at a time and silently, and reports what
|
|
84
|
+
* happened to each. `loadProduct` resolves a line's product by slug; a hook
|
|
85
|
+
* wraps it for storefront use ({@link useAddAppBlockLines}).
|
|
86
|
+
*
|
|
87
|
+
* The first 20 lines are tried; the rest are `over_limit`. A line that cannot
|
|
88
|
+
* be added is reported and the others are still added. The stored price of a
|
|
89
|
+
* line is whatever the store computes for the product (or variant) alone: the
|
|
90
|
+
* function never reads pricing, offers or anything an app sent beyond the
|
|
91
|
+
* product, variant and quantity.
|
|
92
|
+
*/
|
|
93
|
+
export async function addAppBlockLines(
|
|
94
|
+
lines: AppBlockLine[],
|
|
95
|
+
{ shopId, loadProduct }: { shopId: string; loadProduct: LoadProduct },
|
|
96
|
+
): Promise<AddAppBlockLinesResult> {
|
|
97
|
+
const given: Array<AppBlockLine | null | undefined> = Array.isArray(lines) ? lines : [];
|
|
98
|
+
const tried = given.slice(0, APP_BLOCK_MAX_LINES);
|
|
99
|
+
const slugs = [...new Set(tried.filter(validShape).map((line) => line.slug))];
|
|
100
|
+
const loaded = new Map<string, Loaded>();
|
|
101
|
+
|
|
102
|
+
await Promise.all(slugs.map(async (slug) => loaded.set(slug, await load(loadProduct, slug))));
|
|
103
|
+
|
|
104
|
+
const outcomes: AppBlockLineOutcome[] = given.map((line, index) => {
|
|
105
|
+
const base = {
|
|
106
|
+
index,
|
|
107
|
+
product_id: typeof line?.product_id === 'string' ? line.product_id : '',
|
|
108
|
+
variant_id: typeof line?.variant_id === 'string' ? line.variant_id : null,
|
|
109
|
+
title: null as string | null,
|
|
110
|
+
...(line?.properties && typeof line.properties === 'object' && Object.keys(line.properties).length > 0 ? { properties_dropped: true as const } : {}),
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
if (index >= APP_BLOCK_MAX_LINES) {
|
|
114
|
+
return { ...base, status: 'over_limit' };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!validShape(line)) {
|
|
118
|
+
return { ...base, status: 'failed' };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
return addOne(line, base, loaded.get(line.slug), shopId);
|
|
123
|
+
} catch (caught) {
|
|
124
|
+
// A throw before the store call leaves the cart as it was.
|
|
125
|
+
console.error('[cart] an add-to-cart app block line failed:', caught);
|
|
126
|
+
|
|
127
|
+
return { ...base, status: 'failed' };
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const added = outcomes.filter((outcome) => outcome.status === 'added').length;
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
added,
|
|
135
|
+
outcomes,
|
|
136
|
+
complete: outcomes.length > 0 && added === outcomes.length,
|
|
137
|
+
propertiesDropped: outcomes.some((outcome) => outcome.status === 'added' && outcome.properties_dropped === true),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function shopUnits(shopId: string): number {
|
|
142
|
+
return useCartStore.getState().items.reduce((sum, entry) => sum + (entry.shop_id === shopId ? entry.quantity : 0), 0);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function addOne(line: AppBlockLine, base: Omit<AppBlockLineOutcome, 'status'>, entry: Loaded | undefined, shopId: string): AppBlockLineOutcome {
|
|
146
|
+
if (!entry || 'failed' in entry) {
|
|
147
|
+
return { ...base, status: 'failed' };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const product = entry.product;
|
|
151
|
+
const verdict = classify(product, line, shopId);
|
|
152
|
+
const title = product?.title ?? null;
|
|
153
|
+
|
|
154
|
+
if (typeof verdict === 'string') {
|
|
155
|
+
return { ...base, title, status: verdict };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const before = shopUnits(shopId);
|
|
159
|
+
let result: ReturnType<ReturnType<typeof useCartStore.getState>['addItemWithAddons']>;
|
|
160
|
+
|
|
161
|
+
try {
|
|
162
|
+
result = useCartStore.getState().addItemWithAddons(product as Product, line.quantity, [], verdict, { silent: true });
|
|
163
|
+
} catch (caught) {
|
|
164
|
+
// The store writes the line before it reports the add (the analytics event
|
|
165
|
+
// comes last), so a throw is judged by what the cart holds, never guessed.
|
|
166
|
+
console.error('[cart] the cart store threw while adding an app block line:', caught);
|
|
167
|
+
|
|
168
|
+
return { ...base, title, status: shopUnits(shopId) >= before + line.quantity ? 'added' : 'failed' };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { ...base, title, status: result === 'added' ? 'added' : result === 'variant_required' ? 'variant_required' : 'customise' };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** What makes two presses the same pack: the same lines, in the same order. */
|
|
175
|
+
function pressSignature(lines: AppBlockLine[]): string {
|
|
176
|
+
return JSON.stringify(
|
|
177
|
+
(Array.isArray(lines) ? lines : []).map((line) =>
|
|
178
|
+
typeof line === 'object' && line !== null ? [line.product_id, line.slug, line.variant_id ?? null, line.quantity] : null,
|
|
179
|
+
),
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Puts the products of an add-to-cart app block into the shopper's cart through
|
|
185
|
+
* the store's own add action: no app code runs, no app writes to the cart, and
|
|
186
|
+
* no price is touched (each line is priced like the same product added from its
|
|
187
|
+
* page). Call `addLines` from the press handler with `lines` from the block's
|
|
188
|
+
* read, then print ONE notice from the result: "added" only when `complete` is
|
|
189
|
+
* true, else name the lines that were not added from `outcomes` (`customise`
|
|
190
|
+
* and `variant_required` mean the shopper must choose on the product page).
|
|
191
|
+
*
|
|
192
|
+
* `shopId` is the store's id (`product.shop_id`); a line whose product belongs
|
|
193
|
+
* to another store is `unavailable`. While a press is pending, `pending` is
|
|
194
|
+
* true and an `addLines` call with the same lines in the same order returns the
|
|
195
|
+
* pending result and adds nothing, so a double click adds the pack once; a
|
|
196
|
+
* different pack runs on its own. Disable the button on `pending` too.
|
|
197
|
+
*
|
|
198
|
+
* Limits: a line's `properties` are not written to the cart (the store has no
|
|
199
|
+
* entry for them; the outcome says `properties_dropped` and the result
|
|
200
|
+
* `propertiesDropped`), and the products are read fresh on every press.
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* const { addLines, pending } = useAddAppBlockLines(shopId);
|
|
204
|
+
* const result = await addLines(read.lines);
|
|
205
|
+
*/
|
|
206
|
+
export function useAddAppBlockLines(shopId: string | null | undefined): {
|
|
207
|
+
addLines: (lines: AppBlockLine[]) => Promise<AddAppBlockLinesResult>;
|
|
208
|
+
pending: boolean;
|
|
209
|
+
} {
|
|
210
|
+
const { previewData, vendor } = useStorefront();
|
|
211
|
+
const locale = useStorefrontLocale();
|
|
212
|
+
const [pending, setPending] = useState(false);
|
|
213
|
+
const inFlight = useRef(new Map<string, Promise<AddAppBlockLinesResult>>());
|
|
214
|
+
const mounted = useRef(true);
|
|
215
|
+
const previewProducts = previewData?.products;
|
|
216
|
+
const vendorSlug = vendor.slug;
|
|
217
|
+
|
|
218
|
+
useEffect(() => {
|
|
219
|
+
mounted.current = true;
|
|
220
|
+
|
|
221
|
+
return () => {
|
|
222
|
+
mounted.current = false;
|
|
223
|
+
};
|
|
224
|
+
}, []);
|
|
225
|
+
|
|
226
|
+
const addLines = useCallback(
|
|
227
|
+
(lines: AppBlockLine[]): Promise<AddAppBlockLinesResult> => {
|
|
228
|
+
const signature = pressSignature(lines);
|
|
229
|
+
const running = inFlight.current.get(signature);
|
|
230
|
+
|
|
231
|
+
if (running) {
|
|
232
|
+
return running;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const loadProduct: LoadProduct = async (slug) =>
|
|
236
|
+
Array.isArray(previewProducts)
|
|
237
|
+
? (previewProducts.find((entry) => entry.slug === slug) ?? null)
|
|
238
|
+
: fetchProductBySlug(vendorSlug, slug, locale);
|
|
239
|
+
|
|
240
|
+
setPending(true);
|
|
241
|
+
|
|
242
|
+
const run = addAppBlockLines(lines, { shopId: shopId ?? '', loadProduct }).finally(() => {
|
|
243
|
+
inFlight.current.delete(signature);
|
|
244
|
+
|
|
245
|
+
if (mounted.current) {
|
|
246
|
+
setPending(inFlight.current.size > 0);
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
inFlight.current.set(signature, run);
|
|
251
|
+
|
|
252
|
+
return run;
|
|
253
|
+
},
|
|
254
|
+
[shopId, previewProducts, vendorSlug, locale],
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
return { addLines, pending };
|
|
258
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import type { JSX, ReactNode } from 'react';
|
|
4
|
+
import { createContext, useContext } from 'react';
|
|
5
|
+
import type { CartServerPricing } from '../utils/cart-pricing';
|
|
6
|
+
|
|
7
|
+
const CartServerPricingContext = createContext<CartServerPricing | null>(null);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Where the host app hands the kit what the server charges for the cart on
|
|
11
|
+
* screen. The storefront mounts it once, above every theme, with the pricing
|
|
12
|
+
* it read from the server for the cart as it stands (or `null` when it has
|
|
13
|
+
* none). A theme never mounts it; it reads the result through `useShopCart()`
|
|
14
|
+
* or `CartPanelController`.
|
|
15
|
+
*/
|
|
16
|
+
export function CartServerPricingProvider({
|
|
17
|
+
value,
|
|
18
|
+
children,
|
|
19
|
+
}: {
|
|
20
|
+
value: CartServerPricing | null;
|
|
21
|
+
children: ReactNode;
|
|
22
|
+
}): JSX.Element {
|
|
23
|
+
return <CartServerPricingContext.Provider value={value}>{children}</CartServerPricingContext.Provider>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The pricing the host provided, exactly as given, or `null` without a provider.
|
|
28
|
+
* It is NOT checked against any cart lines: prefer `useShopCart(...).pricing`,
|
|
29
|
+
* which only returns it when it covers the lines on screen.
|
|
30
|
+
*/
|
|
31
|
+
export function useCartServerPricing(): CartServerPricing | null {
|
|
32
|
+
return useContext(CartServerPricingContext);
|
|
33
|
+
}
|
package/hooks/use-products.ts
CHANGED
|
@@ -167,6 +167,24 @@ export function useProducts(options?: ProductQuery & {
|
|
|
167
167
|
return { products, isLoading, error };
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
+
/**
|
|
171
|
+
* The `/products/{slug}` read behind {@link useProductBySlug}, for code that is
|
|
172
|
+
* not a hook (an event handler resolving several products). `null` when the
|
|
173
|
+
* response carries no product; a failed request throws.
|
|
174
|
+
*/
|
|
175
|
+
export async function fetchProductBySlug(
|
|
176
|
+
vendorSlug: string | null | undefined,
|
|
177
|
+
slug: string,
|
|
178
|
+
locale?: string | null,
|
|
179
|
+
): Promise<Product | null> {
|
|
180
|
+
const client = createBrowserClient(vendorSlug ?? undefined);
|
|
181
|
+
const response = await client.get<ApiResponse<LegacyProductLike>>(`/products/${encodeURIComponent(slug)}`, withLocaleQuery(undefined, locale));
|
|
182
|
+
const products = extractProducts(response.data);
|
|
183
|
+
const payload = products[0] ?? response.data;
|
|
184
|
+
|
|
185
|
+
return payload ? normalizeProduct(payload as LegacyProductLike) : null;
|
|
186
|
+
}
|
|
187
|
+
|
|
170
188
|
/**
|
|
171
189
|
* Fetch one product by slug: the same `/products/{slug}` request the product
|
|
172
190
|
* page uses, including the full ordered `media.images` list. The list
|
|
@@ -206,17 +224,14 @@ export function useProductBySlug(slug: string | null | undefined): { product: Pr
|
|
|
206
224
|
}
|
|
207
225
|
|
|
208
226
|
let cancelled = false;
|
|
209
|
-
const client = createBrowserClient(vendor.slug ?? undefined);
|
|
210
227
|
|
|
211
228
|
async function run(): Promise<void> {
|
|
212
229
|
setIsLoading(true);
|
|
213
230
|
setError(null);
|
|
214
231
|
try {
|
|
215
|
-
const
|
|
216
|
-
const products = extractProducts(response.data);
|
|
217
|
-
const payload = products[0] ?? response.data;
|
|
232
|
+
const fetched = await fetchProductBySlug(vendor.slug ?? undefined, slug as string, locale);
|
|
218
233
|
if (!cancelled) {
|
|
219
|
-
setProduct(
|
|
234
|
+
setProduct(fetched);
|
|
220
235
|
}
|
|
221
236
|
} catch (caught) {
|
|
222
237
|
if (!cancelled) {
|
package/hooks/use-shop-cart.ts
CHANGED
|
@@ -2,19 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
import { useMemo } from 'react';
|
|
4
4
|
import { useCartStore } from '../stores/cart-store';
|
|
5
|
+
import { resolveCartPricing, type CartServerPricing } from '../utils/cart-pricing';
|
|
6
|
+
import { useCartServerPricing } from './use-cart-server-pricing';
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* The cart lines for one shop, with the unit count and the total (in the
|
|
8
10
|
* currency's major unit, before delivery and discounts). Pass the shop id from
|
|
9
11
|
* `product.shop_id`; a missing id gives an empty cart.
|
|
10
12
|
*
|
|
13
|
+
* `total` is always the list total (`unit_price x quantity`). `pricing` is what
|
|
14
|
+
* the server charges for these exact lines (quantity breaks and spend gates
|
|
15
|
+
* included) when the host app provided it and it covers the lines on screen,
|
|
16
|
+
* else `null`; when it is not `null`, print its amounts (decimal strings; format
|
|
17
|
+
* them with `formatWireMoney`) instead of the list prices, and never compute a
|
|
18
|
+
* discount yourself.
|
|
19
|
+
*
|
|
11
20
|
* @example
|
|
12
|
-
* const { items, count, total } = useShopCart(product.shop_id);
|
|
21
|
+
* const { items, count, total, pricing } = useShopCart(product.shop_id);
|
|
13
22
|
*/
|
|
14
23
|
export function useShopCart(shopId: string | null | undefined): {
|
|
15
24
|
items: ReturnType<typeof useCartStore.getState>['items'];
|
|
16
25
|
count: number;
|
|
17
26
|
total: number;
|
|
27
|
+
/** The server's pricing for exactly these lines, or `null` (print list prices). */
|
|
28
|
+
pricing: CartServerPricing | null;
|
|
18
29
|
setQuantity: ReturnType<typeof useCartStore.getState>['setQuantity'];
|
|
19
30
|
removeItem: ReturnType<typeof useCartStore.getState>['removeItem'];
|
|
20
31
|
clearShopCart: ReturnType<typeof useCartStore.getState>['clearShopCart'];
|
|
@@ -25,6 +36,8 @@ export function useShopCart(shopId: string | null | undefined): {
|
|
|
25
36
|
() => allItems.filter((entry) => entry.shop_id === resolvedShopId),
|
|
26
37
|
[allItems, resolvedShopId],
|
|
27
38
|
);
|
|
39
|
+
const provided = useCartServerPricing();
|
|
40
|
+
const pricing = useMemo(() => resolveCartPricing(provided, items), [provided, items]);
|
|
28
41
|
const count = items.reduce((sum, entry) => sum + entry.quantity, 0);
|
|
29
42
|
const total = items.reduce((sum, entry) => sum + entry.unit_price * entry.quantity, 0);
|
|
30
43
|
|
|
@@ -32,6 +45,7 @@ export function useShopCart(shopId: string | null | undefined): {
|
|
|
32
45
|
items,
|
|
33
46
|
count,
|
|
34
47
|
total,
|
|
48
|
+
pricing,
|
|
35
49
|
setQuantity: useCartStore((state) => state.setQuantity),
|
|
36
50
|
removeItem: useCartStore((state) => state.removeItem),
|
|
37
51
|
clearShopCart: useCartStore((state) => state.clearShopCart),
|
package/index.ts
CHANGED
|
@@ -29,6 +29,7 @@ export * from './types/theme';
|
|
|
29
29
|
export * from './types/block';
|
|
30
30
|
export * from './types/product';
|
|
31
31
|
export * from './types/cart';
|
|
32
|
+
export * from './types/app-block';
|
|
32
33
|
export * from './types/order';
|
|
33
34
|
export * from './types/page';
|
|
34
35
|
export * from './types/menu';
|
|
@@ -43,6 +44,7 @@ export * from './utils/benefit-icon';
|
|
|
43
44
|
export * from './utils/video-embed';
|
|
44
45
|
export * from './utils/match-variant';
|
|
45
46
|
export * from './utils/line-properties';
|
|
47
|
+
export * from './utils/cart-pricing';
|
|
46
48
|
export * from './utils/announcement';
|
|
47
49
|
export * from './utils/locale';
|
|
48
50
|
export * from './utils/locale-switch';
|
package/locales/en.default.json
CHANGED
package/package.json
CHANGED
package/stores/cart-store.ts
CHANGED
|
@@ -5,13 +5,21 @@ import { createJSONStorage, persist } from 'zustand/middleware';
|
|
|
5
5
|
import type { CartAddon, CartItem } from '../types/cart';
|
|
6
6
|
import type { Product, ProductVariant } from '../types/product';
|
|
7
7
|
import { toast } from './toast-store';
|
|
8
|
-
import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY } from '../utils/format';
|
|
9
|
-
import {
|
|
8
|
+
import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY, roundAmount } from '../utils/format';
|
|
9
|
+
import { trackStorefrontEvent } from '../apps/storefront-events';
|
|
10
10
|
import { getActivePlatform, platformScopedStorage } from '../sdk/platform';
|
|
11
11
|
import { productRequiresVariant } from '../utils/match-variant';
|
|
12
12
|
import { readLineText } from './line-text-store';
|
|
13
13
|
import { isBlankText } from '../utils/blank-text';
|
|
14
14
|
|
|
15
|
+
/** What `addItemWithAddons` did: `added` wrote or merged a line, anything else wrote nothing. */
|
|
16
|
+
export type CartAddResult = 'added' | 'variant_required' | 'text_required';
|
|
17
|
+
|
|
18
|
+
/** Options of `addItemWithAddons`. `silent` suppresses its toasts so a caller adding several lines can announce once. */
|
|
19
|
+
export interface AddItemOptions {
|
|
20
|
+
silent?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
15
23
|
interface CartState {
|
|
16
24
|
items: CartItem[];
|
|
17
25
|
/** Set once per vendor mount by the storefront host. The store has no
|
|
@@ -22,7 +30,13 @@ interface CartState {
|
|
|
22
30
|
currency: string;
|
|
23
31
|
setCurrency: (currency: string) => void;
|
|
24
32
|
addProduct: (product: Product, quantity?: number, variant?: ProductVariant | null) => void;
|
|
25
|
-
addItemWithAddons: (
|
|
33
|
+
addItemWithAddons: (
|
|
34
|
+
product: Product,
|
|
35
|
+
quantity: number,
|
|
36
|
+
addons: CartAddon[],
|
|
37
|
+
variant?: ProductVariant | null,
|
|
38
|
+
options?: AddItemOptions,
|
|
39
|
+
) => CartAddResult;
|
|
26
40
|
removeItem: (id: string, shopId: string) => void;
|
|
27
41
|
setQuantity: (id: string, shopId: string, quantity: number) => void;
|
|
28
42
|
clearShopCart: (shopId: string) => void;
|
|
@@ -107,19 +121,21 @@ export const useCartStore = create<CartState>()(
|
|
|
107
121
|
addProduct: (product, quantity = 1, variant = null) => {
|
|
108
122
|
get().addItemWithAddons(product, quantity, [], variant);
|
|
109
123
|
},
|
|
110
|
-
addItemWithAddons: (product, quantity = 1, addons = [], variant = null) => {
|
|
124
|
+
addItemWithAddons: (product, quantity = 1, addons = [], variant = null, options = {}) => {
|
|
111
125
|
// A variant-enabled product has no valid "no selection" line: the cart
|
|
112
126
|
// save fails server-side, so persisting one only moves the failure to
|
|
113
127
|
// checkout. Themes gate
|
|
114
128
|
// their add button too, but a theme is presentation — correctness
|
|
115
129
|
// cannot depend on every theme getting it right.
|
|
116
130
|
if (!variant && productRequiresVariant(product)) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
131
|
+
if (!options.silent) {
|
|
132
|
+
toast({
|
|
133
|
+
title: 'Select options',
|
|
134
|
+
description: `Choose an option for ${product.title} before adding it to your cart.`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
121
137
|
console.error('[cart] refused a variant-enabled product added with no variant:', product.id);
|
|
122
|
-
return;
|
|
138
|
+
return 'variant_required';
|
|
123
139
|
}
|
|
124
140
|
|
|
125
141
|
// Text an app asked for on this product. A product with nothing
|
|
@@ -129,9 +145,11 @@ export const useCartStore = create<CartState>()(
|
|
|
129
145
|
if (lineText.missingRequired.length > 0) {
|
|
130
146
|
const missing = lineText.missingRequired[0];
|
|
131
147
|
|
|
132
|
-
|
|
148
|
+
if (!options.silent) {
|
|
149
|
+
toast({ title: `Add your ${missing.label} before adding to cart` });
|
|
150
|
+
}
|
|
133
151
|
console.error('[cart] refused a product added without its required line text:', product.id, missing.key);
|
|
134
|
-
return;
|
|
152
|
+
return 'text_required';
|
|
135
153
|
}
|
|
136
154
|
|
|
137
155
|
const hasLineText = Object.keys(lineText.properties).length > 0;
|
|
@@ -146,7 +164,7 @@ export const useCartStore = create<CartState>()(
|
|
|
146
164
|
// except on QR, which has its own persistent cart bar (QrCartBar)
|
|
147
165
|
// always visible on screen, so a toast on top of it is redundant
|
|
148
166
|
// (and its "View cart" action has nothing QR-specific to open).
|
|
149
|
-
if (getActivePlatform() !== 'instore_qr') {
|
|
167
|
+
if (getActivePlatform() !== 'instore_qr' && !options.silent) {
|
|
150
168
|
toast({
|
|
151
169
|
title: 'Added to cart',
|
|
152
170
|
description: variant?.title ? `${product.title} (${variant.title})` : product.title,
|
|
@@ -154,10 +172,7 @@ export const useCartStore = create<CartState>()(
|
|
|
154
172
|
showCart: true,
|
|
155
173
|
});
|
|
156
174
|
}
|
|
157
|
-
|
|
158
|
-
{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: Math.max(1, quantity) },
|
|
159
|
-
get().currency,
|
|
160
|
-
);
|
|
175
|
+
const addedQuantity = Math.max(1, quantity);
|
|
161
176
|
|
|
162
177
|
set((state) => {
|
|
163
178
|
const existing = state.items.findIndex(
|
|
@@ -196,6 +211,14 @@ export const useCartStore = create<CartState>()(
|
|
|
196
211
|
],
|
|
197
212
|
};
|
|
198
213
|
});
|
|
214
|
+
|
|
215
|
+
trackStorefrontEvent('product_added_to_cart', {
|
|
216
|
+
currency: get().currency,
|
|
217
|
+
value: roundAmount(unitPrice * addedQuantity),
|
|
218
|
+
items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
return 'added';
|
|
199
222
|
},
|
|
200
223
|
removeItem: (id, shopId) => {
|
|
201
224
|
set((state) => ({
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The add-to-cart app block: what the storefront reads for it and what adding
|
|
3
|
+
* its lines to the cart reports back. Pure types, importable from anywhere.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One line of the add-to-cart read
|
|
8
|
+
* (`GET v1/client/apps/{slug}/{path}?target=add-to-cart&block={key}`), already
|
|
9
|
+
* vetted and resolved by the platform. A line names a product, a quantity and
|
|
10
|
+
* nothing else that matters here: it never carries a price.
|
|
11
|
+
*/
|
|
12
|
+
export interface AppBlockLine {
|
|
13
|
+
/** The product's `p_id`. */
|
|
14
|
+
product: number;
|
|
15
|
+
slug: string;
|
|
16
|
+
/** The product's id, the one the cart stores. */
|
|
17
|
+
product_id: string;
|
|
18
|
+
/** Units, a whole number from 1 to 20. */
|
|
19
|
+
quantity: number;
|
|
20
|
+
/** The variant's `p_id`; present only for a variant product. */
|
|
21
|
+
variant?: number;
|
|
22
|
+
/** The variant's id, the one the cart stores. */
|
|
23
|
+
variant_id?: string;
|
|
24
|
+
/** App-namespaced text for the line. The kit does not put it on the cart line (see `useAddAppBlockLines`). */
|
|
25
|
+
properties?: Record<string, string>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A line the platform left out of the read, with why (`reason` is a stable code, not shopper text). */
|
|
29
|
+
export interface AppBlockSkippedLine {
|
|
30
|
+
index: number;
|
|
31
|
+
reason: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The answer of the add-to-cart read. */
|
|
35
|
+
export interface AppBlockAddToCartRead {
|
|
36
|
+
lines: AppBlockLine[];
|
|
37
|
+
skipped: AppBlockSkippedLine[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What happened to one line.
|
|
42
|
+
*
|
|
43
|
+
* - `added`: the line is on the cart (or its quantity grew).
|
|
44
|
+
* - `customise`: nothing added; the shopper must choose first (any required add-on
|
|
45
|
+
* group, pack groups included, or a required line text field).
|
|
46
|
+
* - `variant_required`: nothing added; a variant product with no variant on the line.
|
|
47
|
+
* - `unavailable`: nothing added; the product or variant is gone, inactive, out of
|
|
48
|
+
* stock (`in_stock` false; the quantity is never checked, checkout enforces stock),
|
|
49
|
+
* from another store, or not the product the line named.
|
|
50
|
+
* - `failed`: nothing added; the product could not be read (network or server
|
|
51
|
+
* error) or the line is malformed. Trying again can help.
|
|
52
|
+
* - `over_limit`: nothing added; the line is past the 20th of the press.
|
|
53
|
+
*/
|
|
54
|
+
export type AppBlockLineStatus = 'added' | 'customise' | 'variant_required' | 'unavailable' | 'failed' | 'over_limit';
|
|
55
|
+
|
|
56
|
+
export interface AppBlockLineOutcome {
|
|
57
|
+
/** Position of the line in the array given to `addLines`. */
|
|
58
|
+
index: number;
|
|
59
|
+
status: AppBlockLineStatus;
|
|
60
|
+
product_id: string;
|
|
61
|
+
variant_id: string | null;
|
|
62
|
+
/** The product's title when it was read, for naming the line in a notice; else `null`. */
|
|
63
|
+
title: string | null;
|
|
64
|
+
/** True when the line carried `properties`, which the kit never writes to the cart. */
|
|
65
|
+
properties_dropped?: true;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The result of one press. */
|
|
69
|
+
export interface AddAppBlockLinesResult {
|
|
70
|
+
/** Lines added to the cart (not units). */
|
|
71
|
+
added: number;
|
|
72
|
+
/** One entry per given line, in order. */
|
|
73
|
+
outcomes: AppBlockLineOutcome[];
|
|
74
|
+
/**
|
|
75
|
+
* True only when there is at least one line and every one was `added`. Say
|
|
76
|
+
* "added" to the shopper only when this is true; otherwise name what was not
|
|
77
|
+
* added from `outcomes`.
|
|
78
|
+
*/
|
|
79
|
+
complete: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* True when a line that was added carried `properties` the kit did not write
|
|
82
|
+
* to the cart (it writes none in this version). A renderer whose app relies on
|
|
83
|
+
* them should say so instead of reporting a plain success.
|
|
84
|
+
*/
|
|
85
|
+
propertiesDropped: boolean;
|
|
86
|
+
}
|
package/types/vendor.ts
CHANGED
|
@@ -225,7 +225,13 @@ export interface StorefrontConfig {
|
|
|
225
225
|
}>;
|
|
226
226
|
apps?: {
|
|
227
227
|
whatsapp_chat?: { enabled?: boolean; number?: string; message?: string; position?: string; bottom_offset?: number };
|
|
228
|
-
analytics?: {
|
|
228
|
+
analytics?: {
|
|
229
|
+
enabled?: boolean;
|
|
230
|
+
ga_id?: string;
|
|
231
|
+
meta_pixel_id?: string;
|
|
232
|
+
tiktok_pixel_id?: string;
|
|
233
|
+
pinterest_tag_id?: string;
|
|
234
|
+
};
|
|
229
235
|
follow_card?: { enabled?: boolean; display?: 'floating' | 'footer' | 'block'; position?: string };
|
|
230
236
|
subscribe?: {
|
|
231
237
|
enabled?: boolean;
|