@usequeek/theme-kit 0.1.29 → 0.1.31
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/client.ts +4 -0
- package/components/cart/cart-panel-controller.tsx +9 -4
- package/components/cart/default-cart-shell.tsx +68 -7
- package/components/market-switcher.tsx +82 -0
- package/hooks/use-add-app-block-lines.ts +258 -0
- package/hooks/use-cart-server-pricing.tsx +33 -0
- package/hooks/use-markets.ts +55 -0
- package/hooks/use-products.ts +20 -5
- package/hooks/use-shop-cart.ts +15 -1
- package/index.ts +3 -0
- package/locales/en.default.json +6 -1
- package/package.json +1 -1
- package/provider.tsx +37 -2
- package/sdk/client.ts +6 -1
- package/sdk/queek-client.ts +17 -1
- package/sdk/server-store-client.ts +45 -4
- package/stores/cart-store.ts +59 -11
- package/types/app-block.ts +86 -0
- package/types/theme.ts +7 -0
- package/utils/cart-pricing.ts +115 -0
- package/utils/format.ts +36 -0
- package/utils/market-choice.ts +38 -0
- package/utils/market.ts +189 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback, useContext, useMemo } from 'react';
|
|
4
|
+
import { StorefrontContext } from '../provider';
|
|
5
|
+
import { chooseMarket } from '../utils/market-choice';
|
|
6
|
+
import { normalizeCurrencyCode } from '../utils/format';
|
|
7
|
+
import type { StoreMarket } from '../utils/market';
|
|
8
|
+
|
|
9
|
+
export interface MarketsState {
|
|
10
|
+
/** The store's published markets. Empty on a store that sells in its own currency only. */
|
|
11
|
+
markets: StoreMarket[];
|
|
12
|
+
/** More than zero published markets: whether a market choice makes sense at all. */
|
|
13
|
+
hasMarkets: boolean;
|
|
14
|
+
/** The market the shopper chose, or null for the store's own currency. */
|
|
15
|
+
active: StoreMarket | null;
|
|
16
|
+
/** The store's own currency (ISO 4217). */
|
|
17
|
+
shopCurrency: string;
|
|
18
|
+
/** The currency prices are shown and charged in: the active market's, else the store's own. */
|
|
19
|
+
displayCurrency: string;
|
|
20
|
+
/** Chooses a market (`null` = the store's own currency) and reloads the page in it. */
|
|
21
|
+
select: (marketId: number | null) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The store's markets and the shopper's choice, for a theme that builds its own
|
|
26
|
+
* currency control. Reads what the host passed to `StorefrontProvider`; outside a
|
|
27
|
+
* provider, or on a store with no published market, it reports no markets and
|
|
28
|
+
* the store's own currency. Most themes want `MarketSwitcher` instead.
|
|
29
|
+
*/
|
|
30
|
+
export function useMarkets(): MarketsState {
|
|
31
|
+
const context = useContext(StorefrontContext);
|
|
32
|
+
const markets = context?.markets;
|
|
33
|
+
const activeMarketId = context?.activeMarketId ?? null;
|
|
34
|
+
const vendorSlug = context?.vendor.slug ?? '';
|
|
35
|
+
const vendorId = context?.vendor.id ?? '';
|
|
36
|
+
const shopCurrency = normalizeCurrencyCode(context?.vendor.currency);
|
|
37
|
+
|
|
38
|
+
const list = useMemo(() => markets ?? [], [markets]);
|
|
39
|
+
const active = useMemo(() => list.find((m) => m.id === activeMarketId) ?? null, [list, activeMarketId]);
|
|
40
|
+
const select = useCallback((marketId: number | null) => chooseMarket(vendorSlug, vendorId, marketId), [vendorSlug, vendorId]);
|
|
41
|
+
|
|
42
|
+
return useMemo(
|
|
43
|
+
() => ({ markets: list, hasMarkets: list.length > 0, active, shopCurrency, displayCurrency: active?.currency ?? shopCurrency, select }),
|
|
44
|
+
[list, active, shopCurrency, select],
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The ISO currency code store-wide amounts (cart totals, delivery, checkout) are
|
|
50
|
+
* shown in: the shopper's market currency, else the store's own. A product price
|
|
51
|
+
* reads its own `currency`, which the API already answers in the market currency.
|
|
52
|
+
*/
|
|
53
|
+
export function useDisplayCurrency(): string {
|
|
54
|
+
return useMarkets().displayCurrency;
|
|
55
|
+
}
|
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,9 +44,11 @@ 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';
|
|
51
|
+
export * from './utils/market';
|
|
49
52
|
|
|
50
53
|
// Theme strings — the pure/server-safe i18n core (no next/*, no React).
|
|
51
54
|
export * from './strings/theme-strings';
|
package/locales/en.default.json
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"each": "{price} each",
|
|
10
10
|
"decrease": "Decrease {title}",
|
|
11
11
|
"increase": "Increase {title}",
|
|
12
|
-
"remove": "Remove {title}"
|
|
12
|
+
"remove": "Remove {title}",
|
|
13
|
+
"discounted": "Was {original}, now {price}"
|
|
13
14
|
},
|
|
14
15
|
"related": {
|
|
15
16
|
"title": "You may also like",
|
|
@@ -180,5 +181,9 @@
|
|
|
180
181
|
"embed": {
|
|
181
182
|
"placeholder": "Paste the link or embed code of the content you want to show",
|
|
182
183
|
"title": "Embedded content"
|
|
184
|
+
},
|
|
185
|
+
"market": {
|
|
186
|
+
"label": "Currency",
|
|
187
|
+
"named": "Currency: {name}"
|
|
183
188
|
}
|
|
184
189
|
}
|
package/package.json
CHANGED
package/provider.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import type { JSX } from 'react';
|
|
4
|
-
import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react';
|
|
4
|
+
import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from 'react';
|
|
5
5
|
import type { Menu } from './types/menu';
|
|
6
6
|
import type { ReviewItem } from './types/block';
|
|
7
7
|
import type { Post } from './types/page';
|
|
@@ -10,6 +10,8 @@ import type { StorefrontConfig, VendorProfile } from './types/vendor';
|
|
|
10
10
|
import { getBrandCssVariables } from './utils/brand';
|
|
11
11
|
import { parseLocaleCode } from './utils/locale';
|
|
12
12
|
import { normalizeStoreLocales, type StoreLocale, type StoreLocaleInput } from './utils/locale-switch';
|
|
13
|
+
import { normalizeStoreMarkets, parseMarketId, setBrowserMarketId, type StoreMarket } from './utils/market';
|
|
14
|
+
import { reconcileMarketChoice } from './utils/market-choice';
|
|
13
15
|
import {
|
|
14
16
|
defaultThemeStrings,
|
|
15
17
|
t as translateThemeStrings,
|
|
@@ -59,6 +61,10 @@ interface StorefrontContextValue {
|
|
|
59
61
|
* `LanguageSwitcher` renders nothing. Optional so hand-built context values
|
|
60
62
|
* keep compiling without it. */
|
|
61
63
|
locales?: StoreLocale[];
|
|
64
|
+
/** The store's published markets (empty or omitted = the store sells in its own currency only: no picker, no `?market`). */
|
|
65
|
+
markets?: StoreMarket[];
|
|
66
|
+
/** The market the shopper chose, only when it is one of `markets`; null = the store's own currency. */
|
|
67
|
+
activeMarketId?: number | null;
|
|
62
68
|
}
|
|
63
69
|
|
|
64
70
|
/** The context behind {@link StorefrontProvider}. Read it through the hooks; use it directly only to test for a provider without throwing. */
|
|
@@ -88,6 +94,8 @@ export function StorefrontProvider({
|
|
|
88
94
|
locale,
|
|
89
95
|
strings,
|
|
90
96
|
locales,
|
|
97
|
+
markets,
|
|
98
|
+
market,
|
|
91
99
|
children,
|
|
92
100
|
}: {
|
|
93
101
|
vendor: VendorProfile;
|
|
@@ -122,6 +130,19 @@ export function StorefrontProvider({
|
|
|
122
130
|
* owns it, like `basePath`.
|
|
123
131
|
*/
|
|
124
132
|
locales?: readonly StoreLocaleInput[] | null;
|
|
133
|
+
/**
|
|
134
|
+
* The store's published markets, as `GET /client/store/markets` lists them,
|
|
135
|
+
* resolved by the host. Optional — absent or empty means no market choice:
|
|
136
|
+
* `MarketSwitcher` renders nothing and every request stays as before. Themes
|
|
137
|
+
* never set this; the host owns it.
|
|
138
|
+
*/
|
|
139
|
+
markets?: readonly unknown[] | null;
|
|
140
|
+
/**
|
|
141
|
+
* The market id the shopper chose (the host reads it from the store's market
|
|
142
|
+
* cookie). Honoured only when it names one of `markets`; anything else is the
|
|
143
|
+
* store's own currency.
|
|
144
|
+
*/
|
|
145
|
+
market?: number | string | null;
|
|
125
146
|
children: ReactNode;
|
|
126
147
|
}): JSX.Element {
|
|
127
148
|
const resolvedBasePath = basePath ?? `/${vendor.slug ?? ''}`;
|
|
@@ -136,6 +157,18 @@ export function StorefrontProvider({
|
|
|
136
157
|
[strings],
|
|
137
158
|
);
|
|
138
159
|
const resolvedLocales = useMemo(() => normalizeStoreLocales(locales), [locales]);
|
|
160
|
+
const resolvedMarkets = useMemo(() => normalizeStoreMarkets(markets), [markets]);
|
|
161
|
+
const marketsKnown = Array.isArray(markets);
|
|
162
|
+
const requestedMarket = parseMarketId(market);
|
|
163
|
+
const activeMarketId = resolvedMarkets.some((m) => m.id === requestedMarket) ? requestedMarket : null;
|
|
164
|
+
// Browser transports read the market per request. Idempotent and a no-op on the server.
|
|
165
|
+
setBrowserMarketId(activeMarketId);
|
|
166
|
+
const vendorSlug = vendor.slug ?? '';
|
|
167
|
+
const vendorId = vendor.id;
|
|
168
|
+
useEffect(() => {
|
|
169
|
+
// A cookie naming a market the store no longer publishes: drop it (and the lines priced under it) once.
|
|
170
|
+
reconcileMarketChoice(vendorSlug, vendorId, marketsKnown ? resolvedMarkets : null);
|
|
171
|
+
}, [vendorSlug, vendorId, resolvedMarkets, marketsKnown]);
|
|
139
172
|
const value = useMemo(
|
|
140
173
|
() => ({
|
|
141
174
|
vendor,
|
|
@@ -147,8 +180,10 @@ export function StorefrontProvider({
|
|
|
147
180
|
locale: resolvedLocale,
|
|
148
181
|
strings: resolvedStrings,
|
|
149
182
|
locales: resolvedLocales,
|
|
183
|
+
markets: resolvedMarkets,
|
|
184
|
+
activeMarketId,
|
|
150
185
|
}),
|
|
151
|
-
[config, menus, previewData, vendor, resolvedBasePath, pagesChrome, resolvedLocale, resolvedStrings, resolvedLocales],
|
|
186
|
+
[config, menus, previewData, vendor, resolvedBasePath, pagesChrome, resolvedLocale, resolvedStrings, resolvedLocales, resolvedMarkets, activeMarketId],
|
|
152
187
|
);
|
|
153
188
|
const brandRootRef = useRef<HTMLDivElement>(null);
|
|
154
189
|
|
package/sdk/client.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getActivePlatform } from './platform';
|
|
2
|
+
import { getBrowserMarketId, isMarketPricedPath, withMarketQuery } from '../utils/market';
|
|
2
3
|
|
|
3
4
|
const LOCAL_API_URL = 'http://127.0.0.1:8000/api/v1';
|
|
4
5
|
const API_URL_FROM_ENV = process.env.QUEEK_API_URL ?? process.env.NEXT_PUBLIC_QUEEK_API_URL;
|
|
@@ -356,12 +357,16 @@ export function createBrowserClient(vendorSlug?: string, token?: string): {
|
|
|
356
357
|
return headers;
|
|
357
358
|
};
|
|
358
359
|
|
|
360
|
+
// The shopper's market, on priced paths only; no market leaves the query untouched.
|
|
361
|
+
const marketFor = (path: string): number | null => (isMarketPricedPath(path) ? getBrowserMarketId() : null);
|
|
362
|
+
|
|
359
363
|
return {
|
|
360
364
|
get: <T>(path: string, query?: RequestOptions['query']) =>
|
|
361
|
-
request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, { query, timeoutMs: BROWSER_GET_TIMEOUT_MS }, buildHeaders()),
|
|
365
|
+
request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, { query: withMarketQuery(query, marketFor(path)), timeoutMs: BROWSER_GET_TIMEOUT_MS }, buildHeaders()),
|
|
362
366
|
post: <T>(path: string, body?: unknown) =>
|
|
363
367
|
request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, {
|
|
364
368
|
method: 'POST',
|
|
369
|
+
query: withMarketQuery(undefined, marketFor(path)),
|
|
365
370
|
body: body ? JSON.stringify(body) : undefined,
|
|
366
371
|
timeoutMs: BROWSER_POST_TIMEOUT_MS,
|
|
367
372
|
}, buildHeaders()),
|
package/sdk/queek-client.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { createQueekClient, type QueekClientInstance, type StorageAdapter } from '@usequeek/client-sdk';
|
|
4
4
|
import { triggerReauth } from './error-handler';
|
|
5
5
|
import { getActivePlatform } from './platform';
|
|
6
|
+
import { getBrowserMarketId, isMarketPricedPath, withMarketPath } from '../utils/market';
|
|
6
7
|
|
|
7
8
|
// This file is 'use client' — every export here only ever runs in the browser.
|
|
8
9
|
// ALWAYS same-origin-relative, on purpose: the host app's `next.config` rewrite
|
|
@@ -35,7 +36,8 @@ const localStorageAdapter: StorageAdapter = {
|
|
|
35
36
|
* the rest of the site stays `storefront`. Reads the holder per request, so a
|
|
36
37
|
* single cached client serves both platforms.
|
|
37
38
|
*/
|
|
38
|
-
const platformFetch: typeof fetch = (
|
|
39
|
+
const platformFetch: typeof fetch = (rawInput, init) => {
|
|
40
|
+
const input = withActiveMarket(rawInput);
|
|
39
41
|
if (init?.headers) {
|
|
40
42
|
const headers = new Headers(init.headers);
|
|
41
43
|
headers.set('X-Platform', getActivePlatform());
|
|
@@ -44,6 +46,20 @@ const platformFetch: typeof fetch = (input, init) => {
|
|
|
44
46
|
return fetch(input, init).then(captureRequestId);
|
|
45
47
|
};
|
|
46
48
|
|
|
49
|
+
/**
|
|
50
|
+
* The shopper's market rides every priced store call as `?market=<id>` (reads,
|
|
51
|
+
* cart writes, the quote and the order): the one place the SDK-backed client
|
|
52
|
+
* learns it, so no caller can forget it. No market chosen: the URL is untouched.
|
|
53
|
+
* The SDK always hands `fetch` a string URL; anything else passes through.
|
|
54
|
+
*/
|
|
55
|
+
function withActiveMarket(input: RequestInfo | URL): RequestInfo | URL {
|
|
56
|
+
const marketId = getBrowserMarketId();
|
|
57
|
+
if (marketId === null || typeof input !== 'string' || !input.includes('/client/store/') || !isMarketPricedPath(input)) {
|
|
58
|
+
return input;
|
|
59
|
+
}
|
|
60
|
+
return withMarketPath(input, marketId);
|
|
61
|
+
}
|
|
62
|
+
|
|
47
63
|
/**
|
|
48
64
|
* Every API response carries a request id. The SDK's `request()` returns only
|
|
49
65
|
* the parsed body, so this wrapper — the one place every SDK call's raw Response
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { headers } from 'next/headers';
|
|
1
|
+
import { cookies, headers } from 'next/headers';
|
|
2
2
|
import { resolveCustomDomainVendorSlug, resolveCustomDomainVendorSlugRemote, resolveSubdomainVendorSlug } from '../utils/vendor-host';
|
|
3
3
|
import { LOCALE_CODE_HEADER, parseLocaleCode, withLocaleQuery, withLocaleTags } from '../utils/locale';
|
|
4
|
+
import { isMarketPricedPath, readMarketFromCookieString, withMarketQuery } from '../utils/market';
|
|
4
5
|
import { API_BASE_URL, request, type RequestCachePolicy, type RequestOptions } from './client';
|
|
5
6
|
import { getActivePlatform } from './platform';
|
|
6
7
|
|
|
@@ -190,7 +191,43 @@ export function withLocaleCachePolicy(
|
|
|
190
191
|
return { revalidate: policy.revalidate, tags: withLocaleTags(policy.tags, locale) };
|
|
191
192
|
}
|
|
192
193
|
|
|
193
|
-
|
|
194
|
+
/**
|
|
195
|
+
* The market the shopper chose for this store (its cookie), for a server read.
|
|
196
|
+
* Never throws: outside a request scope there is no cookie, which reads as the
|
|
197
|
+
* store's own currency. `verify` (see {@link ServerStoreClientOptions}) lets the
|
|
198
|
+
* host confirm the id against the store's market list; without it only the id's
|
|
199
|
+
* shape is checked and the API answers in the store's currency for an id it does
|
|
200
|
+
* not offer, so a stale cookie can never price anything wrongly.
|
|
201
|
+
*/
|
|
202
|
+
export async function readRequestMarket(vendorSlug: string, verify?: (marketId: number) => Promise<boolean>): Promise<number | null> {
|
|
203
|
+
let marketId: number | null;
|
|
204
|
+
try {
|
|
205
|
+
marketId = readMarketFromCookieString((await cookies()).toString(), vendorSlug);
|
|
206
|
+
} catch {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (marketId === null || !verify) return marketId;
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
return (await verify(marketId)) ? marketId : null;
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Options of {@link createServerStoreClient}. */
|
|
220
|
+
export interface ServerStoreClientOptions {
|
|
221
|
+
/**
|
|
222
|
+
* Decides, per request, whether the shopper's market cookie names a market the store really offers. A host that
|
|
223
|
+
* reads the store's market list passes it, so the server prices in a market only when the page and the browser
|
|
224
|
+
* will: a cookie the host cannot confirm (an unpublished market, a failed list read) reads as the store currency.
|
|
225
|
+
* Omitted: the cookie's shape is all that is checked and the API answers in the store currency for an unknown id.
|
|
226
|
+
*/
|
|
227
|
+
verifyMarket?: (marketId: number) => Promise<boolean>;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function createServerStoreClient(vendorSlug: string, origin?: string, options: ServerStoreClientOptions = {}): {
|
|
194
231
|
get: <T>(path: string, query?: RequestOptions['query'], locale?: string) => Promise<T>;
|
|
195
232
|
post: <T>(path: string, body?: unknown) => Promise<T>;
|
|
196
233
|
} {
|
|
@@ -211,13 +248,17 @@ export function createServerStoreClient(vendorSlug: string, origin?: string): {
|
|
|
211
248
|
// suffix on every cache tag).
|
|
212
249
|
get: async <T>(path: string, query?: RequestOptions['query'], locale?: string) => {
|
|
213
250
|
const code = await resolveRequestLocale(locale);
|
|
251
|
+
// A shopper in a market gets prices in its currency: `?market=<id>` on the priced reads, and those reads
|
|
252
|
+
// leave the shared data cache. The cache is shared by every visitor, its key is the URL, and a rate moves
|
|
253
|
+
// without any revalidation tag, so a market price is never stored there. No market: today's request.
|
|
254
|
+
const marketId = isMarketPricedPath(path) ? await readRequestMarket(vendorSlug, options.verifyMarket) : null;
|
|
214
255
|
return request<T>(
|
|
215
256
|
API_BASE_URL,
|
|
216
257
|
`/client/store${path}`,
|
|
217
258
|
{
|
|
218
|
-
query: withLocaleQuery(query, code),
|
|
259
|
+
query: withMarketQuery(withLocaleQuery(query, code), marketId),
|
|
219
260
|
timeoutMs: SSR_TIMEOUT_MS,
|
|
220
|
-
cachePolicy: (await isPreviewRender())
|
|
261
|
+
cachePolicy: marketId !== null || (await isPreviewRender())
|
|
221
262
|
? null
|
|
222
263
|
: withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
|
|
223
264
|
},
|
package/stores/cart-store.ts
CHANGED
|
@@ -12,6 +12,14 @@ 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;
|
|
@@ -93,6 +107,34 @@ function propertiesSuffix(properties?: Record<string, unknown> | null): string {
|
|
|
93
107
|
return `~p-${(fnv1a(json, 0x811c9dc5) + fnv1a(json, 0x9e3779b9)).slice(0, 12)}`;
|
|
94
108
|
}
|
|
95
109
|
|
|
110
|
+
const CART_STORAGE_NAME = 'queek-storefront-cart';
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Removes one shop's lines from the PERSISTED cart without touching the live
|
|
114
|
+
* store, for a page that is about to reload. A shopper who changes market gets
|
|
115
|
+
* every price in another currency, and a line keeps the unit price it was added
|
|
116
|
+
* at, so it must not survive into the new currency; the server cart still holds
|
|
117
|
+
* the lines and the reload adopts them re-priced. Changing the live store here
|
|
118
|
+
* would make the cart sync delete that server copy, so this writes storage only.
|
|
119
|
+
*/
|
|
120
|
+
export function dropPersistedShopLines(shopId: string): void {
|
|
121
|
+
const storage = platformScopedStorage();
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
const raw = storage.getItem(CART_STORAGE_NAME);
|
|
125
|
+
if (!raw) return;
|
|
126
|
+
|
|
127
|
+
const persisted = JSON.parse(raw) as { state?: { items?: CartItem[] } };
|
|
128
|
+
if (!Array.isArray(persisted.state?.items)) return;
|
|
129
|
+
|
|
130
|
+
persisted.state.items = persisted.state.items.filter((entry) => entry.shop_id !== shopId);
|
|
131
|
+
storage.setItem(CART_STORAGE_NAME, JSON.stringify(persisted));
|
|
132
|
+
} catch {
|
|
133
|
+
// Unreadable storage holds nothing worth keeping; the reload starts from the server cart.
|
|
134
|
+
storage.removeItem(CART_STORAGE_NAME);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
96
138
|
/**
|
|
97
139
|
* The cart store. Prefer the `useCart()` and `useShopCart()` hooks; read this
|
|
98
140
|
* directly only from non-React code (`useCartStore.getState()`). Lines persist
|
|
@@ -107,19 +149,21 @@ export const useCartStore = create<CartState>()(
|
|
|
107
149
|
addProduct: (product, quantity = 1, variant = null) => {
|
|
108
150
|
get().addItemWithAddons(product, quantity, [], variant);
|
|
109
151
|
},
|
|
110
|
-
addItemWithAddons: (product, quantity = 1, addons = [], variant = null) => {
|
|
152
|
+
addItemWithAddons: (product, quantity = 1, addons = [], variant = null, options = {}) => {
|
|
111
153
|
// A variant-enabled product has no valid "no selection" line: the cart
|
|
112
154
|
// save fails server-side, so persisting one only moves the failure to
|
|
113
155
|
// checkout. Themes gate
|
|
114
156
|
// their add button too, but a theme is presentation — correctness
|
|
115
157
|
// cannot depend on every theme getting it right.
|
|
116
158
|
if (!variant && productRequiresVariant(product)) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
159
|
+
if (!options.silent) {
|
|
160
|
+
toast({
|
|
161
|
+
title: 'Select options',
|
|
162
|
+
description: `Choose an option for ${product.title} before adding it to your cart.`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
121
165
|
console.error('[cart] refused a variant-enabled product added with no variant:', product.id);
|
|
122
|
-
return;
|
|
166
|
+
return 'variant_required';
|
|
123
167
|
}
|
|
124
168
|
|
|
125
169
|
// Text an app asked for on this product. A product with nothing
|
|
@@ -129,9 +173,11 @@ export const useCartStore = create<CartState>()(
|
|
|
129
173
|
if (lineText.missingRequired.length > 0) {
|
|
130
174
|
const missing = lineText.missingRequired[0];
|
|
131
175
|
|
|
132
|
-
|
|
176
|
+
if (!options.silent) {
|
|
177
|
+
toast({ title: `Add your ${missing.label} before adding to cart` });
|
|
178
|
+
}
|
|
133
179
|
console.error('[cart] refused a product added without its required line text:', product.id, missing.key);
|
|
134
|
-
return;
|
|
180
|
+
return 'text_required';
|
|
135
181
|
}
|
|
136
182
|
|
|
137
183
|
const hasLineText = Object.keys(lineText.properties).length > 0;
|
|
@@ -146,7 +192,7 @@ export const useCartStore = create<CartState>()(
|
|
|
146
192
|
// except on QR, which has its own persistent cart bar (QrCartBar)
|
|
147
193
|
// always visible on screen, so a toast on top of it is redundant
|
|
148
194
|
// (and its "View cart" action has nothing QR-specific to open).
|
|
149
|
-
if (getActivePlatform() !== 'instore_qr') {
|
|
195
|
+
if (getActivePlatform() !== 'instore_qr' && !options.silent) {
|
|
150
196
|
toast({
|
|
151
197
|
title: 'Added to cart',
|
|
152
198
|
description: variant?.title ? `${product.title} (${variant.title})` : product.title,
|
|
@@ -199,6 +245,8 @@ export const useCartStore = create<CartState>()(
|
|
|
199
245
|
value: roundAmount(unitPrice * addedQuantity),
|
|
200
246
|
items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
|
|
201
247
|
});
|
|
248
|
+
|
|
249
|
+
return 'added';
|
|
202
250
|
},
|
|
203
251
|
removeItem: (id, shopId) => {
|
|
204
252
|
set((state) => ({
|
|
@@ -234,7 +282,7 @@ export const useCartStore = create<CartState>()(
|
|
|
234
282
|
},
|
|
235
283
|
}),
|
|
236
284
|
{
|
|
237
|
-
name:
|
|
285
|
+
name: CART_STORAGE_NAME,
|
|
238
286
|
storage: createJSONStorage(platformScopedStorage),
|
|
239
287
|
},
|
|
240
288
|
),
|
|
@@ -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/theme.ts
CHANGED
|
@@ -389,6 +389,13 @@ export interface ThemeManifest {
|
|
|
389
389
|
* it keeps the storefront's control for multi-language stores.
|
|
390
390
|
*/
|
|
391
391
|
languageSwitcher?: 'theme';
|
|
392
|
+
/**
|
|
393
|
+
* Set to `'theme'` when the theme places the kit's `MarketSwitcher` itself.
|
|
394
|
+
* The storefront then does not also render its own floating market control.
|
|
395
|
+
* Optional — a manifest without it keeps the storefront's control, which
|
|
396
|
+
* shows only on a store with a published market.
|
|
397
|
+
*/
|
|
398
|
+
marketSwitcher?: 'theme';
|
|
392
399
|
}
|
|
393
400
|
|
|
394
401
|
/**
|