All files / src/lib event-tracking.ts

99.02% Statements 203/205
95.65% Branches 22/23
100% Functions 19/19
99.02% Lines 203/205

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 2061x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 25x 25x 25x 25x 25x 31x 31x 31x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x     26x 26x 31x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Client-side Event Tracking System
 * Tracks user interactions for analytics (Google Analytics 4 and backend logging)
 */
 
import { logger } from '@/lib/logging';
 
/**
 * Track a generic event
 */
export const trackEvent = (
  category: string,
  action: string,
  label?: string,
  value?: number
): void => {
  // Google Analytics 4
  if (typeof window !== "undefined" && window.gtag) {
    window.gtag("event", action, {
      event_category: category,
      event_label: label,
      value: value});
  }
 
  // Also log to our backend
  if (typeof window !== "undefined" && typeof fetch !== "undefined") {
    void fetch("/api/analytics/track", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        category,
        action,
        label,
        value,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent,
        url: window.location.href})}).catch((error) => {
      // Silently fail - don't disrupt user experience
      if (process.env.NODE_ENV === "development") {
        logger.error("Analytics tracking failed", error instanceof Error ? error : new Error(String(error)), { category: 'ANALYTICS' });
      }
    });
  }
};
 
/**
 * Convenience functions for common analytics events
 */
export const eventTracking = {
  /**
   * Track product view
   */
  productView: (productId: number, productName: string): void => {
    trackEvent("Product", "view", productName, productId);
  },
 
  /**
   * Track add to cart action
   */
  addToCart: (productId: number, productName: string, price: number): void => {
    trackEvent("Cart", "add", productName, price);
  },
 
  /**
   * Track remove from cart action
   */
  removeFromCart: (productId: number, productName: string): void => {
    trackEvent("Cart", "remove", productName, productId);
  },
 
  /**
   * Track cart quantity update
   */
  updateCartQuantity: (productId: number, productName: string, newQuantity: number): void => {
    trackEvent("Cart", "update_quantity", productName, newQuantity);
  },
 
  /**
   * Track wishlist add
   */
  addToWishlist: (productId: number, productName: string): void => {
    trackEvent("Wishlist", "add", productName, productId);
  },
 
  /**
   * Track wishlist remove
   */
  removeFromWishlist: (productId: number, productName: string): void => {
    trackEvent("Wishlist", "remove", productName, productId);
  },
 
  /**
   * Track checkout initiation
   */
  initiateCheckout: (cartValue: number, itemCount: number): void => {
    trackEvent("Checkout", "initiate", `${itemCount} items`, cartValue);
  },
 
  /**
   * Track checkout step completion
   */
  checkoutStep: (step: string, stepNumber: number): void => {
    trackEvent("Checkout", "step", step, stepNumber);
  },
 
  /**
   * Track successful purchase
   */
  completePurchase: (orderId: number, total: number, itemCount: number): void => {
    trackEvent("Purchase", "complete", `Order ${orderId}`, total);
 
    // Also track as conversion
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", "purchase", {
        transaction_id: orderId.toString(),
        value: total,
        currency: "USD",
        items: itemCount});
    }
  },
 
  /**
   * Track search query
   */
  search: (query: string, resultCount: number): void => {
    trackEvent("Search", "query", query, resultCount);
  },
 
  /**
   * Track filter usage
   */
  applyFilter: (filterType: string, filterValue: string): void => {
    trackEvent("Filter", "apply", `${filterType}: ${filterValue}`);
  },
 
  /**
   * Track filter removal
   */
  removeFilter: (filterType: string): void => {
    trackEvent("Filter", "remove", filterType);
  },
 
  /**
   * Track sort change
   */
  changeSort: (sortOption: string): void => {
    trackEvent("Sort", "change", sortOption);
  },
 
  /**
   * Track authentication events
   */
  signIn: (method: string): void => {
    trackEvent("Auth", "sign_in", method);
  },
 
  /**
   * Track sign up events
   */
  signUp: (method: string): void => {
    trackEvent("Auth", "sign_up", method);
  },
 
  /**
   * Track sign out
   */
  signOut: (): void => {
    trackEvent("Auth", "sign_out");
  },
 
  /**
   * Track page views (for SPA navigation)
   */
  pageView: (path: string, title?: string): void => {
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", "page_view", {
        page_path: path,
        page_title: title});
    }
    trackEvent("Navigation", "page_view", path);
  },
 
  /**
   * Track errors
   */
  error: (errorType: string, errorMessage: string): void => {
    trackEvent("Error", errorType, errorMessage);
 
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", "exception", {
        description: errorMessage,
        fatal: false});
    }
  }};
 
// Type definitions for gtag
declare global {
  interface Window {
    gtag?: (
      command: string,
      eventName: string,
      params?: Record<string, unknown>
    ) => void;
  }
}