Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
266 changes: 126 additions & 140 deletions commerce/sdk/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,162 +4,148 @@
* These are the generic, platform-independent mappers. Sites can wrap them
* to add custom fields (sellerP, etc.) via the `extend` option.
*/
import type { BreadcrumbList, Product } from "../types";
import type { BreadcrumbList, Product } from "../types/commerce";

export interface AnalyticsItem {
item_id?: string;
item_name?: string;
affiliation?: string;
coupon?: string;
discount?: number;
index?: number;
item_group_id?: string;
item_url?: string;
item_brand?: string;
item_category?: string;
item_category2?: string;
item_category3?: string;
item_category4?: string;
item_category5?: string;
item_list_id?: string;
item_list_name?: string;
item_variant?: string;
location_id?: string;
price?: number;
quantity: number;
[key: string]: unknown;
item_id?: string;
item_name?: string;
affiliation?: string;
coupon?: string;
discount?: number;
index?: number;
item_group_id?: string;
item_url?: string;
item_brand?: string;
item_category?: string;
item_category2?: string;
item_category3?: string;
item_category4?: string;
item_category5?: string;
item_list_id?: string;
item_list_name?: string;
item_variant?: string;
location_id?: string;
price?: number;
quantity: number;
[key: string]: unknown;
}

export function mapCategoriesToAnalyticsCategories(
categories: string[],
): Record<string, string> {
return categories.slice(0, 5).reduce(
(result, category, index) => {
result[`item_category${index === 0 ? "" : index + 1}`] = category;
return result;
},
{} as Record<string, string>,
);
export function mapCategoriesToAnalyticsCategories(categories: string[]): Record<string, string> {
return categories.slice(0, 5).reduce(
(result, category, index) => {
result[`item_category${index === 0 ? "" : index + 1}`] = category;
return result;
},
{} as Record<string, string>,
);
}

export function mapProductCategoryToAnalyticsCategories(category: string): Record<string, string> {
return category.split(">").reduce(
(result, cat, index) => {
result[`item_category${index === 0 ? "" : index}`] = cat.trim();
return result;
},
{} as Record<string, string>,
);
return category.split(">").reduce(
(result, cat, index) => {
result[`item_category${index === 0 ? "" : index}`] = cat.trim();
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Category key numbering is off by one, producing item_category1 instead of item_category2 for the second category.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At commerce/sdk/analytics.ts, line 46:

<comment>Category key numbering is off by one, producing `item_category1` instead of `item_category2` for the second category.</comment>

<file context>
@@ -4,162 +4,148 @@
-  );
+	return category.split(">").reduce(
+		(result, cat, index) => {
+			result[`item_category${index === 0 ? "" : index}`] = cat.trim();
+			return result;
+		},
</file context>
Suggested change
result[`item_category${index === 0 ? "" : index}`] = cat.trim();
result[`item_category${index === 0 ? "" : index + 1}`] = cat.trim();
Fix with Cubic

return result;
},
{} as Record<string, string>,
);
}

export interface MapProductToAnalyticsItemOptions {
product: Product;
breadcrumbList?: BreadcrumbList;
price?: number;
lowPrice?: number;
listPrice?: number;
index?: number;
quantity?: number;
coupon?: string;
/** Extend the result with custom fields (e.g., sellerP, sellerName) */
extend?: (product: Product, base: AnalyticsItem) => Record<string, unknown>;
product: Product;
breadcrumbList?: BreadcrumbList;
price?: number;
lowPrice?: number;
listPrice?: number;
index?: number;
quantity?: number;
coupon?: string;
/** Extend the result with custom fields (e.g., sellerP, sellerName) */
extend?: (product: Product, base: AnalyticsItem) => Record<string, unknown>;
}

export function mapProductToAnalyticsItem(opts: MapProductToAnalyticsItemOptions): AnalyticsItem {
const {
product,
breadcrumbList,
price,
lowPrice,
listPrice,
index = 0,
quantity = 1,
coupon = "",
extend,
} = opts;

const { name, productID, inProductGroupWithID, isVariantOf, url, sku } = product;

const categories = breadcrumbList?.itemListElement
? mapCategoriesToAnalyticsCategories(
breadcrumbList.itemListElement
.map(({ name: n }) => n ?? "")
.filter(Boolean),
)
: mapProductCategoryToAnalyticsCategories(product.category ?? "");

const base: AnalyticsItem = {
item_id: productID,
item_group_id: inProductGroupWithID,
quantity,
coupon,
price: lowPrice,
index,
item_variant: sku,
discount: Number((price && listPrice ? listPrice - price : 0).toFixed(2)),
item_name: isVariantOf?.name ?? name ?? "",
item_brand: product.brand?.name ?? "",
item_url: url,
...categories,
};

if (extend) {
return { ...base, ...extend(product, base) };
}

return base;
const {
product,
breadcrumbList,
price,
lowPrice,
listPrice,
index = 0,
quantity = 1,
coupon = "",
extend,
} = opts;

const { name, productID, inProductGroupWithID, isVariantOf, url, sku } = product;

const categories = breadcrumbList?.itemListElement
? mapCategoriesToAnalyticsCategories(
breadcrumbList.itemListElement.map(({ name: n }) => n ?? "").filter(Boolean),
)
: mapProductCategoryToAnalyticsCategories(product.category ?? "");

const base: AnalyticsItem = {
item_id: productID,
item_group_id: inProductGroupWithID,
quantity,
coupon,
price: lowPrice,
index,
item_variant: sku,
discount: Number((price && listPrice ? listPrice - price : 0).toFixed(2)),
item_name: isVariantOf?.name ?? name ?? "",
item_brand: product.brand?.name ?? "",
item_url: url,
...categories,
};

if (extend) {
return { ...base, ...extend(product, base) };
}

return base;
}

export interface MapProductToAnalyticsItemListOptions {
product: Product;
breadcrumbList?: BreadcrumbList;
price?: number;
listPrice?: number;
index?: number;
quantity?: number;
coupon?: string;
product: Product;
breadcrumbList?: BreadcrumbList;
price?: number;
listPrice?: number;
index?: number;
quantity?: number;
coupon?: string;
}

export function mapProductToAnalyticsItemList(opts: MapProductToAnalyticsItemListOptions): AnalyticsItem {
const {
product,
breadcrumbList,
price,
listPrice,
index = 0,
quantity = 1,
coupon = "",
} = opts;

const { name, productID, inProductGroupWithID, isVariantOf, url } = product;

const categories = breadcrumbList?.itemListElement
? mapCategoriesToAnalyticsCategories(
breadcrumbList.itemListElement
.map(({ name: n }) => n ?? "")
.filter(Boolean),
)
: mapProductCategoryToAnalyticsCategories(product.category ?? "");

const finalPrice = typeof price === "number" ? price : 0;
const discount =
typeof listPrice === "number" && typeof price === "number"
? Math.max(0, listPrice - price)
: 0;

const itemId = inProductGroupWithID ?? isVariantOf?.productGroupID ?? productID;

return {
item_id: itemId,
item_group_id: inProductGroupWithID,
quantity,
coupon,
price: finalPrice,
index,
discount: Number(discount.toFixed(2)),
item_name: isVariantOf?.name ?? name ?? "",
item_brand: product.brand?.name ?? "",
item_url: url,
...categories,
};
export function mapProductToAnalyticsItemList(
opts: MapProductToAnalyticsItemListOptions,
): AnalyticsItem {
const { product, breadcrumbList, price, listPrice, index = 0, quantity = 1, coupon = "" } = opts;

const { name, productID, inProductGroupWithID, isVariantOf, url } = product;

const categories = breadcrumbList?.itemListElement
? mapCategoriesToAnalyticsCategories(
breadcrumbList.itemListElement.map(({ name: n }) => n ?? "").filter(Boolean),
)
: mapProductCategoryToAnalyticsCategories(product.category ?? "");

const finalPrice = typeof price === "number" ? price : 0;
const discount =
typeof listPrice === "number" && typeof price === "number" ? Math.max(0, listPrice - price) : 0;

const itemId = inProductGroupWithID ?? isVariantOf?.productGroupID ?? productID;

return {
item_id: itemId,
item_group_id: inProductGroupWithID,
quantity,
coupon,
price: finalPrice,
index,
discount: Number(discount.toFixed(2)),
item_name: isVariantOf?.name ?? name ?? "",
item_brand: product.brand?.name ?? "",
item_url: url,
...categories,
};
}
6 changes: 4 additions & 2 deletions shopify/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ export function initShopify(config: { storeName: string; storefrontAccessToken:
* Initialize Shopify from a blocks map (convenience wrapper).
* Looks for the "deco-shopify" block and extracts credentials.
*/
export function initShopifyFromBlocks(blocks: Record<string, any>) {
const shopifyBlock = blocks["deco-shopify"];
export function initShopifyFromBlocks(blocks: Record<string, unknown>) {
const shopifyBlock = blocks["deco-shopify"] as
| { storeName: string; storefrontAccessToken: string }
| undefined;
if (!shopifyBlock) {
console.warn("[Shopify] No deco-shopify block found.");
return;
Expand Down
26 changes: 15 additions & 11 deletions shopify/loaders/ProductList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export type Props = {
metafields?: Metafield[];
};

const isQueryList = (p: any): p is QueryProps =>
typeof p.query === "string" && typeof p.count === "number";
const isQueryList = (p: QueryProps | CollectionProps): p is QueryProps =>
"query" in p && typeof p.query === "string" && typeof p.count === "number";

export default async function productListLoader(
expandedProps: Props,
Expand All @@ -52,19 +52,23 @@ export default async function productListLoader(
const metafields = expandedProps.metafields || [];
const sort = props.sort ?? "";

const filters: any[] = [];
expandedProps.filters?.tags?.forEach((tag) => filters.push({ tag }));
expandedProps.filters?.productTypes?.forEach((productType) => filters.push({ productType }));
expandedProps.filters?.productVendors?.forEach((productVendor) =>
filters.push({ productVendor }),
);
const filters: Record<string, unknown>[] = [];
for (const tag of expandedProps.filters?.tags ?? []) {
filters.push({ tag });
}
for (const productType of expandedProps.filters?.productTypes ?? []) {
filters.push({ productType });
}
for (const productVendor of expandedProps.filters?.productVendors ?? []) {
filters.push({ productVendor });
}
if (expandedProps.filters?.priceMin != null)
filters.push({ price: { min: expandedProps.filters.priceMin } });
if (expandedProps.filters?.priceMax != null)
filters.push({ price: { max: expandedProps.filters.priceMax } });
expandedProps.filters?.variantOptions?.forEach((variantOption) =>
filters.push({ variantOption }),
);
for (const variantOption of expandedProps.filters?.variantOptions ?? []) {
filters.push({ variantOption });
}

let shopifyProducts: { nodes: ProductShopify[] } | undefined;

Expand Down
6 changes: 3 additions & 3 deletions shopify/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface ShopifyState {
* Returns an AppDefinition or null if required fields are missing.
*/
export async function configure(
block: any,
block: Record<string, unknown>,
resolveSecret: ResolveSecretFn,
): Promise<AppDefinition<ShopifyState> | null> {
if (!block?.storeName) return null;
Expand All @@ -48,9 +48,9 @@ export async function configure(
if (!storefrontAccessToken) return null;

const config: ShopifyConfig = {
storeName: block.storeName,
storeName: block.storeName as string,
storefrontAccessToken,
publicUrl: block.publicUrl,
publicUrl: block.publicUrl as string | undefined,
};

// Bridge: maintain global singleton for backward compat
Expand Down
1 change: 1 addition & 0 deletions shopify/utils/admin/admin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file no-explicit-any ban-types ban-unused-ignore
// biome-ignore-all lint/suspicious/noExplicitAny: generated GraphQL scalar types

export type Maybe<T> = T | null;

Expand Down
Loading
Loading