All files / app/services analytics.service.ts

87.09% Statements 27/31
87.5% Branches 14/16
83.33% Functions 5/6
87.09% Lines 27/31

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                          1x 24x   24x     24x 24x   24x             2x       2x 2x 1x 1x                 1x 1x 1x 1x     1x 1x                 1x             2x 1x     1x 1x 1x               1x       1x 1x 1x                              
import { Injectable, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { CookieService } from './cookie.service';
 
declare var gtag: any;
 
/**
 * Service pour gérer Google Analytics
 * Respecte les préférences de cookies de l'utilisateur
 */
@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  private readonly GA_MEASUREMENT_ID = 'G-XXXXXXXXXX'; // À remplacer par votre ID Google Analytics
  private isBrowser: boolean;
  private isInitialized = false;
 
  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private cookieService: CookieService
  ) {
    this.isBrowser = isPlatformBrowser(this.platformId);
  }
 
  /**
   * Initialise Google Analytics si l'utilisateur a accepté les cookies analytiques
   */
  initialize(): void {
    Iif (!this.isBrowser || this.isInitialized) {
      return;
    }
 
    const consent = this.cookieService.getPreferences();
    if (consent.analytics) {
      this.loadGoogleAnalytics();
      this.isInitialized = true;
    }
  }
 
  /**
   * Charge le script Google Analytics
   */
  private loadGoogleAnalytics(): void {
    // Script gtag.js
    const script1 = document.createElement('script');
    script1.async = true;
    script1.src = `https://www.googletagmanager.com/gtag/js?id=${this.GA_MEASUREMENT_ID}`;
    document.head.appendChild(script1);
 
    // Configuration gtag
    const script2 = document.createElement('script');
    script2.innerHTML = `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${this.GA_MEASUREMENT_ID}', {
        'anonymize_ip': true,
        'cookie_flags': 'SameSite=None;Secure'
      });
    `;
    document.head.appendChild(script2);
  }
 
  /**
   * Envoie un événement à Google Analytics
   */
  trackEvent(eventName: string, eventParams?: any): void {
    if (!this.isBrowser || !this.isInitialized) {
      return;
    }
 
    const consent = this.cookieService.getPreferences();
    if (consent.analytics && typeof gtag !== 'undefined') {
      gtag('event', eventName, eventParams);
    }
  }
 
  /**
   * Envoie une page view à Google Analytics
   */
  trackPageView(path: string): void {
    Iif (!this.isBrowser || !this.isInitialized) {
      return;
    }
 
    const consent = this.cookieService.getPreferences();
    if (consent.analytics && typeof gtag !== 'undefined') {
      gtag('config', this.GA_MEASUREMENT_ID, {
        page_path: path
      });
    }
  }
 
  /**
   * Réinitialise Google Analytics (appelé quand l'utilisateur change ses préférences)
   */
  reinitialize(): void {
    this.isInitialized = false;
    this.initialize();
  }
}