-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdata-layer.ts
More file actions
418 lines (373 loc) · 13 KB
/
Copy pathdata-layer.ts
File metadata and controls
418 lines (373 loc) · 13 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// DataLayer: singleton helper for pushing structured analytics events/vars to window.dataLayer.
// On load it emits one aggregated event `pageJsonVariablesReady` with:
// EN_PAGEJSON_* (normalized pageJson), EN_URLPARAM_*, EN_RECURRING_FREQUENCIES (donation pages),
// and EN_SUBMISSION_SUCCESS_{PAGETYPE} when on the final page.
// User actions emit: EN_FORM_VALUE_UPDATED (field changes) and submission opt‑in/out events.
// Queued end‑of‑gift events/variables (via addEndOfGiftProcessEvent / addEndOfGiftProcessVariable)
// are replayed after a successful gift process load.
// Sensitive payment/bank fields are excluded; selected PII fields are Base64 “hashed” (btoa — not cryptographic).
// Replace with a real hash (e.g., SHA‑256) if required.
import { EngridLogger, ENGrid, EnForm, RememberMeEvents } from ".";
export class DataLayer {
private logger: EngridLogger = new EngridLogger(
"DataLayer",
"#f1e5bc",
"#009cdc",
"📊"
);
private dataLayer = (window as any).dataLayer || [];
private _form: EnForm = EnForm.getInstance();
private static instance: DataLayer;
private encoder = new TextEncoder();
private endOfGiftProcessStorageKey = "ENGRID_END_OF_GIFT_PROCESS_EVENTS";
// pageJson entries related to the gift process
private giftFields = [
"amount",
"currency",
"donationLogId",
"feeCover",
"giftProcess",
"paymentType",
"receiptNumber",
"recurring",
"transactionId",
"transactionType",
];
private excludedFields = [
// Credit Card
"transaction.ccnumber",
"transaction.ccexpire.delimiter",
"transaction.ccexpire",
"transaction.ccvv",
"supporter.creditCardHolderName",
// Bank Account
"supporter.bankAccountNumber",
"supporter.bankAccountType",
"transaction.bankname",
"supporter.bankRoutingNumber",
];
private hashedFields = [
// Supporter Address, Phone Numbers, and Address
"supporter.emailAddress",
"supporter.phoneNumber",
"supporter.phoneNumber2",
"supporter.address1",
"supporter.address2",
"supporter.address3",
// In Honor/Memory Inform Email and Address
"transaction.infemail",
"transaction.infadd1",
"transaction.infadd2",
"transaction.infadd3",
// Billing Address
"supporter.billingAddress1",
"supporter.billingAddress2",
"supporter.billingAddress3",
];
private retainedEmailField = "supporter.emailAddress";
private retainedAddressFields = [
"supporter.address1",
"supporter.address2",
"supporter.address3",
];
private retainedPhoneFields = [
"supporter.phoneNumber2",
"supporter.phoneNumber",
];
constructor() {
if (ENGrid.getOption("RememberMe")) {
RememberMeEvents.getInstance().onLoad.subscribe((hasData) => {
this.logger.log("Remember me - onLoad", hasData);
this.onLoad();
});
} else {
this.onLoad();
}
this._form.onSubmit.subscribe(() => this.onSubmit());
}
public static getInstance(): DataLayer {
if (!DataLayer.instance) {
DataLayer.instance = new DataLayer();
(window as any)._dataLayer = DataLayer.instance;
}
return DataLayer.instance;
}
private transformJSON(value: any) {
if (typeof value === "string") {
return value
.toUpperCase()
.trim()
.replace(/\s+/g, "-")
.replace(/:-/g, "-");
}
if (typeof value === "boolean") {
return value ? "TRUE" : "FALSE";
}
if (typeof value === "number") {
return value; // Preserve numeric type for analytics platforms that infer number vs string
}
return "";
}
private onLoad() {
// Collect all data layer variables to push at once
const dataLayerData: { [key: string]: any } = {};
const suppressEcardData =
ENGrid.getPageType() === "ECARD" &&
ENGrid.getOption("SuppressPurchaseEcard");
if (ENGrid.getGiftProcess()) {
// EN will chain together gift process data on the page json when redirecting from a completed donation to an ecard.
// Since the ecard page can be embedded on the thank you page of a donation, this can cause confusion in the data layer with events
// firing for both the donation and the ecard on the same page.
if (suppressEcardData) {
this.logger.log(
"⛔ Gift process was detected BUT suppressing EN_SUCCESSFUL_DONATION event due to SuppressPurchaseEcard option enabled"
);
window.sessionStorage.removeItem(this.endOfGiftProcessStorageKey);
} else {
this.logger.log("EN_SUCCESSFUL_DONATION");
this.addEndOfGiftProcessEventsToDataLayer();
}
}
if (window.pageJson) {
const pageJson = window.pageJson as Record<string, any>;
for (const property in pageJson) {
if (suppressEcardData && this.giftFields.includes(property)) {
continue;
}
const key = `EN_PAGEJSON_${property.toUpperCase()}`;
const value = pageJson[property];
dataLayerData[key] = this.transformJSON(value);
}
if (ENGrid.getPageCount() === ENGrid.getPageNumber()) {
dataLayerData[
`EN_SUBMISSION_SUCCESS_${pageJson.pageType.toUpperCase()}`
] = "TRUE";
}
}
const urlParams = new URLSearchParams(window.location.search);
urlParams.forEach((value, key) => {
dataLayerData[`EN_URLPARAM_${key.toUpperCase()}`] =
this.transformJSON(value);
});
this.addRetainedHashesToDataLayer(dataLayerData);
if (ENGrid.getPageType() === "DONATION") {
const recurrFreqEls = document.querySelectorAll(
'[name="transaction.recurrfreq"]'
) as NodeListOf<HTMLInputElement>;
const recurrValues = [...recurrFreqEls].map((el) => el.value);
dataLayerData[`EN_RECURRING_FREQUENCIES`] = recurrValues;
}
// Push all collected variables at once
if (Object.keys(dataLayerData).length > 0) {
dataLayerData.event = "pageJsonVariablesReady";
this.dataLayer.push(dataLayerData);
}
this.attachEventListeners();
}
private addRetainedHashesToDataLayer(
dataLayerData: Record<string, any>
): void {
if (typeof window === "undefined" || !window.localStorage) {
return;
}
["EMAIL", "ADDRESS", "PHONE"].forEach((suffix) => {
const storageKey = `EN_HASH_${suffix}`;
const storedValue = window.localStorage.getItem(storageKey);
if (storedValue) {
dataLayerData[storageKey] = storedValue;
}
});
}
private onSubmit() {
const optIn = document.querySelector(
".en__field__item:not(.en__field--question) input[name^='supporter.questions'][type='checkbox']:checked"
);
if (optIn) {
this.logger.log("EN_SUBMISSION_WITH_EMAIL_OPTIN");
this.dataLayer.push({
event: "EN_SUBMISSION_WITH_EMAIL_OPTIN",
});
} else {
this.logger.log("EN_SUBMISSION_WITHOUT_EMAIL_OPTIN");
this.dataLayer.push({
event: "EN_SUBMISSION_WITHOUT_EMAIL_OPTIN",
});
}
}
private attachEventListeners() {
const textInputs = document.querySelectorAll(
".en__component--advrow input:not([type=checkbox]):not([type=radio]):not([type=submit]):not([type=button]):not([type=hidden]):not([unhidden]), .en__component--advrow textarea"
) as NodeListOf<HTMLInputElement>;
textInputs.forEach((el) => {
el.addEventListener("blur", (e) => {
this.handleFieldValueChange(e.target as HTMLInputElement);
});
});
const radioAndCheckboxInputs = document.querySelectorAll(
".en__component--advrow input[type=checkbox], .en__component--advrow input[type=radio]"
) as NodeListOf<HTMLInputElement>;
radioAndCheckboxInputs.forEach((el) => {
el.addEventListener("change", (e) => {
this.handleFieldValueChange(e.target as HTMLInputElement);
});
});
const selectInputs = document.querySelectorAll(
".en__component--advrow select"
) as NodeListOf<HTMLInputElement>;
selectInputs.forEach((el) => {
el.addEventListener("change", (e) => {
this.handleFieldValueChange(e.target as HTMLInputElement);
});
});
}
private async handleFieldValueChange(
el: HTMLInputElement | HTMLSelectElement
) {
if (el.value === "" || this.excludedFields.includes(el.name)) return;
const value = this.hashedFields.includes(el.name)
? await this.hash(el.value)
: el.value;
if (["checkbox", "radio"].includes(el.type)) {
if ((el as HTMLInputElement).checked) {
if (el.name === "en__pg") {
//Premium gift handling
this.dataLayer.push({
event: "EN_FORM_VALUE_UPDATED",
enFieldName: el.name,
enFieldLabel: "Premium Gift",
enFieldValue: el
.closest(".en__pg__body")
?.querySelector(".en__pg__name")?.textContent,
enProductId: (
document.querySelector(
'[name="transaction.selprodvariantid"]'
) as HTMLInputElement
)?.value,
});
} else {
this.dataLayer.push({
event: "EN_FORM_VALUE_UPDATED",
enFieldName: el.name,
enFieldLabel: this.getFieldLabel(el),
enFieldValue: value,
});
}
}
return;
}
if (el.name === this.retainedEmailField) {
const retainedEmailValue = this.geRetainedFieldsValue("email");
const sha256value = await this.hash(retainedEmailValue);
localStorage.setItem(`EN_HASH_EMAIL`, sha256value);
this.dataLayer.push({
event: "EN_HASH_VALUE_UPDATED",
enFieldName: "email",
enFieldLabel: this.getFieldLabel(el),
enFieldValue: sha256value,
});
return;
} else if (this.retainedAddressFields.includes(el.name)) {
const retainedAddressValue = this.geRetainedFieldsValue("address");
const sha256value = await this.hash(retainedAddressValue);
localStorage.setItem(`EN_HASH_ADDRESS`, sha256value);
this.dataLayer.push({
event: "EN_HASH_VALUE_UPDATED",
enFieldName: "address",
enFieldLabel: "Supporter Address",
enFieldValue: sha256value,
});
} else if (this.retainedPhoneFields.includes(el.name)) {
const retainedPhoneValue = this.geRetainedFieldsValue("phone");
const sha256value = await this.hash(retainedPhoneValue);
localStorage.setItem(`EN_HASH_PHONE`, sha256value);
this.dataLayer.push({
event: "EN_HASH_VALUE_UPDATED",
enFieldName: "phone",
enFieldLabel: "Supporter Phone",
enFieldValue: sha256value,
});
}
this.dataLayer.push({
event: "EN_FORM_VALUE_UPDATED",
enFieldName: el.name,
enFieldLabel: this.getFieldLabel(el),
enFieldValue: value,
});
}
private geRetainedFieldsValue(kind: "email" | "address" | "phone"): string {
switch (kind) {
case "email":
return ENGrid.getFieldValue(this.retainedEmailField);
case "address":
return this.retainedAddressFields
.map((field) => ENGrid.getFieldValue(field))
.filter((value) => value !== "")
.join("")
.toLocaleLowerCase()
.replace(/\s+/g, "");
case "phone":
// Only return the first phone number found - prioritize phoneNumber2 over phoneNumber and remove non-numeric characters
for (const field of this.retainedPhoneFields) {
const value = ENGrid.getFieldValue(field);
if (value !== "") {
return value.replace(/\D/g, "");
}
}
return "";
default:
return "";
}
}
private async hash(value: string): Promise<string> {
const data = this.encoder.encode(value);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hashBuffer))
.map((byte) => {
const hex = byte.toString(16);
return hex.length === 1 ? "0" + hex : hex;
})
.join("");
}
private getFieldLabel(
el: HTMLInputElement | HTMLSelectElement
): string | null {
return el.closest(".en__field")?.querySelector("label")?.textContent || "";
}
public addEndOfGiftProcessEvent(
eventName: string,
eventProperties: object = {}
) {
this.storeEndOfGiftProcessData({
event: eventName,
...eventProperties,
});
}
public addEndOfGiftProcessVariable(
variableName: string,
variableValue: any = ""
) {
this.storeEndOfGiftProcessData({
[variableName.toUpperCase()]: variableValue,
});
}
private storeEndOfGiftProcessData(data: object) {
const events = this.getEndOfGiftProcessData();
events.push(data);
window.sessionStorage.setItem(
this.endOfGiftProcessStorageKey,
JSON.stringify(events)
);
}
private addEndOfGiftProcessEventsToDataLayer() {
this.getEndOfGiftProcessData().forEach((event: object) => {
this.dataLayer.push(event);
});
window.sessionStorage.removeItem(this.endOfGiftProcessStorageKey);
}
private getEndOfGiftProcessData(): Array<any> {
let eventsData = window.sessionStorage.getItem(
this.endOfGiftProcessStorageKey
);
return !eventsData ? [] : JSON.parse(eventsData);
}
}