Skip to content

Commit

Permalink
fix: analytics event product data (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vavarine committed Jul 11, 2023
1 parent 22c8ce1 commit 3c22171
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions commerce/utils/productToAnalyticsItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ export const mapCategoriesToAnalyticsCategories = (
);
};

export const mapProductCategoryToAnalyticsCategories = (category: string) => {
return category.split(">").reduce(
(result, category, index) => {
result[`item_category${index === 0 ? "" : index + 1}`] = category;
return result;
},
{} as Record<`item_category${number | ""}`, string>,
);
};

export const mapProductToAnalyticsItem = (
{ product, breadcrumbList, price, listPrice }: {
product: Product;
Expand All @@ -20,18 +30,31 @@ export const mapProductToAnalyticsItem = (
listPrice?: number;
},
): AnalyticsItem => {
const { name, productID } = product;
return {
item_id: product.isVariantOf?.productGroupID ?? "",
quantity: 1,
price,
discount: price && listPrice ? listPrice - price : 0,
item_name: name,
item_variant: productID,
...(mapCategoriesToAnalyticsCategories(
const { name, productID, isVariantOf } = product;
const index = Math.max(
product.isVariantOf?.hasVariant.findIndex((v) => v.url === product.url) ||
0,
0,
);

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

return {
item_id: productID,
quantity: 1,
coupon: "",
price,
index,
discount: Number((price && listPrice ? listPrice - price : 0).toFixed(2)),
item_name: isVariantOf?.name ?? name ?? "",
item_variant: name,
item_brand: product.brand ?? "",
...categories,
};
};

0 comments on commit 3c22171

Please sign in to comment.