109 lines
2.7 KiB
TypeScript
109 lines
2.7 KiB
TypeScript
/**
|
|
* Google Analytics 4 (GA4) E-Commerce & Telemetry Tracker
|
|
* Property ID: 521198579 / iFixKart Storefront
|
|
*/
|
|
|
|
declare global {
|
|
interface Window {
|
|
dataLayer: any[];
|
|
gtag: (...args: any[]) => void;
|
|
}
|
|
}
|
|
|
|
export const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || 'G-IFIXKART2026';
|
|
|
|
export function trackPageView(url: string) {
|
|
if (typeof window === 'undefined' || typeof window.gtag !== 'function') return;
|
|
try {
|
|
window.gtag('config', GA_MEASUREMENT_ID, {
|
|
page_path: url,
|
|
});
|
|
} catch (err) {
|
|
console.debug('[GA4] Pageview tracking suppressed', err);
|
|
}
|
|
}
|
|
|
|
export function trackEvent(action: string, params: Record<string, any> = {}) {
|
|
if (typeof window === 'undefined' || typeof window.gtag !== 'function') return;
|
|
try {
|
|
window.gtag('event', action, params);
|
|
} catch (err) {
|
|
console.debug('[GA4] Event tracking suppressed', err);
|
|
}
|
|
}
|
|
|
|
export function trackViewItem(product: {
|
|
id: string | number;
|
|
name: string;
|
|
price: number;
|
|
category?: string;
|
|
brand?: string;
|
|
sku?: string;
|
|
}) {
|
|
trackEvent('view_item', {
|
|
currency: 'INR',
|
|
value: product.price,
|
|
items: [
|
|
{
|
|
item_id: String(product.sku || product.id),
|
|
item_name: product.name,
|
|
price: product.price,
|
|
item_category: product.category || 'Spare Parts',
|
|
item_brand: product.brand || 'iFixKart',
|
|
quantity: 1,
|
|
},
|
|
],
|
|
});
|
|
}
|
|
|
|
export function trackAddToCart(product: {
|
|
id: string | number;
|
|
name: string;
|
|
price: number;
|
|
category?: string;
|
|
brand?: string;
|
|
sku?: string;
|
|
quantity?: number;
|
|
}) {
|
|
trackEvent('add_to_cart', {
|
|
currency: 'INR',
|
|
value: product.price * (product.quantity || 1),
|
|
items: [
|
|
{
|
|
item_id: String(product.sku || product.id),
|
|
item_name: product.name,
|
|
price: product.price,
|
|
item_category: product.category || 'Spare Parts',
|
|
item_brand: product.brand || 'iFixKart',
|
|
quantity: product.quantity || 1,
|
|
},
|
|
],
|
|
});
|
|
}
|
|
|
|
export function trackBeginCheckout(items: any[], totalValue: number) {
|
|
trackEvent('begin_checkout', {
|
|
currency: 'INR',
|
|
value: totalValue,
|
|
items: items.map((item) => ({
|
|
item_id: String(item.variant_id || item.product_id || item.id),
|
|
item_name: item.name || item.title,
|
|
price: item.price,
|
|
quantity: item.quantity || 1,
|
|
})),
|
|
});
|
|
}
|
|
|
|
export function trackPurchase(orderId: string, totalValue: number, items: any[]) {
|
|
trackEvent('purchase', {
|
|
transaction_id: orderId,
|
|
currency: 'INR',
|
|
value: totalValue,
|
|
items: items.map((item) => ({
|
|
item_id: String(item.variant_id || item.product_id || item.id),
|
|
item_name: item.name || item.title,
|
|
price: item.price,
|
|
quantity: item.quantity || 1,
|
|
})),
|
|
});
|
|
}
|