-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtemplate.js
More file actions
242 lines (218 loc) · 7.42 KB
/
Copy pathtemplate.js
File metadata and controls
242 lines (218 loc) · 7.42 KB
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
const getAllEventData = require('getAllEventData');
const getCookieValues = require('getCookieValues');
const getRequestHeader = require('getRequestHeader');
const getType = require('getType');
const JSON = require('JSON');
const logToConsole = require('logToConsole');
const makeTableMap = require('makeTableMap');
const sendHttpRequest = require('sendHttpRequest');
const setCookie = require('setCookie');
/*==============================================================================
==============================================================================*/
const eventData = getAllEventData();
if (shouldExitEarly(data, eventData)) return;
// Fallback to V2, which is the one being used in the Gallery when this change was made.
const API_VERSION = data.apiVersion || 'v2';
let email = data.email;
if (data.storeEmail) {
if (!email) email = getCookieValues('brevo_email')[0];
else storeCookie('email', email);
}
switch (data.type) {
case 'trackPage':
sendEvent('page_view', formatEventPayloadByApiVersion('trackPage'));
break;
case 'trackEvent':
sendEvent(data.event, formatEventPayloadByApiVersion('trackEvent'));
break;
case 'trackLink':
sendEvent('link', formatEventPayloadByApiVersion('trackLink'));
break;
case 'identify':
sendEvent('identify', formatEventPayloadByApiVersion('identify'));
break;
default:
return data.gtmOnFailure();
}
/*==============================================================================
Vendor related functions
==============================================================================*/
function sendEvent(eventName, brevoEventData) {
if (areThereRequiredFieldsMissing(brevoEventData)) {
log({
Name: 'Brevo',
Type: 'Message',
EventName: eventName,
Message: '🛑 [ERROR] Request was not sent. API ' + API_VERSION,
Reason: 'One or more fields are missing: v2: Email; v3: Email, Phone Number or External ID.'
});
return data.gtmOnFailure();
}
const url = getRequestUrl();
sendHttpRequest(
url,
(statusCode, headers, body) => {
if (!data.useOptimisticScenario) {
if (statusCode >= 200 && statusCode < 300) return data.gtmOnSuccess();
return data.gtmOnFailure();
}
},
{
headers: getRequestHeaders(),
method: 'POST'
},
JSON.stringify(brevoEventData)
);
if (data.useOptimisticScenario) return data.gtmOnSuccess();
}
function formatEventPayloadByApiVersion(event) {
const eventPayloadByApiVersion = {
v2: {
trackPage: () => ({
properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
email: email,
page: data.page
}),
trackEvent: () => ({
properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
eventData: data.propertiesEvent ? makeTableMap(data.propertiesEvent, 'name', 'value') : {},
email: email,
event: data.event
}),
trackLink: () => ({
properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
email: email,
link: data.link
}),
identify: () => ({
attributes: data.customerProperties
? makeTableMap(data.customerProperties, 'name', 'value')
: {},
email: email
})
},
v3: {
trackPage: () => ({
event_name: 'page_view',
identifiers: mergeObj(
{ email_id: email },
data.customerIdentifiers ? makeTableMap(data.customerIdentifiers, 'name', 'value') : {}
),
event_properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
page: data.page
}),
trackEvent: () => ({
event_name: data.event,
identifiers: mergeObj(
{ email_id: email },
data.customerIdentifiers ? makeTableMap(data.customerIdentifiers, 'name', 'value') : {}
),
contact_properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
event_properties: data.propertiesEvent
? makeTableMap(data.propertiesEvent, 'name', 'value')
: {}
}),
trackLink: () => ({
event_name: 'link',
identifiers: mergeObj(
{ email_id: email },
data.customerIdentifiers ? makeTableMap(data.customerIdentifiers, 'name', 'value') : {}
),
event_properties: data.properties ? makeTableMap(data.properties, 'name', 'value') : {},
link: data.link
}),
identify: () => ({
event_name: 'identify',
identifiers: mergeObj(
{ email_id: email },
data.customerIdentifiers ? makeTableMap(data.customerIdentifiers, 'name', 'value') : {}
),
contact_properties: data.customerProperties
? makeTableMap(data.customerProperties, 'name', 'value')
: {}
})
}
};
return eventPayloadByApiVersion[API_VERSION][event]();
}
function areThereRequiredFieldsMissing(brevoEventData) {
const requiredFieldsValidationByApiVersion = {
v2: () => {
if (!isValidValue(brevoEventData.email)) return true;
return false;
},
v3: () => {
const doesNotHaveValidIdentifier = ['email_id', 'phone_id', 'ext_id'].every(
(p) => !isValidValue(brevoEventData.identifiers[p])
);
if (doesNotHaveValidIdentifier) return true;
return false;
}
};
return requiredFieldsValidationByApiVersion[API_VERSION]();
}
function getRequestUrl() {
const baseUrlByApiVersion = {
v2: 'https://in-automate.brevo.com/api/v2/' + data.type,
v3: 'https://api.brevo.com/v3/events'
};
return baseUrlByApiVersion[API_VERSION];
}
function getRequestHeaders() {
const baseHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
const headersByApiVersion = {
v2: { 'ma-key': data.clientKey },
v3: { 'api-key': data.clientKey }
};
return mergeObj(baseHeaders, headersByApiVersion[API_VERSION]);
}
function storeCookie(name, value) {
setCookie('brevo_' + name, value, {
domain: 'auto',
path: '/',
samesite: 'Lax',
secure: true,
'max-age': 63072000, // 2 years
httpOnly: false
});
}
/*==============================================================================
Helpers
==============================================================================*/
function getUrl(eventData) {
return eventData.page_location || getRequestHeader('referer') || eventData.page_referrer;
}
function shouldExitEarly(data, eventData) {
if (!isConsentGivenOrNotRequired(data, eventData)) {
data.gtmOnSuccess();
return true;
}
const url = getUrl(eventData);
if (url && url.lastIndexOf('https://gtm-msr.appspot.com/', 0) === 0) {
data.gtmOnSuccess();
return true;
}
}
function isValidValue(value) {
const valueType = getType(value);
return valueType !== 'null' && valueType !== 'undefined' && value !== '' && value === value;
}
function mergeObj(target, source) {
for (const key in source) {
if (source.hasOwnProperty(key)) target[key] = source[key];
}
return target;
}
function isConsentGivenOrNotRequired(data, eventData) {
if (data.adStorageConsent !== 'required') return true;
if (eventData.consent_state) return !!eventData.consent_state.ad_storage;
const xGaGcs = eventData['x-ga-gcs'] || ''; // x-ga-gcs is a string like "G110"
return xGaGcs[2] === '1';
}
function log(rawDataToLog) {
rawDataToLog.TraceId = getRequestHeader('trace-id');
logToConsole(JSON.stringify(rawDataToLog));
}