feat(analytics): added products to add to cart event

This commit is contained in:
oybek 2024-04-01 18:28:57 +04:00
parent 7be35ae4e3
commit ff5c75bbc5
5 changed files with 45 additions and 4 deletions

View File

@ -4,11 +4,14 @@ import { TAGS } from 'lib/constants';
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify'; import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
import { revalidateTag } from 'next/cache'; import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { ShopifyAnalyticsProduct } from '@shopify/hydrogen-react';
import { productToAnalytics } from '../../lib/utils';
type AddItemResponse = { type AddItemResponse = {
cartId?: string; cartId?: string;
success: boolean; success: boolean;
message?: string; message?: string;
products?: ShopifyAnalyticsProduct[];
}; };
export async function addItem( export async function addItem(
@ -17,6 +20,7 @@ export async function addItem(
): Promise<AddItemResponse> { ): Promise<AddItemResponse> {
let cartId = cookies().get('cartId')?.value; let cartId = cookies().get('cartId')?.value;
let cart; let cart;
const quantity = 1;
if (cartId) { if (cartId) {
cart = await getCart(cartId); cart = await getCart(cartId);
@ -33,12 +37,13 @@ export async function addItem(
} }
try { try {
await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity: 1 }]); const response = await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity }]);
revalidateTag(TAGS.cart); revalidateTag(TAGS.cart);
return { return {
success: true, success: true,
message: 'Item added to cart', message: 'Item added to cart',
cartId cartId,
products: productToAnalytics(response.lines, quantity, selectedVariantId)
}; };
} catch (e) { } catch (e) {
return { success: false, message: 'Error adding item to cart' }; return { success: false, message: 'Error adding item to cart' };

View File

@ -87,10 +87,12 @@ export function AddToCart({
useEffect(() => { useEffect(() => {
if (response?.success && response.cartId) { if (response?.success && response.cartId) {
sendAddToCart({ sendAddToCart({
cartId: response.cartId cartId: response.cartId,
products: response.products,
totalValue: Number(response.products?.[0]?.price)
}); });
} }
}, [response?.success, response?.cartId, sendAddToCart]); }, [response?.success, response?.cartId, sendAddToCart, response?.products]);
return ( return (
<form action={actionWithVariant}> <form action={actionWithVariant}>

View File

@ -37,6 +37,10 @@ const cartFragment = /* GraphQL */ `
name name
value value
} }
price {
amount
currencyCode
}
product { product {
...product ...product
} }

View File

@ -21,6 +21,7 @@ export type CartItem = {
merchandise: { merchandise: {
id: string; id: string;
title: string; title: string;
price: Money;
selectedOptions: { selectedOptions: {
name: string; name: string;
value: string; value: string;

View File

@ -1,4 +1,6 @@
import { ReadonlyURLSearchParams } from 'next/navigation'; import { ReadonlyURLSearchParams } from 'next/navigation';
import { Cart } from './shopify/types';
import { ShopifyAnalyticsProduct } from '@shopify/hydrogen-react';
export const createUrl = (pathname: string, params: URLSearchParams | ReadonlyURLSearchParams) => { export const createUrl = (pathname: string, params: URLSearchParams | ReadonlyURLSearchParams) => {
const paramsString = params.toString(); const paramsString = params.toString();
@ -37,3 +39,30 @@ export const validateEnvironmentVariables = () => {
); );
} }
}; };
/**
* This function takes a cart and a quantity and returns an array of ShopifyAnalyticsProduct objects.
* */
export const productToAnalytics = (
cartItems: Cart['lines'],
quantity: number,
variantId: string
) => {
const line = cartItems.find((line) => line.merchandise.id === variantId);
if (!line) return;
const { merchandise } = line;
if (!merchandise) return;
return [
{
productGid: merchandise?.product.id,
variantGid: variantId,
name: merchandise?.product.title,
variantName: merchandise?.title,
price: merchandise?.price.amount,
quantity
} as ShopifyAnalyticsProduct
];
};