Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 16 additions & 35 deletions packages/sui-segment-wrapper/src/repositories/googleRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {EVENTS} from '../events.js'
import {utils} from '../middlewares/source/pageReferrer.js'

const FIELDS = {
clientId: 'client_id',
sessionId: 'session_id'
clientId: 'clientId',
sessionId: 'sessionId'
}

export const DEFAULT_DATA_LAYER_NAME = 'dataLayer'
Expand Down Expand Up @@ -72,45 +72,32 @@ export const loadGoogleAnalytics = async () => {
}

// Trigger GA init event just once per session.
const triggerGoogleAnalyticsInitEvent = sessionId => {
export const triggerGoogleAnalyticsInitEvent = async () => {
const eventName = getConfig('googleAnalyticsInitEvent') ?? DEFAULT_GA_INIT_EVENT
const eventPrefix = `ga_event_${eventName}_`
const eventKey = `${eventPrefix}${sessionId}`
let sessionId, isNewSession

if (typeof window.gtag === 'undefined') return

try {
;({sessionId, isNewSession} = (await window.__mpi.segmentWrapper.gaDataPromise) || {})
} catch (error) {
// eslint-disable-next-line no-console
console.log('Error retrieving GA session data:', error)

return
}

// Check if the event has already been sent in this session.
if (!localStorage.getItem(eventKey)) {
if (isNewSession && sessionId) {
// If not, send it.
window.gtag('event', eventName)

// eslint-disable-next-line no-console
console.log(`Sending GA4 event "${eventName}" for the session "${sessionId}"`)

// And then save a new GA session hit in local storage.
localStorage.setItem(eventKey, 'true')
dispatchEvent({eventName: EVENTS.GA4_INIT_EVENT_SENT, detail: {eventName, sessionId}})
}

// Clean old GA sessions hits from the storage.
Object.keys(localStorage).forEach(key => {
if (key.startsWith(eventPrefix) && key !== eventKey) {
localStorage.removeItem(key)
}
})
}

const getGoogleField = async field => {
const googleAnalyticsMeasurementId = getConfig('googleAnalyticsMeasurementId')

// If `googleAnalyticsMeasurementId` is not present, don't load anything.
if (!googleAnalyticsMeasurementId) return Promise.resolve()

return new Promise(resolve => {
// If it is, get it from `gtag`.
window.gtag?.('get', googleAnalyticsMeasurementId, field, resolve)
})
}
const getGoogleField = async field => window.__mpi.segmentWrapper.gaDataPromise?.then(gaData => gaData[field])

export const trackingTagsTypes = {
STC: 'stc',
Expand Down Expand Up @@ -184,13 +171,7 @@ function readFromUtm(searchParams) {
}

export const getGoogleClientId = async () => getGoogleField(FIELDS.clientId)
export const getGoogleSessionId = async () => {
const sessionId = await getGoogleField(FIELDS.sessionId)

triggerGoogleAnalyticsInitEvent(sessionId)

return sessionId
}
export const getGoogleSessionId = async () => getGoogleField(FIELDS.sessionId)

// Unified consent state getter.
// Returns GRANTED, DENIED or undefined (default / unknown / unavailable).
Expand Down
5 changes: 4 additions & 1 deletion packages/sui-segment-wrapper/src/segmentWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
getGoogleClientId,
getGoogleSessionId,
setGoogleUserId,
sendGoogleConsents
sendGoogleConsents,
triggerGoogleAnalyticsInitEvent
} from './repositories/googleRepository.js'
import {getXandrId} from './repositories/xandrRepository.js'
import {getConfig} from './config.js'
Expand Down Expand Up @@ -70,6 +71,8 @@ const getTrackIntegrations = async ({gdprPrivacyValue, event}) => {
console.error(error)
}

triggerGoogleAnalyticsInitEvent()

const restOfIntegrations = getRestOfIntegrations({isGdprAccepted, event})

// If we don't have the user consents we remove all the integrations but Adobe Analytics nor GA4
Expand Down
5 changes: 4 additions & 1 deletion packages/sui-segment-wrapper/test/segmentWrapperSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,10 @@ describe('Segment Wrapper', function () {
const integrations = {
All: false,
'Adobe Analytics': true,
'Google Analytics 4': true,
'Google Analytics 4': {
clientId: 'fakeClientId',
sessionId: 'fakeSessionId'
},
Personas: false,
Webhooks: true,
Webhook: true
Expand Down
11 changes: 9 additions & 2 deletions packages/sui-segment-wrapper/test/stubs.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export const stubFetch = ({responses = [{urlRe: /^http/, fetchResponse: {}}]} =

export const stubGoogleAnalytics = () => {
const fakeFields = {
client_id: 'fakeClientId',
session_id: 'fakeSessionId'
clientId: 'fakeClientId',
sessionId: 'fakeSessionId'
}

window.gtag = (key, id, field, done) => {
Expand All @@ -57,6 +57,13 @@ export const stubGoogleAnalytics = () => {
fakeFields[id] = field
}
}

window.__mpi = window.__mpi || {}
window.__mpi.segmentWrapper = window.__mpi.segmentWrapper || {}
window.__mpi.segmentWrapper.gaDataPromise = Promise.resolve({
clientId: fakeFields.clientId,
sessionId: fakeFields.sessionId
})
}

export const stubWindowObjects = ({borosMock = true, borosSuccess = true, isDmpAccepted = true} = {}) => {
Expand Down
Loading