Skip to content

Commit ff7f12a

Browse files
committed
fix: make campaign tracking order before page view tracking
1 parent cb448e4 commit ff7f12a

File tree

4 files changed

+51
-32
lines changed

4 files changed

+51
-32
lines changed

packages/analytics-browser/src/browser-client.ts

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
7676
if (isAttributionTrackingEnabled(this.config.defaultTracking)) {
7777
const attributionTrackingOptions = getAttributionTrackingConfig(this.config);
7878
this.webAttribution = new WebAttribution(attributionTrackingOptions, this, this.config);
79-
await this.webAttribution.init();
79+
//await this.webAttribution.init();
8080
}
8181

8282
// Step 3: Set session ID
@@ -85,6 +85,9 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
8585
// Default: `Date.now()`
8686
// Session ID is handled differently than device ID and user ID due to session events
8787
console.log('before set sesion id');
88+
console.log('options.sessionId : ', options.sessionId );
89+
90+
console.log('this.config.sessionId: ', this.config.sessionId);
8891
this.setSessionId(options.sessionId ?? this.config.sessionId ?? Date.now());
8992

9093
await super._init(this.config);
@@ -171,12 +174,12 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
171174
return this.config?.sessionId;
172175
}
173176

174-
setSessionId(sessionId: number) {
177+
async setSessionId(sessionId: number, shouldTrackNewCampaign?: boolean) {
175178
if (!this.config) {
176179
this.q.push(this.setSessionId.bind(this, sessionId));
177180
return;
178181
}
179-
182+
console.log(sessionId, ' ', this.config.sessionId);
180183
// Prevents starting a new session with the same session ID
181184
if (sessionId === this.config.sessionId) {
182185
return;
@@ -189,38 +192,46 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
189192
this.config.sessionId = sessionId;
190193
this.config.lastEventTime = undefined;
191194
this.config.pageCounter = 0;
192-
console.log(this.config.sessionId);
195+
console.log('the session config: ', this.config.sessionId);
196+
197+
await this.fireUtilEvent(previousSessionId, lastEventTime, lastEventId, shouldTrackNewCampaign);
198+
193199

200+
this.previousSessionDeviceId = this.config.deviceId;
201+
this.previousSessionUserId = this.config.userId;
202+
}
203+
204+
async fireUtilEvent(previousSessionId: number | undefined,lastEventTime: number | undefined, lastEventId: number , shouldTrackNewCampaign?: boolean) {
194205
if (isSessionTrackingEnabled(this.config.defaultTracking)) {
195206
if (previousSessionId && lastEventTime) {
196207
console.log('end session track');
197-
this.track(DEFAULT_SESSION_END_EVENT, undefined, {
208+
await this.track(DEFAULT_SESSION_END_EVENT, undefined, {
198209
device_id: this.previousSessionDeviceId,
199210
event_id: ++lastEventId,
200211
session_id: previousSessionId,
201212
time: lastEventTime + 1,
202213
user_id: this.previousSessionUserId,
203-
});
214+
}).promise;
204215
}
205216
this.config.lastEventTime = this.config.sessionId;
206217
}
207218

208219
// fire web attribution events
209220
console.log('last event time in setSessionId: ', this.config.lastEventTime);
210-
this.webAttribution?.track();
221+
if (await this.webAttribution?.shouldTrackNewCampaign() || shouldTrackNewCampaign) {
222+
console.log('in setsession id, should track new campaign');
223+
this.webAttribution?.track();
224+
}
211225

212226
if (isSessionTrackingEnabled(this.config.defaultTracking)) {
213227
console.log('start session track');
214-
215-
this.track(DEFAULT_SESSION_START_EVENT, undefined, {
228+
// must under await, otherwise, the case resetSessionOnNewCampaign = true and with new campaign input the order of session start will be log after the page view event
229+
await this.track(DEFAULT_SESSION_START_EVENT, undefined, {
216230
event_id: ++lastEventId,
217231
session_id: this.config.sessionId,
218232
time: this.config.lastEventTime,
219-
});
233+
}).promise;
220234
}
221-
222-
this.previousSessionDeviceId = this.config.deviceId;
223-
this.previousSessionUserId = this.config.userId;
224235
}
225236

226237
extendSession() {
@@ -276,8 +287,7 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
276287
const currentTime = Date.now();
277288
console.log('currentTime: ', currentTime);
278289
const isEventInNewSession = isNewSession(this.config.sessionTimeout, this.config.lastEventTime);
279-
await this.webAttribution?.fetchCampaign();
280-
const shouldTrackNewCampaign = this.webAttribution?.shouldTrackNewCampaign();
290+
const shouldTrackNewCampaign = await this.webAttribution?.shouldTrackNewCampaign();
281291
const shouldSetSessionId = shouldTrackNewCampaign && this.webAttribution?.options.resetSessionOnNewCampaign;
282292
console.log('isEventInNewSession: ', isEventInNewSession);
283293
console.log('shouldTrackNewCampaign: ', shouldTrackNewCampaign);
@@ -290,11 +300,11 @@ export class AmplitudeBrowser extends AmplitudeCore implements BrowserClient {
290300
) {
291301
if (isEventInNewSession || shouldSetSessionId) {
292302
console.log('setting session id');
293-
this.setSessionId(currentTime);
303+
await this.setSessionId(currentTime, shouldTrackNewCampaign);
294304
} else if (!isEventInNewSession && shouldTrackNewCampaign) {
295305
console.log('in process identify track');
296306
// web attribution should be track during the middle of the session if there has any new campaign
297-
this.webAttribution?.track();
307+
await this.webAttribution?.track().promise;
298308
}
299309
}
300310

packages/analytics-browser/src/config.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ export const useBrowserConfig = async (
215215
// Step 1: Parse cookies using identity storage instance
216216
const legacyCookies = await parseLegacyCookies(apiKey, cookieStorage, options.cookieOptions?.upgrade ?? true);
217217
const previousCookies = await cookieStorage.get(getCookieName(apiKey));
218+
console.log('privousCookies: ', previousCookies);
218219
const queryParams = getQueryParams();
219220

220221
// Step 3: Reconcile user identity
@@ -224,6 +225,7 @@ export const useBrowserConfig = async (
224225
const lastEventTime = previousCookies?.lastEventTime ?? legacyCookies.lastEventTime;
225226
const optOut = options.optOut ?? previousCookies?.optOut ?? legacyCookies.optOut;
226227
const sessionId = previousCookies?.sessionId ?? legacyCookies.sessionId;
228+
console.log('sessionid in the config: ', sessionId);
227229
const userId = options.userId ?? previousCookies?.userId ?? legacyCookies.userId;
228230
amplitudeInstance.previousSessionDeviceId = previousCookies?.deviceId ?? legacyCookies.deviceId;
229231
amplitudeInstance.previousSessionUserId = previousCookies?.userId ?? legacyCookies.userId;

packages/analytics-browser/src/utils/web-attribution.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
isNewCampaign,
99
} from './web-attribution-helper';
1010
import { CampaignParser } from '@amplitude/analytics-client-common';
11+
//import { returnWrapper } from '@amplitude/analytics-core';
1112

1213
export class WebAttribution {
1314
options: Options;
@@ -29,13 +30,13 @@ export class WebAttribution {
2930
this.storageKey = getStorageKey(config.apiKey, 'MKTG');
3031
}
3132

32-
async init() {
33-
console.log('in init');
34-
await this.fetchCampaign();
35-
}
36-
37-
shouldTrackNewCampaign() {
33+
async shouldTrackNewCampaign() {
34+
[this.currentCampaign, this.previousCampaign] = await this.fetchCampaign();
3835
console.log('in should tracknew campaign');
36+
console.log('this.currentCampaign: ', this.currentCampaign);
37+
console.log('this.previousCampaign: ', this.previousCampaign );
38+
await this.storage.set(this.storageKey, this.currentCampaign);
39+
console.log('after set storage');
3940
if (isNewCampaign(this.currentCampaign, this.previousCampaign, this.options)) {
4041
return true;
4142
}
@@ -44,7 +45,9 @@ export class WebAttribution {
4445

4546
async fetchCampaign() {
4647
console.log('in fetch campaign');
47-
[this.currentCampaign, this.previousCampaign] = await Promise.all([
48+
//[this.currentCampaign, this.previousCampaign] =
49+
50+
return await Promise.all([
4851
new CampaignParser().parse(),
4952
this.storage.get(this.storageKey),
5053
]);
@@ -57,13 +60,17 @@ export class WebAttribution {
5760
* 1. set a new session
5861
* 2. has new campaign and enable resetSessionOnNewCampaign
5962
*/
60-
track() {
61-
if (this.shouldTrackNewCampaign()) {
63+
track(){
64+
//
65+
// if (void this.shouldTrackNewCampaign()) {
6266
console.log('in web attribution track');
6367
const campaignEvent = createCampaignEvent(this.currentCampaign, this.options);
64-
this.amplitude.track(campaignEvent);
65-
console.log('after track campaignEvent');
66-
void this.storage.set(this.storageKey, this.currentCampaign);
67-
}
68+
// This must be update before track otherwise it will cause infinite loop. since shouldTrackNewCampaign will be called before the storage has been updated.
69+
// return returnWrapper(this.dispatch(event));
70+
// console.log('after track campaignEvent');
71+
// return returnWrapper(this.amplitude.dispatch(campaignEvent));
72+
// return returnWrapper(this.amplitude.dispatch(campaignEvent));
73+
return this.amplitude.track(campaignEvent);
74+
// return;
6875
}
6976
}

packages/plugin-page-view-tracking-browser/src/page-view-tracking.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export const pageViewTrackingPlugin: CreatePageViewTrackingPlugin = (options: Op
5858
if (shouldTrackPageView) {
5959
/* istanbul ignore next */
6060
loggerProvider?.log('Tracking page view event');
61-
amplitude?.track(await createPageViewEvent());
61+
await amplitude?.track(await createPageViewEvent()).promise;
6262
}
6363
};
6464

@@ -101,7 +101,7 @@ export const pageViewTrackingPlugin: CreatePageViewTrackingPlugin = (options: Op
101101
if (shouldTrackOnPageLoad()) {
102102
loggerProvider.log('Tracking page view event');
103103

104-
amplitude.track(await createPageViewEvent());
104+
await amplitude.track(await createPageViewEvent()).promise;
105105
}
106106
},
107107

0 commit comments

Comments
 (0)