@usequeek/theme-kit 0.1.29 → 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 CHANGED
@@ -131,6 +131,7 @@ they keep the data already on screen. They return `isLoading`, except
131
131
  | `useReviews(block)` | `hooks/use-reviews` | Reviews and the rating summary |
132
132
  | `useProductQuestions(block)` | `hooks/use-product-questions` | Product questions and answers |
133
133
  | `useCart()` / `useShopCart(shopId)` | `hooks/use-cart`, `hooks/use-shop-cart` | The cart and its actions; one shop's lines and totals |
134
+ | `useAddAppBlockLines(shopId)` | `hooks/use-add-app-block-lines` | Adds the products of an add-to-cart app block: `{ addLines, pending }` |
134
135
  | `useAuth()` | `hooks/use-auth` | The signed-in customer and sign-in modal controls |
135
136
  | `useVariantSelection(product)` | `hooks/use-variant-selection` | Option selection state and the add-to-cart gate |
136
137
  | `useSearch(query, products, collections)` | `hooks/use-search` | Instant search over data you hold |
@@ -139,6 +140,87 @@ they keep the data already on screen. They return `isLoading`, except
139
140
  | `useLocales()` | `hooks/use-locales` | The store's languages and the active one |
140
141
  | `useStorefront()` / `useStorefrontLocale()` / `useThemeStrings()` | `provider` | The store, the request locale, the bound `t` |
141
142
 
143
+ ### Cart pricing
144
+
145
+ `useShopCart(shopId)` and `CartPanelController` also return `pricing`: what the
146
+ server charges for exactly the lines on screen (quantity-break and spend-gate
147
+ discounts included), or `null`. Amounts are decimal strings as the server sent
148
+ them; print them with `formatWireMoney(amount, currency)` (from
149
+ `utils/format`) and never compute a discount in a theme. When `pricing` is `null`, print `unit_price x quantity` as
150
+ before.
151
+
152
+ ```tsx
153
+ const { items, total, pricing } = useShopCart(vendor.id);
154
+
155
+ items.map((item) => {
156
+ const line = cartLinePricing(pricing, item.id); // from utils/cart-pricing
157
+ return line ? (
158
+ <Fragment key={item.id}>
159
+ {line.list_line_total ? <del>{formatWireMoney(line.list_line_total, currency)}</del> : null}
160
+ <ins>{formatWireMoney(line.line_total, currency)}</ins>
161
+ </Fragment>
162
+ ) : (
163
+ formatMoney(item.unit_price * item.quantity, currency)
164
+ );
165
+ });
166
+ ```
167
+
168
+ `formatWireMoney` hands the string to Intl at the currency's own precision, so a
169
+ zero-decimal currency prints no decimals and an amount with more digits than the
170
+ currency has is rounded by Intl; it returns an empty string for anything that is
171
+ not a plain non-negative decimal. The storefront app keeps a different
172
+ `formatWireMoney` (it accepts numbers and negatives and returns an em dash for a
173
+ missing amount); the wiring item must converge on one of them.
174
+
175
+ The host app supplies the server pricing once, above every theme, with
176
+ `<CartServerPricingProvider value={pricing}>` (`hooks/use-cart-server-pricing`).
177
+
178
+ ### Add-to-cart app blocks
179
+
180
+ An add-to-cart app block puts the products its app named into the cart with one
181
+ press. The storefront reads the block's lines (type `AppBlockAddToCartRead`, from
182
+ `types/app-block`), then calls `useAddAppBlockLines(shopId)` and prints ONE notice
183
+ from the result. No app code runs, the app never writes to the cart, and no price
184
+ is touched: each line is priced like the same product added from its page.
185
+
186
+ ```tsx
187
+ const { addLines, pending } = useAddAppBlockLines(vendor.id);
188
+
189
+ async function onPress(): Promise<void> {
190
+ const result = await addLines(read.lines);
191
+ if (result.complete) {
192
+ notify('added');
193
+ } else {
194
+ // result.outcomes: one { index, status, title, ... } per line, in order
195
+ notifyNotAdded(result.outcomes.filter((outcome) => outcome.status !== 'added'));
196
+ }
197
+ }
198
+ ```
199
+
200
+ Each line ends as `added`, `customise` (any required add-on group, pack groups
201
+ included, or required line text: the shopper must choose on the product page),
202
+ `variant_required`, `unavailable` (gone, inactive, `in_stock` false, another
203
+ store; the quantity is never compared with stock, which checkout enforces), `failed` (the
204
+ product could not be read; retry can help) or `over_limit` (past the 20th line).
205
+ A line that is not added never stops the others. Say "added" only when
206
+ `complete` is true. The statuses are what the kit can know from the product as
207
+ read; it cannot see the host's cart write, so the host keeps handling that
208
+ write's own answers.
209
+
210
+ While a press is pending, an `addLines` call with the same lines in the same
211
+ order returns the pending result and adds nothing, so a double click adds the
212
+ pack once; a different pack runs on its own (also disable the button on
213
+ `pending`). A malformed entry in `lines` is `failed`, and a throw while handling
214
+ one line never loses the outcomes of the others.
215
+
216
+ Limits: a line's `properties` are not written to the cart in this version (an app
217
+ claim or other app text never reaches the line). The outcome carries
218
+ `properties_dropped` and the result `propertiesDropped` (true when an added line
219
+ had some), so the renderer can say so. Products are read fresh on every press.
220
+ `addItemWithAddons` takes an optional fifth argument `{ silent: true }` that
221
+ suppresses its toasts, and now returns `'added' | 'variant_required' |
222
+ 'text_required'`.
223
+
142
224
  ## Errors
143
225
 
144
226
  Requests go through one place (`sdk/client.ts`). A non-2xx answer throws
package/client.ts CHANGED
@@ -36,6 +36,8 @@ export * from './hooks/use-locales';
36
36
  export * from './hooks/use-auth';
37
37
  export * from './hooks/use-cart';
38
38
  export * from './hooks/use-shop-cart';
39
+ export * from './hooks/use-add-app-block-lines';
40
+ export * from './hooks/use-cart-server-pricing';
39
41
  export * from './hooks/use-products';
40
42
  export * from './hooks/use-product-detail';
41
43
  export * from './hooks/use-product-sections';
@@ -9,12 +9,15 @@ import { useHref } from '../../hooks/use-href';
9
9
  import { useShopCart } from '../../hooks/use-shop-cart';
10
10
  import { useCartPanelStore } from '../../stores/cart-panel-store';
11
11
  import { normalizeCurrencyCode } from '../../utils/format';
12
+ import type { CartServerPricing } from '../../utils/cart-pricing';
12
13
 
13
14
  /** What {@link CartPanelController} hands to your render function: the panel state, this shop's lines, and the actions that change them. */
14
15
  export interface CartPanelControllerRenderProps {
15
16
  isOpen: boolean;
16
17
  items: CartItem[];
17
18
  total: number;
19
+ /** What the server charges for these lines (decimal strings; print them with `formatWireMoney`), or `null`/absent: print list prices. Never compute a discount. The controller always passes it; it is optional in the type so a hand-built props object (a test, a story) stays valid. */
20
+ pricing?: CartServerPricing | null;
18
21
  currency: string;
19
22
  onClose: () => void;
20
23
  onCheckout: () => void;
@@ -46,7 +49,7 @@ export function CartPanelController({
46
49
  const router = useRouter();
47
50
  const isOpen = useCartPanelStore((state) => state.isOpen);
48
51
  const closePanel = useCartPanelStore((state) => state.close);
49
- const { items, total, setQuantity, removeItem } = useShopCart(vendor.id);
52
+ const { items, total, pricing, setQuantity, removeItem } = useShopCart(vendor.id);
50
53
 
51
54
  useEffect(() => {
52
55
  if (!isOpen) return;
@@ -71,6 +74,7 @@ export function CartPanelController({
71
74
  isOpen,
72
75
  items,
73
76
  total,
77
+ pricing,
74
78
  // Store-wide display uses the vendor's currency; item rows carry their own.
75
79
  // List-level meta.currency is never read (platform default, wrong per store).
76
80
  currency: normalizeCurrencyCode(vendor.currency),
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import type { JSX } from 'react';
3
+ import type { CSSProperties, JSX } from 'react';
4
4
  import { useRef, useState } from 'react';
5
5
  import Link from 'next/link';
6
6
  import type { CartShellProps } from '../../types/theme';
@@ -9,11 +9,58 @@ import { useThemeStrings } from '../../provider';
9
9
  import { useCheckoutStore } from '../../stores/checkout-store';
10
10
  import { useRelatedProducts } from '../../hooks/use-related-products';
11
11
  import { useCart } from '../../hooks/use-cart';
12
- import { formatMoney } from '../../utils/format';
12
+ import { formatMoney, formatWireMoney } from '../../utils/format';
13
+ import { cartLinePricing, resolveCartPricing } from '../../utils/cart-pricing';
14
+ import { useCartServerPricing } from '../../hooks/use-cart-server-pricing';
13
15
  import { productRequiresVariant } from '../../utils/match-variant';
14
16
  import { visibleLineProperties } from '../../utils/line-properties';
15
17
  import { Image } from '../image';
16
18
 
19
+ /** The standard visually-hidden recipe, inline because the kit ships no CSS for the cart page. */
20
+ const VISUALLY_HIDDEN: CSSProperties = {
21
+ position: 'absolute',
22
+ width: 1,
23
+ height: 1,
24
+ margin: -1,
25
+ padding: 0,
26
+ overflow: 'hidden',
27
+ clip: 'rect(0 0 0 0)',
28
+ whiteSpace: 'nowrap',
29
+ border: 0,
30
+ };
31
+
32
+ /**
33
+ * An amount the server charges, with the list amount struck through when the
34
+ * server charges less. Both are server decimal strings printed as received.
35
+ *
36
+ * Assistive technology reads ONE visually hidden sentence ("Was X, now Y", a
37
+ * plain text node, so it is read in browse mode too) and the visible `<del>` /
38
+ * `<ins>` pair is hidden from it: a deletion's semantics are announced
39
+ * unevenly across screen readers and an `aria-label` on a generic wrapper can
40
+ * be skipped, while a text node cannot. Themes style the pair through
41
+ * `core-cart-item__was` / `core-cart-item__now`; the inline `text-decoration`
42
+ * is the fallback for a theme without those classes (it sets nothing else, so
43
+ * a theme's colour rule still applies).
44
+ */
45
+ function ChargedPrice({ amount, list, currency }: { amount: string; list: string | null; currency: string }): JSX.Element {
46
+ const t = useThemeStrings();
47
+ const charged = formatWireMoney(amount, currency);
48
+
49
+ if (list === null) {
50
+ return <>{charged}</>;
51
+ }
52
+
53
+ const original = formatWireMoney(list, currency);
54
+
55
+ return (
56
+ <>
57
+ <span style={VISUALLY_HIDDEN}>{t('cart.item.discounted', { original, price: charged })}</span>
58
+ <del className="core-cart-item__was" aria-hidden="true">{original}</del>{' '}
59
+ <ins className="core-cart-item__now" aria-hidden="true" style={{ textDecoration: 'none' }}>{charged}</ins>
60
+ </>
61
+ );
62
+ }
63
+
17
64
  /**
18
65
  * The cart page's shared, root design — every theme's shells/cart-shell.tsx
19
66
  * delegates to this (all thin passthroughs today) unless one chooses to
@@ -36,6 +83,8 @@ export function DefaultCartShell({
36
83
  const [noteOpen, setNoteOpen] = useState(false);
37
84
  const [agreed, setAgreed] = useState(false);
38
85
  const relatedRef = useRef<HTMLDivElement>(null);
86
+ // What the server charges for exactly these lines, or null: list prices, as always.
87
+ const serverPricing = resolveCartPricing(useCartServerPricing(), items);
39
88
 
40
89
  const firstSlug = items.find((item) => item.slug)?.slug ?? '';
41
90
  const { products: related } = useRelatedProducts(firstSlug, 6);
@@ -68,7 +117,10 @@ export function DefaultCartShell({
68
117
  <div className="core-cart-page__main">
69
118
  <div className="core-cart-page__items-card">
70
119
  <ul className="core-cart-page__items">
71
- {items.map((item) => (
120
+ {items.map((item) => {
121
+ const linePricing = cartLinePricing(serverPricing, item.id);
122
+
123
+ return (
72
124
  <li key={`${item.shop_id}-${item.id}`} className="core-cart-page__item">
73
125
  {item.image ? (
74
126
  <Image src={item.image} alt={item.title} className="core-cart-page__item-img" />
@@ -80,7 +132,7 @@ export function DefaultCartShell({
80
132
  {visibleLineProperties(item).map((row) => (
81
133
  <span key={row.key} className="core-cart-page__item-price">{`${row.label}: ${row.value}`}</span>
82
134
  ))}
83
- <span className="core-cart-page__item-price">{t('cart.item.each', { price: formatMoney(item.unit_price, currency) })}</span>
135
+ <span className="core-cart-page__item-price">{t('cart.item.each', { price: linePricing ? formatWireMoney(linePricing.unit_price, currency) : formatMoney(item.unit_price, currency) })}</span>
84
136
  </div>
85
137
  <div className="core-cart-page__item-qty">
86
138
  <button type="button" onClick={() => onDecrease(item.id, item.shop_id)} aria-label={t('cart.item.decrease', { title: item.title })}>
@@ -91,14 +143,19 @@ export function DefaultCartShell({
91
143
  <svg width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M6 2v8M2 6h8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
92
144
  </button>
93
145
  </div>
94
- <span className="core-cart-page__item-total">{formatMoney(item.unit_price * item.quantity, currency)}</span>
146
+ <span className="core-cart-page__item-total">
147
+ {linePricing ? (
148
+ <ChargedPrice amount={linePricing.line_total} list={linePricing.list_line_total} currency={currency} />
149
+ ) : formatMoney(item.unit_price * item.quantity, currency)}
150
+ </span>
95
151
  <button type="button" className="core-cart-page__item-remove" onClick={() => onRemove(item.id, item.shop_id)} aria-label={t('cart.item.remove', { title: item.title })}>
96
152
  <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
97
153
  <path d="M4 6h12M8 6V4.5A1.5 1.5 0 019.5 3h1A1.5 1.5 0 0112 4.5V6m-6 0v9.5A1.5 1.5 0 007.5 17h5a1.5 1.5 0 001.5-1.5V6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
98
154
  </svg>
99
155
  </button>
100
156
  </li>
101
- ))}
157
+ );
158
+ })}
102
159
  </ul>
103
160
  </div>
104
161
 
@@ -184,7 +241,11 @@ export function DefaultCartShell({
184
241
 
185
242
  <div className="core-cart-page__subtotal">
186
243
  <span>{t('cart.summary.subtotal')}</span>
187
- <strong>{formatMoney(total, currency)} {currency}</strong>
244
+ <strong>
245
+ {serverPricing ? (
246
+ <ChargedPrice amount={serverPricing.total} list={serverPricing.list_total} currency={currency} />
247
+ ) : formatMoney(total, currency)} {currency}
248
+ </strong>
188
249
  </div>
189
250
 
190
251
  <label className="core-cart-page__terms">
@@ -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
+ }
@@ -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 response = await client.get<ApiResponse<LegacyProductLike>>(`/products/${encodeURIComponent(slug as string)}`, withLocaleQuery(undefined, locale));
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(payload ? normalizeProduct(payload as LegacyProductLike) : null);
234
+ setProduct(fetched);
220
235
  }
221
236
  } catch (caught) {
222
237
  if (!cancelled) {
@@ -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';
@@ -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",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "The runtime a Queek storefront theme is built on: hooks, stores, page renderer, navigation, shared blocks and locale strings.",
@@ -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: (product: Product, quantity: number, addons: CartAddon[], variant?: ProductVariant | null) => void;
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
- toast({
118
- title: 'Select options',
119
- description: `Choose an option for ${product.title} before adding it to your cart.`,
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
- toast({ title: `Add your ${missing.label} before adding to cart` });
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,
@@ -199,6 +217,8 @@ export const useCartStore = create<CartState>()(
199
217
  value: roundAmount(unitPrice * addedQuantity),
200
218
  items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
201
219
  });
220
+
221
+ return 'added';
202
222
  },
203
223
  removeItem: (id, shopId) => {
204
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
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * What the server charges for the cart on screen, as the host app read it
3
+ * (quantity-break and spend-gate discounts included). The kit only DISPLAYS it:
4
+ * every amount is a decimal string exactly as the server sent it ("4500.00"),
5
+ * and nothing here ever computes a price, a discount or a total.
6
+ */
7
+
8
+ /** One cart line as the server prices it. Matched to a local line by `line_id` AND `quantity`. */
9
+ export interface CartLinePricing {
10
+ /** The local cart line id (`CartItem.id`). */
11
+ line_id: string;
12
+ /** The quantity the server priced; a line whose quantity differs is not covered. */
13
+ quantity: number;
14
+ /** One unit with its add-ons, as charged. */
15
+ unit_price: string;
16
+ /** The line total as charged. */
17
+ line_total: string;
18
+ /** The list (undiscounted) line total, only when the server charges less than it; otherwise null. */
19
+ list_line_total: string | null;
20
+ }
21
+
22
+ /** The server's pricing of one whole cart. */
23
+ export interface CartServerPricing {
24
+ lines: readonly CartLinePricing[];
25
+ /** The cart total as charged (before coupons and delivery). */
26
+ total: string;
27
+ /** The list (undiscounted) cart total, only when the server charges less than it; otherwise null. */
28
+ list_total: string | null;
29
+ }
30
+
31
+ const DECIMAL = /^\d+(\.\d+)?$/;
32
+
33
+ function isDecimal(value: unknown): value is string {
34
+ return typeof value === 'string' && DECIMAL.test(value);
35
+ }
36
+
37
+ /** Digit-exact `a > b` for two non-negative decimal strings (no float round trip). */
38
+ function isGreater(a: string, b: string): boolean {
39
+ const [aWhole, aFraction = ''] = a.split('.');
40
+ const [bWhole, bFraction = ''] = b.split('.');
41
+ const left = aWhole.replace(/^0+(?=\d)/, '');
42
+ const right = bWhole.replace(/^0+(?=\d)/, '');
43
+
44
+ if (left.length !== right.length) {
45
+ return left.length > right.length;
46
+ }
47
+
48
+ // Equal-width digit strings compare in numeric order; this only orders text, it computes nothing.
49
+ const width = aFraction.length > bFraction.length ? aFraction.length : bFraction.length;
50
+ const leftDigits = `${left}${aFraction.padEnd(width, '0')}`;
51
+ const rightDigits = `${right}${bFraction.padEnd(width, '0')}`;
52
+
53
+ return leftDigits > rightDigits;
54
+ }
55
+
56
+ /** A struck list amount is kept only when it is a well-formed decimal HIGHER than what is charged. */
57
+ function strikeOf(list: unknown, charged: string): string | null {
58
+ return isDecimal(list) && isGreater(list, charged) ? list : null;
59
+ }
60
+
61
+ /**
62
+ * The server pricing that may stand for these cart lines, or null.
63
+ *
64
+ * It stands only when it covers the lines one to one: same count, every line
65
+ * found by id with the same quantity, and every amount a plain
66
+ * non-negative decimal string. Anything else (no pricing, a line added or
67
+ * re-quantified since the server read, a malformed amount) is null, and the
68
+ * caller prints its own list prices exactly as it always has: nothing is
69
+ * guessed and nothing is mixed. A struck list amount that is not higher than
70
+ * the amount charged is dropped to null. Amounts are returned as received.
71
+ */
72
+ export function resolveCartPricing(
73
+ pricing: CartServerPricing | null | undefined,
74
+ lines: readonly { id: string; quantity: number }[],
75
+ ): CartServerPricing | null {
76
+ if (!pricing || !Array.isArray(pricing.lines) || !isDecimal(pricing.total)) {
77
+ return null;
78
+ }
79
+
80
+ if (lines.length === 0 || pricing.lines.length !== lines.length) {
81
+ return null;
82
+ }
83
+
84
+ const byId = new Map<string, CartLinePricing>();
85
+
86
+ for (const entry of pricing.lines) {
87
+ if (!entry || typeof entry.line_id !== 'string' || !isDecimal(entry.unit_price) || !isDecimal(entry.line_total)) {
88
+ return null;
89
+ }
90
+
91
+ byId.set(entry.line_id, entry);
92
+ }
93
+
94
+ const covered: CartLinePricing[] = [];
95
+
96
+ for (const line of lines) {
97
+ const entry = byId.get(line.id);
98
+
99
+ if (!entry || entry.quantity !== line.quantity) {
100
+ return null;
101
+ }
102
+
103
+ covered.push({ ...entry, list_line_total: strikeOf(entry.list_line_total, entry.line_total) });
104
+ }
105
+
106
+ return { lines: covered, total: pricing.total, list_total: strikeOf(pricing.list_total, pricing.total) };
107
+ }
108
+
109
+ /** The server pricing of one cart line from a resolved overlay, or null when there is none for it. */
110
+ export function cartLinePricing(
111
+ pricing: CartServerPricing | null | undefined,
112
+ lineId: string,
113
+ ): CartLinePricing | null {
114
+ return pricing?.lines.find((entry) => entry.line_id === lineId) ?? null;
115
+ }
package/utils/format.ts CHANGED
@@ -171,6 +171,42 @@ export function formatMoney(
171
171
  }
172
172
  }
173
173
 
174
+ /**
175
+ * Format a money amount the server sent as a decimal STRING ("4500.00",
176
+ * KWD "1.250") without a float round trip: the string reaches Intl untouched,
177
+ * at the currency's own precision, with decimals shown only when present (the
178
+ * same style as `formatMoney`, which caps at 2 digits). Returns an empty string
179
+ * for anything that is not a plain non-negative decimal. Never computes, never throws.
180
+ *
181
+ * @example
182
+ * formatWireMoney('4500.00', 'NGN'); // "₦4,500"
183
+ */
184
+ export function formatWireMoney(
185
+ amount: string,
186
+ currency = PLATFORM_DEFAULT_CURRENCY,
187
+ locale?: string | null,
188
+ ): string {
189
+ if (typeof amount !== 'string' || !/^\d+(\.\d+)?$/.test(amount)) {
190
+ return '';
191
+ }
192
+
193
+ const code = normalizeCurrencyCode(currency);
194
+ const tag = displayTagFor(locale, (l) => Intl.NumberFormat.supportedLocalesOf(l));
195
+ try {
196
+ const precision = new Intl.NumberFormat(tag, { style: 'currency', currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
197
+
198
+ // Intl parses a decimal string exactly; the cast only satisfies the lib typing.
199
+ return new Intl.NumberFormat(tag, {
200
+ style: 'currency',
201
+ currency: code,
202
+ minimumFractionDigits: 0,
203
+ maximumFractionDigits: precision,
204
+ }).format(amount as unknown as number);
205
+ } catch {
206
+ return `${code} ${amount}`;
207
+ }
208
+ }
209
+
174
210
  /** A whole-number percentage string, e.g. `toPercent(12.4)` is `"12%"`. */
175
211
  /**
176
212
  * The one rounding for an amount the kit computes (event values, line totals):