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

82.77% Statements 245/296
52.38% Branches 22/42
86.95% Functions 20/23
82.77% Lines 245/296

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 2971x 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 39x 39x 39x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x     5x 5x 1x 1x 5x 5x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 5x 5x 1x 1x 5x 5x 5x 5x 15x 15x 15x 15x       15x 5x 5x 1x 1x 15x 15x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 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 1x 5x 5x 5x 5x 5x 5x 5x 5x     5x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x     5x 1x 1x 12x 12x   12x 12x     12x 1x 1x 5x 5x 5x 5x 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 1x 1x 1x                             1x 1x               1x 1x 1x 12x 12x 12x 12x     12x 1x  
/*
Angular UTM & First/Last Touch tracker with Cookies
- Service: UTMTrackerService
- Usage: call utmTracker.initOnFirstPage() on the first page of each session (e.g. AppComponent ngOnInit)
- When sending a lead to HubSpot, call utmTracker.getHubspotPayload() to get First... and Last... fields
- After creating the Deal in HubSpot, call utmTracker.markDealAsSubmitted(dealId) to prevent future updates for that deal
 
Notes:
- Uses sessionStorage for "Current..." keys
- Uses cookies (6 month expiry) for "First..." keys
- Never overwrites First values (cookie check before set)
- Works only in browser (uses isPlatformBrowser guard)
- "Referrer" is captured once per session (session_referrer) and reused.
- Ignores self-referrals using `siteDomain`
*/
 
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;
}
 
@Injectable({ providedIn: 'root' })
export class UTMTrackerService {
	// Key name factories
	private currentPrefix = 'current_';
	private firstPrefix = 'first_';
	private submittedDealKeyPrefix = 'hs_deal_submitted_';
	private cookieService = inject(CookieService);
 
	// site config (set your root domain, without www.)
	private siteDomain = ['gorealtravel.com', 'web.staging.gorealtravel.com', 'localhost'];
 
	isBrowser: boolean;
 
	constructor() {
		const platformId = inject(PLATFORM_ID);
		this.isBrowser = isPlatformBrowser(platformId);
	}
 
	// Public init to be called on the first page of each visit (session)
	initOnFirstPage(): void {
		if (!this.isBrowser) return;
 
		this.captureReferrerOnce();
		this.captureLandingPageOnce();
		this.captureQueriesOnce();
		this.captureUTMsOnce(); // ✅ NEW
 
		const current = this.buildCurrentUTMValues();
		this.setSessionValues(current);
 
		if (!this.cookiesHaveFirstValues()) {
			this.setFirstValuesIfMissing(current);
		}
	}
 
	private captureQueriesOnce(): void {
		const key = 'session_queries';
		if (!sessionStorage.getItem(key)) {
			const q =
				typeof window !== 'undefined' ? (window.location.search ? window.location.search.substring(1) : '') : null;
			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)) {
			let lp = this.getCanonical();
			if (!lp && typeof window !== 'undefined') {
				// ✅ strip query + hash
				const url = new URL(window.location.href);
				lp = url.origin + url.pathname;
			}
			if (lp) {
				sessionStorage.setItem(key, lp);
			}
		}
	}
 
	private getSessionLandingPage(): string | null {
		return sessionStorage.getItem('session_landing_page');
	}
 
	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) {
					// ✅ normalize to lowercase
					sessionStorage.setItem(sessionKey, value.toLowerCase());
				}
			}
		});
	}
 
	private getSessionUTM(key: string): string | null {
		return sessionStorage.getItem('session_' + key);
	}
 
	// Build UTM values using URL and referrer
	private buildCurrentUTMValues(): UTMValues {
		const utm_source = this.getSessionUTM('utm_source');
		const utm_medium = this.getSessionUTM('utm_medium');
		const utm_campaign = this.getSessionUTM('utm_campaign');
		const landing_page = this.getSessionLandingPage();
		const referrer = this.getSessionReferrer();
		const queries = this.getSessionQueries();
 
		return {
			utm_source,
			utm_medium,
			utm_campaign,
			landing_page,
			referrer,
			queries,
		};
	}
 
	private captureReferrerOnce(): void {
		const key = 'session_referrer';
		if (!sessionStorage.getItem(key)) {
			const ref = document?.referrer || null;
			if (ref && !this.isSelfReferral(ref)) {
				try {
					// ✅ store only hostname (or origin if you prefer)
					const url = new URL(ref);
					sessionStorage.setItem(key, url.origin + '/'); // matches your spec format
				} catch {
					sessionStorage.setItem(key, ref);
				}
			}
		}
	}
 
	private getSessionReferrer(): string | null {
		return sessionStorage.getItem('session_referrer');
	}
 
	// Check if referrer is internal (self-referral)
	private isSelfReferral(referrer: string): boolean {
		try {
			const url = new URL(referrer);
			// check if referrer hostname matches any of the domains in the array
			return this.siteDomain.some((domain) => url.hostname.includes(domain));
		} catch {
			return false;
		}
	}
 
	// Get canonical URL if present
	private getCanonical(): string | null {
		if (typeof document === 'undefined') return null;
		const el = document.querySelector('link[rel="canonical"]') as HTMLLinkElement | null;
		return el?.href || null;
	}
 
	// Session storage helpers
	private setSessionValues(values: UTMValues) {
		try {
			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 ?? '');
		} catch (e) {
			console.warn('UTMTracker: failed to set session values', e);
		}
	}
 
	// Cookie helpers for First values
	private cookiesHaveFirstValues(): boolean {
		try {
			return this.cookieService.check(this.firstPrefix + 'utm_source');
		} catch {
			return false;
		}
	}
 
	private setFirstValuesIfMissing(current: UTMValues) {
		const expiry = this.sixMonthsFromNow();
		try {
			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);
		} catch (e) {
			console.warn('UTMTracker: failed to set first values', e);
		}
	}
 
	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: '/' });
		}
	}
 
	private safeCookieGet(key: string): string | null {
		try {
			if (!this.cookieService.check(key)) return null;
			const v = this.cookieService.get(key);
			return v === '' ? null : v;
		} catch {
			return null;
		}
	}
 
	private sixMonthsFromNow(): Date {
		const d = new Date();
		d.setMonth(d.getMonth() + 6);
		return d;
	}
 
	// Public getter to prepare HubSpot payload
	getHubspotPayload(): { [key: string]: string | null } {
		if (!this.isBrowser) return {};
 
		const payload: { [key: string]: string | null } = {};
 
		// First values from cookies
		payload['first_utm_source'] = this.safeCookieGet(this.firstPrefix + 'utm_source');
		payload['first_utm_medium'] = this.safeCookieGet(this.firstPrefix + 'utm_medium');
		payload['first_utm_campaign'] = this.safeCookieGet(this.firstPrefix + 'utm_campaign');
		payload['first_landing_page'] = this.safeCookieGet(this.firstPrefix + 'landing_page');
		payload['first_referrer'] = this.safeCookieGet(this.firstPrefix + 'referrer');
		payload['first_queries'] = this.safeCookieGet(this.firstPrefix + 'queries');
 
		// Last values = current session values
		payload['last_utm_source'] = this.safeSessionGet(this.currentPrefix + 'utm_source');
		payload['last_utm_medium'] = this.safeSessionGet(this.currentPrefix + 'utm_medium');
		payload['last_utm_campaign'] = this.safeSessionGet(this.currentPrefix + 'utm_campaign');
		payload['last_landing_page'] = this.safeSessionGet(this.currentPrefix + 'landing_page');
		payload['last_referrer'] = this.safeSessionGet(this.currentPrefix + 'referrer');
		payload['last_queries'] = this.safeSessionGet(this.currentPrefix + 'queries');
 
		return payload;
	}
 
	// Deal submission logic: mark deals as submitted
	markDealAsSubmitted(dealId: string, snapshotPayload?: object) {
		if (!this.isBrowser) return;
		try {
			const key = this.submittedDealKeyPrefix + dealId;
			if (!localStorage.getItem(key)) {
				const meta = {
					timestamp: new Date().toISOString(),
					payload: snapshotPayload || this.getHubspotPayload(),
				};
				localStorage.setItem(key, JSON.stringify(meta));
			}
		} catch (e) {
			console.warn('UTMTracker: markDealAsSubmitted failed', e);
		}
	}
 
	isDealSubmitted(dealId: string): boolean {
		if (!this.isBrowser) return false;
		try {
			return !!localStorage.getItem(this.submittedDealKeyPrefix + dealId);
		} catch {
			return false;
		}
	}
 
	// Safe session getter
	private safeSessionGet(key: string): string | null {
		try {
			const v = sessionStorage.getItem(key);
			return v === null || v === '' ? null : v;
		} catch {
			return null;
		}
	}
}