@usequeek/theme-kit 0.1.39 → 0.1.40

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.
@@ -3,6 +3,8 @@
3
3
  import { roundAmount } from '../utils/format';
4
4
  import { gtagPush } from './gtag';
5
5
 
6
+ export { catalogItemId, catalogItemIdForCartLine, toPId, type CatalogItemRef, type CatalogItemSource } from '../utils/catalog-id';
7
+
6
8
  /**
7
9
  * The one place a storefront announces a shopping event.
8
10
  *
@@ -27,7 +29,17 @@ import { gtagPush } from './gtag';
27
29
  */
28
30
 
29
31
  export interface StorefrontEventItem {
32
+ /**
33
+ * The catalog id: a variant is `"{product_p_id}_{variant_p_id}"`, a product without variants is
34
+ * `"{product_p_id}"`, and with no `p_id` the product UUID (see `catalogItemId`; build it with that
35
+ * helper, never from a raw id). A string: GA4, Meta and TikTok all take string ids.
36
+ */
30
37
  item_id: string;
38
+ /**
39
+ * True when `item_id` is a product-group id (see `CatalogItemRef.is_group`). Meta and TikTok
40
+ * get `content_type: 'product_group'` for it. Never sent to GA4.
41
+ */
42
+ is_group?: boolean;
31
43
  item_name: string;
32
44
  /** The unit price actually charged, after discounts. Providers sum price * quantity as revenue. */
33
45
  price: number;
@@ -128,6 +140,7 @@ function normalizeItems(items: unknown): StorefrontEventItem[] {
128
140
  item_name: String(item?.item_name ?? ''),
129
141
  price: Number(item?.price),
130
142
  quantity: Number(item?.quantity),
143
+ ...(item?.is_group === true ? { is_group: true } : {}),
131
144
  }));
132
145
  }
133
146
 
@@ -216,6 +229,10 @@ export function trackStorefrontEvent<K extends StorefrontEventName>(name: K, dat
216
229
 
217
230
  const finite = (value: number): boolean => Number.isFinite(value);
218
231
 
232
+ /** GA4's items: the bus item without `is_group`, which only Meta and TikTok read. */
233
+ const gaItems = (items: StorefrontEventItem[]): Array<Omit<StorefrontEventItem, 'is_group'>> =>
234
+ items.map(({ is_group: _isGroup, ...item }) => item);
235
+
219
236
  /** `{ value }` when it is a real number, nothing otherwise: GA gets no `NaN`. */
220
237
  const valueParam = (value: number): { value: number } | Record<string, never> => (finite(value) ? { value } : {});
221
238
 
@@ -232,16 +249,16 @@ const valueParam = (value: number): { value: number } | Record<string, never> =>
232
249
  function googleAnalyticsSubscriber(event: StorefrontEvent): void {
233
250
  switch (event.name) {
234
251
  case 'product_viewed':
235
- gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
252
+ gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
236
253
  return;
237
254
  case 'search_submitted':
238
255
  gtagPush('event', 'search', { search_term: event.data.search_term });
239
256
  return;
240
257
  case 'product_added_to_cart':
241
- gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
258
+ gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
242
259
  return;
243
260
  case 'checkout_started':
244
- gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
261
+ gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: gaItems(event.data.items) });
245
262
  return;
246
263
  case 'checkout_completed': {
247
264
  const { order_no, currency, items, subtotal, tax, shipping } = event.data;
@@ -256,7 +273,7 @@ function googleAnalyticsSubscriber(event: StorefrontEvent): void {
256
273
  currency,
257
274
  ...(typeof tax === 'number' && finite(tax) ? { tax } : {}),
258
275
  ...(typeof shipping === 'number' && finite(shipping) ? { shipping } : {}),
259
- items,
276
+ items: gaItems(items),
260
277
  });
261
278
  }
262
279
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.39",
3
+ "version": "0.1.40",
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.",
@@ -7,6 +7,7 @@ import type { Product, ProductVariant } from '../types/product';
7
7
  import { toast } from './toast-store';
8
8
  import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY, roundAmount } from '../utils/format';
9
9
  import { trackStorefrontEvent } from '../apps/storefront-events';
10
+ import { catalogItemId, toPId } from '../utils/catalog-id';
10
11
  import { getActivePlatform, platformScopedStorage } from '../sdk/platform';
11
12
  import { productRequiresVariant } from '../utils/match-variant';
12
13
  import { readLineText } from './line-text-store';
@@ -201,6 +202,9 @@ export const useCartStore = create<CartState>()(
201
202
  });
202
203
  }
203
204
  const addedQuantity = Math.max(1, quantity);
205
+ // The catalog ids of this line (what the pixel sends); null when the payload carries none.
206
+ const productPId = toPId(product.p_id);
207
+ const variantPId = toPId(variant?.p_id);
204
208
 
205
209
  set((state) => {
206
210
  const existing = state.items.findIndex(
@@ -214,6 +218,8 @@ export const useCartStore = create<CartState>()(
214
218
  ...current,
215
219
  quantity: current.quantity + Math.max(1, quantity),
216
220
  unit_price: unitPrice,
221
+ ...(productPId !== null ? { product_p_id: productPId } : {}),
222
+ ...(variantPId !== null ? { variant_p_id: variantPId } : {}),
217
223
  };
218
224
 
219
225
  return { items };
@@ -234,6 +240,9 @@ export const useCartStore = create<CartState>()(
234
240
  addons,
235
241
  variant_id: variant?.id ?? null,
236
242
  variant_title: variant?.title ?? null,
243
+ // Like `properties`: a payload without a p_id leaves the key off, so a line keeps the shape it always had.
244
+ ...(productPId !== null ? { product_p_id: productPId } : {}),
245
+ ...(variantPId !== null ? { variant_p_id: variantPId } : {}),
237
246
  ...(hasLineText ? { properties: lineText.properties, property_labels: lineText.labels } : {}),
238
247
  },
239
248
  ],
@@ -243,7 +252,14 @@ export const useCartStore = create<CartState>()(
243
252
  trackStorefrontEvent('product_added_to_cart', {
244
253
  currency: get().currency,
245
254
  value: roundAmount(unitPrice * addedQuantity),
246
- items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
255
+ items: [
256
+ {
257
+ ...catalogItemId({ variantPId, productPId, hasVariant: variant !== null, fallbackId: product.id }),
258
+ item_name: product.title,
259
+ price: unitPrice,
260
+ quantity: addedQuantity,
261
+ },
262
+ ],
247
263
  });
248
264
 
249
265
  return 'added';
package/types/cart.ts CHANGED
@@ -16,6 +16,13 @@ export interface CartItem {
16
16
  quantity: number;
17
17
  addons: CartAddon[];
18
18
  variant_id?: string | null;
19
+ /**
20
+ * The product's and the variant's `p_id`, the ids a catalog feed uses, kept so the pixel
21
+ * can send them. Absent on a line saved before they existed or read from a cart the API
22
+ * answered without them: `catalogItemIdForCartLine` then falls back.
23
+ */
24
+ product_p_id?: number | null;
25
+ variant_p_id?: number | null;
19
26
  /** e.g. "Denim" — the selected variant's display name, when this line has one. */
20
27
  variant_title?: string | null;
21
28
  /**
package/types/order.ts CHANGED
@@ -25,6 +25,15 @@ export interface OrderItem {
25
25
  unit_price: number | string;
26
26
  addons: Array<Record<string, unknown>>;
27
27
  product?: { id: string; thumbnail_image?: string | null } | null;
28
+ /**
29
+ * What the API sends on an order line to identify it in a catalog: the product's and the variant's
30
+ * `p_id` and the variant's name. All optional: older answers lack them, and the variant's `p_id` is
31
+ * null for a line whose variant was deleted.
32
+ */
33
+ product_p_id?: number | null;
34
+ variant_id?: string | null;
35
+ variant_p_id?: number | null;
36
+ variant_title?: string | null;
28
37
  }
29
38
 
30
39
  export interface OrderTimeline {
package/types/product.ts CHANGED
@@ -101,6 +101,11 @@ export interface ProductVariantOptionValue {
101
101
 
102
102
  export interface ProductVariant {
103
103
  id: string;
104
+ /**
105
+ * The variant's `p_id`, the id ad-platform catalog feeds use for it (feed `id`) and so the id
106
+ * the pixel must send. Absent on a payload that predates it: read it through `catalogItemId`.
107
+ */
108
+ p_id?: number;
104
109
  sku: string | null;
105
110
  /** Printed barcode / GTIN (EAN-13/8, UPC-A/E) for in-store scan-to-cart. */
106
111
  barcode: string | null;
@@ -0,0 +1,83 @@
1
+ import type { CartItem } from '../types/cart';
2
+
3
+ /**
4
+ * The id a shopping event carries for an item, and the ONE place that decides it.
5
+ *
6
+ * THE CATALOG ID RULE (the ad-platform catalog feeds use the same one):
7
+ *
8
+ * - a variant row is `"{product_p_id}_{variant_p_id}"`;
9
+ * - a product without variants is `"{product_p_id}"`;
10
+ * - the `product_group` id (the feed's `item_group_id`) is `"{product_p_id}"`.
11
+ *
12
+ * Products and variants number their `p_id`s from separate sequences that overlap (both
13
+ * start at 1000), so a bare variant `p_id` could equal an unrelated product's: the id of
14
+ * a variant is always the pair. A pixel event matches a catalog item only when it sends
15
+ * that same id.
16
+ *
17
+ * Fallbacks, in order:
18
+ * - a variant `p_id` AND a product `p_id` -> `"P_V"`;
19
+ * - only a product `p_id` -> `"P"` (flagged `is_group` when the
20
+ * item belongs to a product with variants, because then `"P"` names the group, not a row);
21
+ * - a variant `p_id` but NO product `p_id` -> the UUID. A bare variant `p_id` is never sent;
22
+ * - no `p_id` at all -> the product's UUID.
23
+ *
24
+ * The UUID is the last resort for a line that has no `p_id` (a cart saved before the ids
25
+ * existed, an API answer that predates them). It matches no catalog item, which is no
26
+ * worse than before p_ids. When that fallback is no longer needed, deleting the
27
+ * `fallbackId` branch below is the whole cleanup.
28
+ */
29
+ export interface CatalogItemRef {
30
+ item_id: string;
31
+ /**
32
+ * True when `item_id` is a PRODUCT-group id (a product `p_id` standing for a product that
33
+ * has variants, because no variant is known). Meta and TikTok match that against the
34
+ * feed's `item_group_id` only when the event says `content_type: 'product_group'`.
35
+ */
36
+ is_group?: true;
37
+ }
38
+
39
+ export interface CatalogItemSource {
40
+ variantPId?: unknown;
41
+ /** Needed for any p_id id: without it the item falls back to `fallbackId`. */
42
+ productPId?: unknown;
43
+ /** The item is a specific variant (chosen or bought), or belongs to a product that has variants. */
44
+ hasVariant?: boolean;
45
+ /** The product's UUID: the last resort. Never an order or cart line id. */
46
+ fallbackId?: string | null;
47
+ }
48
+
49
+ /** A `p_id` as a number: a positive whole number (a number, or digits in a string). Anything else is null. */
50
+ export function toPId(value: unknown): number | null {
51
+ const number = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : value;
52
+
53
+ return typeof number === 'number' && Number.isSafeInteger(number) && number > 0 ? number : null;
54
+ }
55
+
56
+ export function catalogItemId(source: CatalogItemSource): CatalogItemRef {
57
+ const productPId = toPId(source.productPId);
58
+
59
+ if (productPId === null) {
60
+ // No product p_id: never a bare variant p_id (variant and product p_ids overlap), so the UUID.
61
+ return { item_id: source.fallbackId ?? '' };
62
+ }
63
+
64
+ const variantPId = toPId(source.variantPId);
65
+
66
+ if (variantPId !== null) {
67
+ return { item_id: `${productPId}_${variantPId}` };
68
+ }
69
+
70
+ return source.hasVariant === true ? { item_id: String(productPId), is_group: true } : { item_id: String(productPId) };
71
+ }
72
+
73
+ /** The catalog id of a cart line (`CartItem`). */
74
+ export function catalogItemIdForCartLine(
75
+ line: Pick<CartItem, 'product_id' | 'variant_id' | 'product_p_id' | 'variant_p_id'>,
76
+ ): CatalogItemRef {
77
+ return catalogItemId({
78
+ variantPId: line.variant_p_id,
79
+ productPId: line.product_p_id,
80
+ hasVariant: typeof line.variant_id === 'string' && line.variant_id !== '',
81
+ fallbackId: line.product_id,
82
+ });
83
+ }
@@ -9,6 +9,7 @@ import type {
9
9
  ProductVariantOptionValue,
10
10
  } from '../types/product';
11
11
  import { normalizeCurrencyCode } from './format';
12
+ import { toPId } from './catalog-id';
12
13
 
13
14
  const KIND_SET = new Set(['physical', 'service', 'digital']);
14
15
  const STATUS_SET = new Set(['active', 'inactive']);
@@ -331,6 +332,8 @@ export function normalizeProduct(raw: LegacyProductLike): Product {
331
332
 
332
333
  return {
333
334
  id: String(variant.id ?? `variant-${index}`),
335
+ // Only a real `p_id` (a positive whole number) is carried; a payload without one keeps its shape.
336
+ ...(toPId(variant.p_id) !== null ? { p_id: toPId(variant.p_id) as number } : {}),
334
337
  sku: variant.sku ?? null,
335
338
  barcode: typeof variant.barcode === 'string' && variant.barcode !== '' ? variant.barcode : null,
336
339
  title: variant.title ?? null,