All files / app/services utm-tracker.service.ts

85.48% Statements 265/310
65.78% Branches 25/38
76.92% Functions 20/26
85.48% Lines 265/310

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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 3111x 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 38x 38x 38x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 55x 55x 55x 55x 55x 5x 5x 1x 1x 22x 22x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 5x 55x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 15x 15x 15x 15x 15x 5x 5x 1x 1x 15x 15x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 1x 1x                   1x 1x           1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 12x 12x 12x 1x 1x 12x   12x 12x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 1x 1x 5x 5x 1x 1x 1x 5x 1x 1x 5x 5x 1x 1x 5x 5x 5x 5x     5x 5x 1x 1x 5x 5x 1x 1x               1x 1x         1x 1x 1x 1x 1x                           1x 1x     1x  
import { isPlatformBrowser } from '@angular/common';
import { inject, Injectable, PLATFORM_ID } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
 
export interface UTMValues {
	utm_source: string | null;
	utm_medium: string | null;
	utm_campaign: string | null;
	landing_page: string | null;
	referrer: string | null;
	queries: string | null;
}
 
export interface GoogleAdsValues {
	hsa_acc: string | null;
	hsa_cam: string | null;
	hsa_grp: string | null;
	hsa_ad: string | null;
	hsa_src: string | null;
	hsa_tgt: string | null;
	hsa_kw: string | null;
	hsa_mt: string | null;
	hsa_net: string | null;
	hsa_ver: string | null;
	lpurl: string | null;
}
 
@Injectable({ providedIn: 'root' })
export class UTMTrackerService {
	private currentPrefix = 'current_';
	private firstPrefix = 'first_';
	private adsPrefix = 'ads_'; // ✅ NEW
	private submittedDealKeyPrefix = 'hs_deal_submitted_';
 
	private cookieService = inject(CookieService);
 
	private siteDomain = ['gorealtravel.com', 'web.staging.gorealtravel.com', 'localhost'];
 
	isBrowser: boolean;
 
	constructor() {
		const platformId = inject(PLATFORM_ID);
		this.isBrowser = isPlatformBrowser(platformId);
	}
 
	// ================================
	// INIT
	// ================================
	initOnFirstPage(): void {
		if (!this.isBrowser) return;
 
		this.captureReferrerOnce();
		this.captureLandingPageOnce();
		this.captureQueriesOnce();
		this.captureUTMsOnce();
		this.captureGoogleAdsParamsOnce(); // ✅ NEW
 
		const current = this.buildCurrentUTMValues();
		this.setSessionValues(current);
 
		const ads = this.buildGoogleAdsValues();
		this.setAdsSessionValues(ads);
 
		if (!this.cookiesHaveFirstValues()) {
			this.setFirstValuesIfMissing(current);
		}
	}
 
	// ================================
	// ADS CAPTURE (NEW)
	// ================================
	private captureGoogleAdsParamsOnce(): void {
		if (!this.isBrowser) return;
 
		const keys: (keyof GoogleAdsValues)[] = [
			'hsa_acc',
			'hsa_cam',
			'hsa_grp',
			'hsa_ad',
			'hsa_src',
			'hsa_tgt',
			'hsa_kw',
			'hsa_mt',
			'hsa_net',
			'hsa_ver',
			'lpurl',
		];
 
		const params = new URLSearchParams(window.location.search);
 
		keys.forEach((key) => {
			const storageKey = 'ads_' + key;
			if (!sessionStorage.getItem(storageKey)) {
				const value = params.get(key);
				if (value) sessionStorage.setItem(storageKey, value);
			}
		});
	}
 
	private getAds(key: string): string | null {
		return sessionStorage.getItem('ads_' + key);
	}
 
	private buildGoogleAdsValues(): GoogleAdsValues {
		return {
			hsa_acc: this.getAds('hsa_acc'),
			hsa_cam: this.getAds('hsa_cam'),
			hsa_grp: this.getAds('hsa_grp'),
			hsa_ad: this.getAds('hsa_ad'),
			hsa_src: this.getAds('hsa_src'),
			hsa_tgt: this.getAds('hsa_tgt'),
			hsa_kw: this.getAds('hsa_kw'),
			hsa_mt: this.getAds('hsa_mt'),
			hsa_net: this.getAds('hsa_net'),
			hsa_ver: this.getAds('hsa_ver'),
			lpurl: this.getAds('lpurl'),
		};
	}
 
	private setAdsSessionValues(values: GoogleAdsValues) {
		Object.entries(values).forEach(([key, val]) => {
			sessionStorage.setItem(this.adsPrefix + key, val ?? '');
		});
	}
 
	// ================================
	// UTM (UNCHANGED)
	// ================================
	private captureUTMsOnce(): void {
		const keys = ['utm_source', 'utm_medium', 'utm_campaign'];
		const params = new URLSearchParams(typeof window !== 'undefined' ? window.location.search : '');
 
		keys.forEach((key) => {
			const sessionKey = 'session_' + key;
			if (!sessionStorage.getItem(sessionKey)) {
				const value = params.get(key);
				if (value) sessionStorage.setItem(sessionKey, value.toLowerCase());
			}
		});
	}
 
	private getSessionUTM(key: string): string | null {
		return sessionStorage.getItem('session_' + key);
	}
 
	private buildCurrentUTMValues(): UTMValues {
		return {
			utm_source: this.getSessionUTM('utm_source'),
			utm_medium: this.getSessionUTM('utm_medium'),
			utm_campaign: this.getSessionUTM('utm_campaign'),
			landing_page: this.getSessionLandingPage(),
			referrer: this.getSessionReferrer(),
			queries: this.getSessionQueries(),
		};
	}
 
	// ================================
	// STORAGE HELPERS
	// ================================
	private setSessionValues(values: UTMValues) {
		sessionStorage.setItem(this.currentPrefix + 'utm_source', values.utm_source ?? '');
		sessionStorage.setItem(this.currentPrefix + 'utm_medium', values.utm_medium ?? '');
		sessionStorage.setItem(this.currentPrefix + 'utm_campaign', values.utm_campaign ?? '');
		sessionStorage.setItem(this.currentPrefix + 'landing_page', values.landing_page ?? '');
		sessionStorage.setItem(this.currentPrefix + 'referrer', values.referrer ?? '');
		sessionStorage.setItem(this.currentPrefix + 'queries', values.queries ?? '');
	}
 
	private cookiesHaveFirstValues(): boolean {
		return this.cookieService.check(this.firstPrefix + 'utm_source');
	}
 
	private setFirstValuesIfMissing(current: UTMValues) {
		const expiry = this.sixMonthsFromNow();

		this.setCookieIfMissing('utm_source', current.utm_source, expiry);
		this.setCookieIfMissing('utm_medium', current.utm_medium, expiry);
		this.setCookieIfMissing('utm_campaign', current.utm_campaign, expiry);
		this.setCookieIfMissing('landing_page', current.landing_page, expiry);
		this.setCookieIfMissing('referrer', current.referrer, expiry);
		this.setCookieIfMissing('queries', current.queries, expiry);
	}
 
	private setCookieIfMissing(keySuffix: string, value: string | null, expiry: Date) {
		const key = this.firstPrefix + keySuffix;
		if (!this.cookieService.check(key)) {
			this.cookieService.set(key, value ?? '', { expires: expiry, sameSite: 'Lax', path: '/' });
		}
	}
 
	// ================================
	// HUBSPOT PAYLOAD (UPDATED)
	// ================================
	getHubspotPayload(): any {
		if (!this.isBrowser) return {};
 
		return {
			// FIRST
			first_utm_source: this.safeCookieGet('first_utm_source'),
			first_utm_medium: this.safeCookieGet('first_utm_medium'),
			first_utm_campaign: this.safeCookieGet('first_utm_campaign'),
			first_landing_page: this.safeCookieGet('first_landing_page'),
			first_referrer: this.safeCookieGet('first_referrer'),
			first_queries: this.safeCookieGet('first_queries'),
 
			// LAST
			last_utm_source: this.safeSessionGet(this.currentPrefix + 'utm_source'),
			last_utm_medium: this.safeSessionGet(this.currentPrefix + 'utm_medium'),
			last_utm_campaign: this.safeSessionGet(this.currentPrefix + 'utm_campaign'),
			last_landing_page: this.safeSessionGet(this.currentPrefix + 'landing_page'),
			last_referrer: this.safeSessionGet(this.currentPrefix + 'referrer'),
			last_queries: this.safeSessionGet(this.currentPrefix + 'queries'),
 
			// ✅ GOOGLE ADS (NEW - NOT FIRST/CURRENT)
			...this.buildGoogleAdsValues(),
		};
	}
 
	// ================================
	// SAFE GETTERS
	// ================================
	private safeSessionGet(key: string): string | null {
		const v = sessionStorage.getItem(key);
		return v || null;
	}
 
	private safeCookieGet(key: string): string | null {
		if (!this.cookieService.check(key)) return null;
		const v = this.cookieService.get(key);
		return v || null;
	}
 
	// ================================
	// OTHER LOGIC (UNCHANGED)
	// ================================
	private captureQueriesOnce(): void {
		const key = 'session_queries';
		if (!sessionStorage.getItem(key)) {
			const q = typeof window !== 'undefined' ? window.location.search.substring(1) : '';
			if (q) sessionStorage.setItem(key, q);
		}
	}
 
	private getSessionQueries(): string | null {
		return sessionStorage.getItem('session_queries');
	}
 
	private captureLandingPageOnce(): void {
		const key = 'session_landing_page';
		if (!sessionStorage.getItem(key)) {
			const url = window.location.href.split('?')[0];
			sessionStorage.setItem(key, url);
		}
	}
 
	private getSessionLandingPage(): string | null {
		return sessionStorage.getItem('session_landing_page');
	}
 
	private captureReferrerOnce(): void {
		const key = 'session_referrer';
		if (!sessionStorage.getItem(key)) {
			const ref = document.referrer;
			if (ref && !this.isSelfReferral(ref)) {
				sessionStorage.setItem(key, new URL(ref).origin + '/');
			}
		}
	}
 
	private getSessionReferrer(): string | null {
		return sessionStorage.getItem('session_referrer');
	}
 
	private isSelfReferral(referrer: string): boolean {
		try {
			const url = new URL(referrer);
			return this.siteDomain.some((d) => url.hostname.includes(d));
		} catch {
			return false;
		}
	}
 
	private sixMonthsFromNow(): Date {
		const d = new Date();
		d.setMonth(d.getMonth() + 6);
		return d;
	}
 
	// ================================
	// DEAL TRACKING (UNCHANGED)
	// ================================
	markDealAsSubmitted(dealId: string, snapshotPayload?: object) {
		if (!this.isBrowser) return;

		const key = this.submittedDealKeyPrefix + dealId;
		if (!localStorage.getItem(key)) {
			localStorage.setItem(
				key,
				JSON.stringify({
					timestamp: new Date().toISOString(),
					payload: snapshotPayload || this.getHubspotPayload(),
				}),
			);
		}
	}
 
	isDealSubmitted(dealId: string): boolean {
		return !!localStorage.getItem(this.submittedDealKeyPrefix + dealId);
	}
}