w-funnel/src/lib/funnel/unleash/sendImpression.ts
2025-10-23 21:16:09 +02:00

126 lines
4.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
/**
* Отправляет impression событие в Google Analytics для AB теста
*
* Используется в FunnelRuntime когда экран с AB тестом становится видимым
* Автоматически предотвращает дубликаты через sessionStorage
*
* @param flag - название флага из Unleash
* @param variant - вариант который получил пользователь
*/
export function sendUnleashImpression(flag: string, variant: string | undefined) {
const timestamp = new Date().toISOString();
// Проверяем что вариант валидный
if (!variant || variant === "disabled") {
console.groupCollapsed(
`%c[GA] 🧪 AB Test Impression SKIPPED`,
'color: #9E9E9E; font-weight: bold'
);
console.log('🕐 Timestamp:', timestamp);
console.log('🏷️ Flag:', flag);
console.log('🎯 Variant:', variant);
console.log('⚠️ Reason: Invalid variant (disabled or undefined)');
console.groupEnd();
return;
}
// Проверяем что браузерное окружение
if (typeof window === "undefined") {
console.warn('[GA] 🧪 AB Test Impression SKIPPED: Not browser environment');
return;
}
// Проверяем не отправляли ли уже это событие в этой сессии
const storageKey = `unleash_impression_${flag}_${variant}`;
const alreadySent = sessionStorage.getItem(storageKey);
if (alreadySent) {
// Уже отправляли - пропускаем
console.groupCollapsed(
`%c[GA] 🧪 AB Test Impression SKIPPED (Already Sent)`,
'color: #9E9E9E; font-weight: bold'
);
console.log('🕐 Timestamp:', timestamp);
console.log('🏷️ Flag:', flag);
console.log('🎯 Variant:', variant);
console.log('💾 Storage Key:', storageKey);
console.log('⚠️ Reason: Already sent in this session');
console.log('📊 Check sessionStorage to verify');
console.groupEnd();
return;
}
// Проверяем наличие gtag
if (!window.gtag) {
console.groupCollapsed(
`%c[GA] 🧪 AB Test Impression NOT Sent`,
'color: #FF0000; font-weight: bold'
);
console.log('🕐 Timestamp:', timestamp);
console.log('🏷️ Flag:', flag);
console.log('🎯 Variant:', variant);
console.log('❌ Error: Google Analytics not available (window.gtag is undefined)');
console.log('💡 Solution: Check that GoogleAnalytics component is loaded with measurementId');
console.groupEnd();
return;
}
// Подготавливаем payload
const payload = {
app_name: "witlab-funnel",
feature: flag,
treatment: variant,
};
// Отправляем событие в Google Analytics
window.gtag("event", "experiment_impression", payload);
// Помечаем что отправили
sessionStorage.setItem(storageKey, "true");
// Детальное логирование успешной отправки
console.groupCollapsed(
`%c[GA] 🧪 AB Test Impression Event Sent`,
'color: #4285F4; font-weight: bold'
);
console.log('🕐 Timestamp:', timestamp);
console.log('🏷️ Flag:', flag);
console.log('🎯 Variant:', variant);
console.log('📦 Event Name:', 'experiment_impression');
console.log('📦 Payload:', payload);
console.log('💾 Storage Key:', storageKey);
console.log('✅ Status: Successfully sent to Google Analytics');
console.log('🔍 Verify in Network tab: Look for /g/collect requests');
console.groupEnd();
}
/**
* Очищает историю отправленных impression (для тестирования)
* В production обычно не используется
*/
export function clearUnleashImpressions() {
if (typeof window === "undefined") {
return;
}
const keysToRemove = Object.keys(sessionStorage)
.filter(key => key.startsWith("unleash_impression_"));
const timestamp = new Date().toISOString();
keysToRemove.forEach(key => sessionStorage.removeItem(key));
console.groupCollapsed(
`%c[GA] 🧪 AB Test Impressions Cleared`,
'color: #FF9800; font-weight: bold'
);
console.log('🕐 Timestamp:', timestamp);
console.log('🧹 Keys Removed:', keysToRemove.length);
console.log('📋 Removed Keys:', keysToRemove);
console.log('✅ Status: All AB test impression history cleared');
console.log('💡 New impressions will be sent on next screen view');
console.groupEnd();
}