-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1680 lines (1435 loc) · 62.3 KB
/
script.js
File metadata and controls
1680 lines (1435 loc) · 62.3 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Add near the top with other variable declarations
const adminUsers = [
{
userId: "admin_01234",
firstName: "Sarah",
lastName: "Anderson",
adminEmail: "sarah-anderson@admin.com"
},
{
userId: "admin_56789",
firstName: "Michael",
lastName: "Chen",
adminEmail: "michael.chen@admin.com"
},
{
userId: "admin_abcde",
firstName: "Jessica",
lastName: "Taylor",
adminEmail: "jessica-taylor@admin.com"
},
{
userId: "admin_fghij",
firstName: "David",
lastName: "Rodriguez",
adminEmail: "david_rodriguez@admin.com"
},
{
userId: "admin_klmno",
firstName: "Emma",
lastName: "Phillips",
adminEmail: "emma.phillips@admin.com"
}
];
let currentAdminUser = adminUsers[Math.floor(Math.random() * adminUsers.length)];
// Update the adminState object to include more details
let adminState = {
isEnabled: false,
currentAdmin: null,
originalContext: null,
originalUserId: null,
originalAnonymousId: null,
originalTraits: null
};
// async function handleAdminToggle(event) {
// adminState.isEnabled = event.target.checked;
// if (adminState.isEnabled) {
// try {
// // Get current client data before reset
// const clientData = await getClientData();
// // Store original state
// adminState.currentAdmin = currentAdminUser;
// adminState.originalContext = clientData.context;
// adminState.originalUserId = clientData.clientUserId;
// adminState.originalAnonymousId = clientData.clientAnonymousId;
// adminState.originalTraits = clientData.traits;
// console.log('Admin mode activated:', adminState.currentAdmin);
// // Disable client-side event buttons
// document.querySelectorAll('.client-side-events button').forEach(btn => {
// btn.disabled = true;
// btn.style.opacity = '0.5';
// btn.style.cursor = 'not-allowed';
// });
// // update client-side card to appear disabled
// // document.getElementsByClassName('client-side-events').style.backgroundColor = `#eee`;
// document.getElementById('client-side-events').classList.add('not-allowed');
// document.getElementById('admin-label').style.color = '#dc3545'; // Explicitly set color
// document.getElementById('admin-label').classList.remove('hidden');
// // #admin-toggle .enabled
// document.getElementById('admin-toggle').classList.add('enabled');
// document.getElementById('admin-user-info').classList.remove('hidden');
// document.getElementById('admin-userId-span').innerText = `${currentAdminUser.userId}`;
// document.getElementById('admin-email-span').innerText = `${currentAdminUser.adminEmail}`;
// document.getElementById('admin-firstName-span').innerText = `${currentAdminUser.firstName}`;
// document.getElementById('admin-lastName-span').innerText = `${currentAdminUser.lastName}`;
// // Change instructions
// document.querySelector('.instructions').innerHTML = `
// <p><strong>ADMIN MODE ACTIVE</strong></p>
// <p>1. You are now impersonating a user as an admin.</p>
// <p>2. Click the Generate User Data button to create a user to impersonate.</p>
// <p>3. Only Server-Side events are enabled for admin users.</p>
// <p>4. All server events will include your admin information sent in the event's context.admin object.</p>
// <p>5. Click any button under Server Event Triggers to have that event triggered on the server.</p>
// <p>6. Review the event requests under Server Side Segment Requests, click on them to reveal the payload.</p>
// `;
// // Reset user data last to avoid page reload issues
// cookieReset();
// console.log(`Logged in as Admin: ${currentAdminUser.firstName} ${currentAdminUser.lastName}`);
// } catch (error) {
// console.error('Error activating admin mode:', error);
// event.target.checked = false;
// adminState.isEnabled = false;
// }
// } else {
// // Enable client-side event buttons
// document.querySelectorAll('.client-side-events button').forEach(btn => {
// btn.disabled = false;
// btn.style.opacity = '1';
// btn.style.cursor = 'pointer';
// });
// document.getElementById('client-side-events').classList.remove('not-allowed');
// // Clear admin state
// adminState.currentAdmin = null;
// adminState.originalContext = null;
// adminState.originalUserId = null;
// adminState.originalAnonymousId = null;
// adminState.originalTraits = null;
// document.getElementById('admin-user-info').classList.add('hidden');
// document.getElementById('admin-userId-span').innerText = ``;
// document.getElementById('admin-email-span').innerText = ``;
// document.getElementById('admin-firstName-span').innerText = ``;
// document.getElementById('admin-lastName-span').innerText = ``;
// // Restore original instructions
// document.querySelector('.instructions').innerHTML = `
// <p>1. Click the Generate User Data button to create user traits and a userId.</p>
// <p>2. Click any button under Client Event Triggers to have that event triggered on the client.</p>
// <p>3. Click any button under Server Event Triggers to have that event triggered on the server.</p>
// <p>4. Review the event requests under Segment Requests, click on them to reveal the payload.</p>
// <p>5. You can also manually complete the User Form with customized data. The Submit button triggers an Identify event and a Track event 'Form Submitted' with the form's data.</p>
// `;
// // Hide admin info
// document.getElementById('admin-label').style.color = '#6b7280'; // Reset color
// document.getElementById('admin-user-info').classList.add('hidden');
// // Enable client-side event buttons
// document.querySelectorAll('.client-side-events button').forEach(btn => {
// btn.disabled = false;
// btn.style.opacity = '1';
// btn.style.cursor = 'pointer';
// });
// // Reset cookies to clear any admin state
// cookieReset();
// window.location.reload();
// }
// }
// UPDATES COOKIE ON CLICK OR NEW VALUE
// const cookieClick = (cookieType, cookieValue) => {
// cookieType === 'userId' ? document.getElementById('userId').innerText = `userId : ${JSON.stringify(cookieValue)}` : ''
// cookieType === 'anonymousId' ? document.getElementById('anonymousId').innerText = `anonymousId : ${JSON.stringify(cookieValue)}` : ''
// cookieType === 'userTraits' ? document.getElementById('userTraits').innerText = `traits : ${JSON.stringify(cookieValue)}` : ''
// }
// // RESETS ALL COOKIES AND RELOADS THE PAGE
// const cookieReset = async () => {
// try {
// // Get the current anonymousId before reset
// const currentAnonymousId = analytics.user().anonymousId();
// // Reset client-side analytics
// analytics.reset();
// // Clear UI elements
// document.getElementById('userId').innerText = 'userId : ';
// document.getElementById('anonymousId').innerText = 'anonymousId : ';
// document.getElementById('userTraits').innerText = 'userTraits : ';
// // Clear local variables
// userId = '';
// anonymousId = '';
// userTraits = {};
// firstName = '';
// lastName = '';
// username = '';
// phone = '';
// street = '';
// city = '';
// state = '';
// zipcode = '';
// email = '';
// // Call server reset endpoint
// const response = await fetch('http://localhost:4100/api/reset', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// anonymousId: currentAnonymousId
// })
// });
// if (!response.ok) {
// throw new Error(`Server reset failed: ${response.statusText}`);
// }
// const result = await response.json();
// console.log('Server reset result:', result);
// // Clear any local storage items if they currently have values
// localStorage.removeItem('userId');
// localStorage.removeItem('anonymousId');
// localStorage.removeItem('groupId');
// localStorage.removeItem('userTraits');
// localStorage.removeItem('groupTraits');
// // Optional: Clear all segment-related local storage items
// Object.keys(localStorage).forEach(key => {
// if (key.startsWith('ajs_') || key.startsWith('seg_')) {
// localStorage.removeItem(key);
// }
// });
// // Reload the page to simulate a new session
// // Only reload if not in admin mode
// if (!adminState.isEnabled) {
// window.location.reload();
// } else {
// // For admin mode, just clear the displayed user data
// document.getElementById('firstName-span').innerHTML = '';
// document.getElementById('lastName-span').innerHTML = '';
// document.getElementById('username-span').innerHTML = '';
// document.getElementById('phone-span').innerHTML = '';
// document.getElementById('email-span').innerHTML = '';
// document.getElementById('street-span').innerHTML = '';
// document.getElementById('city-span').innerHTML = '';
// document.getElementById('state-span').innerHTML = '';
// document.getElementById('zipcode-span').innerHTML = '';
// }
// } catch (error) {
// console.error('Error during reset:', error);
// // You might want to show this error to the user
// alert('Error during reset. Check console for details.');
// }
// };
// Centralized function to update UI based on admin state
function updateAdminUI(isAdminMode) {
// Get the actual checkbox element (not the container)
const adminCheckbox = document.querySelector('.admin-input');
// Set the checkbox state programmatically to match admin state
if (adminCheckbox) {
adminCheckbox.checked = isAdminMode;
}
const clientEventButtons = document.querySelectorAll('.client-side-events button');
const clientEventsContainer = document.getElementById('client-side-events');
const adminLabel = document.getElementById('admin-label');
const adminToggle = document.getElementById('admin-toggle');
const adminUserInfo = document.getElementById('admin-user-info');
const instructionsElement = document.querySelector('.instructions');
if (isAdminMode) {
// Disable client-side event buttons
clientEventButtons.forEach(btn => {
btn.disabled = true;
btn.style.opacity = '0.5';
btn.style.cursor = 'not-allowed';
});
clientEventsContainer.classList.add('not-allowed');
// Update admin label
adminLabel.style.color = '#dc3545';
adminLabel.classList.remove('hidden');
// Update admin toggle
adminToggle.classList.add('enabled');
// Show admin user info
adminUserInfo.classList.remove('hidden');
// Update admin user details
document.getElementById('admin-userId-span').innerText = `${currentAdminUser.userId}`;
document.getElementById('admin-email-span').innerText = `${currentAdminUser.adminEmail}`;
document.getElementById('admin-firstName-span').innerText = `${currentAdminUser.firstName}`;
document.getElementById('admin-lastName-span').innerText = `${currentAdminUser.lastName}`;
// Remove anonymousId from server events
document.getElementById('anonymousId').innerText = 'anonymousId : ';
anonymousId = ''
analytics.user().anonymousId('')
// Update instructions
instructionsElement.innerHTML = `
<p><strong>ADMIN MODE ACTIVE</strong></p>
<p>1. You are now impersonating a user as an admin.</p>
<p>2. Click the Generate User Data button to create a user to impersonate.</p>
<p>3. Only Server-Side events are enabled for admin users.</p>
<p>4. All server events will include your admin information sent in the event's context.admin object.</p>
<p>5. Click any button under Server Event Triggers to have that event triggered on the server.</p>
<p>6. Review the event requests under Server Side Segment Requests, click on them to reveal the payload.</p>
`;
} else {
// Enable client-side event buttons
clientEventButtons.forEach(btn => {
btn.disabled = false;
btn.style.opacity = '1';
btn.style.cursor = 'pointer';
});
clientEventsContainer.classList.remove('not-allowed');
// Reset admin label
adminLabel.style.color = '#6b7280';
adminToggle.classList.remove('enabled');
// Hide admin user info
adminUserInfo.classList.add('hidden');
// Clear admin user details
document.getElementById('admin-userId-span').innerText = '';
document.getElementById('admin-email-span').innerText = '';
document.getElementById('admin-firstName-span').innerText = '';
document.getElementById('admin-lastName-span').innerText = '';
// Remove anonymousId from server events
let anonymousId = analytics.user().anonymousId()
document.getElementById('anonymousId').innerText = `anonymousId : ${anonymousId}`;
// Restore original instructions
instructionsElement.innerHTML = `
<p>1. Click the Generate User Data button to create user traits and a userId.</p>
<p>2. Click any button under Client Event Triggers to have that event triggered on the client.</p>
<p>3. Click any button under Server Event Triggers to have that event triggered on the server.</p>
<p>4. Review the event requests under Segment Requests, click on them to reveal the payload.</p>
<p>5. You can also manually complete the User Form with customized data. The Submit button triggers an Identify event and a Track event 'Form Submitted' with the form's data.</p>
`;
}
}
// Centralized function to clear user data
function clearUserData() {
// Clear UI elements
document.getElementById('userId').innerText = 'userId : ';
document.getElementById('anonymousId').innerText = 'anonymousId : ';
document.getElementById('userTraits').innerText = 'userTraits : ';
// Clear local variables
userId = '';
anonymousId = '';
userTraits = {};
firstName = '';
lastName = '';
username = '';
phone = '';
street = '';
city = '';
state = '';
zipcode = '';
email = '';
// Clear user-related spans
const userDetailSpans = [
'firstName-span', 'lastName-span', 'username-span',
'phone-span', 'email-span', 'street-span',
'city-span', 'state-span', 'zipcode-span'
];
userDetailSpans.forEach(spanId => {
const span = document.getElementById(spanId);
if (span) span.innerHTML = '';
});
}
// Centralized function to clear local storage & optionally preserves admin state with parameter
// Modified clearLocalStorageItems to optionally preserve admin state
function clearLocalStorageItems(preserveAdminState = false) {
// If preserving admin state, save it first
let savedAdminState = null;
if (preserveAdminState) {
savedAdminState = localStorage.getItem('adminReloadState');
}
// Clear specific local storage items
const itemsToRemove = [
'userId', 'anonymousId', 'groupId',
'userTraits', 'groupTraits'
];
itemsToRemove.forEach(item => localStorage.removeItem(item));
// Clear all segment-related local storage items
Object.keys(localStorage).forEach(key => {
if (key.startsWith('ajs_') || key.startsWith('seg_')) {
localStorage.removeItem(key);
}
});
// Restore admin state if needed
if (preserveAdminState && savedAdminState) {
localStorage.setItem('adminReloadState', savedAdminState);
}
}
// Function to save admin state before page reload
function saveAdminStateForReload() {
// Always save the current state, whether enabled or not
const adminReloadState = {
isEnabled: adminState.isEnabled,
currentAdmin: adminState.currentAdmin,
originalContext: adminState.originalContext,
originalUserId: adminState.originalUserId,
originalAnonymousId: adminState.originalAnonymousId,
originalTraits: adminState.originalTraits
};
// Save to localStorage, but use a timestamp to ensure freshness
localStorage.setItem('adminReloadState', JSON.stringify({
timestamp: Date.now(),
state: adminReloadState
}));
}
// Function to restore admin state after page reload
function restoreAdminStateAfterReload() {
const savedAdminStateJSON = localStorage.getItem('adminReloadState');
if (savedAdminStateJSON) {
try {
const savedData = JSON.parse(savedAdminStateJSON);
// Check if data is fresh (less than 10 seconds old)
const isDataFresh = (Date.now() - savedData.timestamp) < 10000;
if (isDataFresh) {
// Restore admin state
adminState = { ...savedData.state };
// Update UI based on restored state
updateAdminUI(adminState.isEnabled);
console.log('Admin state restored:', adminState.isEnabled ?
'Admin mode enabled' : 'Admin mode disabled');
// Clear the saved state from localStorage
localStorage.removeItem('adminReloadState');
return true;
} else {
// Data is stale, clear it
localStorage.removeItem('adminReloadState');
return false;
}
} catch (error) {
console.error('Error restoring admin state:', error);
localStorage.removeItem('adminReloadState');
return false;
}
}
return false;
}
// Updated handleAdminToggle function
async function handleAdminToggle(event) {
const newAdminState = event.target.checked;
// If the state didn't actually change, do nothing
if (newAdminState === adminState.isEnabled) return;
// Select a new random admin user each time admin mode is toggled on
if (newAdminState) {
currentAdminUser = adminUsers[Math.floor(Math.random() * adminUsers.length)];
console.log('Selected new admin user:', currentAdminUser);
}
adminState.isEnabled = newAdminState;
if (adminState.isEnabled) {
try {
// Get current client data before making changes
const clientData = await getClientData();
// Store original state
adminState.currentAdmin = currentAdminUser; // Store the newly selected admin
adminState.originalContext = clientData.context;
adminState.originalUserId = clientData.clientUserId;
adminState.originalAnonymousId = clientData.clientAnonymousId;
adminState.originalTraits = clientData.traits;
console.log('Admin mode activated with user:', adminState.currentAdmin);
// Update UI without page reload
updateAdminUI(true);
// Reset user data
// cookieReset();
// No longer calling cookieReset() here to preserve user data
// Save the admin state for potential reload
saveAdminStateForReload();
} catch (error) {
console.error('Error activating admin mode:', error);
// Reset the checkbox state
event.target.checked = false;
adminState.isEnabled = false;
}
} else {
// Clear admin state
const previousAdminState = {...adminState};
adminState.currentAdmin = null;
adminState.originalContext = null;
adminState.originalUserId = null;
adminState.originalAnonymousId = null;
adminState.originalTraits = null;
adminState.isEnabled = false;
// Update UI to exit admin mode
updateAdminUI(false);
// Save the fact that admin mode is disabled
saveAdminStateForReload();
// Reset cookies and reload
// cookieReset();
// No longer calling cookieReset() here to preserve user data
}
}
// Updated cookieReset function
const cookieReset = async () => {
try {
// Save current admin state before doing anything else
saveAdminStateForReload();
// Get the current anonymousId before reset
const currentAnonymousId = analytics.user().anonymousId();
// Reset client-side analytics
analytics.reset();
// Clear user data
clearUserData();
// Call server reset endpoint
const response = await fetch('http://localhost:4100/api/reset', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
anonymousId: currentAnonymousId
})
});
if (!response.ok) {
throw new Error(`Server reset failed: ${response.statusText}`);
}
const result = await response.json();
console.log('Server reset result:', result);
// Clear local storage items (but not admin state)
clearLocalStorageItems(true); // Pass true to preserve admin state
// Always reload to get fresh state
// window.location.reload();
console.log('User data reset complete');
} catch (error) {
console.error('Error during reset:', error);
alert('Error during reset. Check console for details.');
}
};
// Add this to your page load/initialization script
document.addEventListener('DOMContentLoaded', () => {
// Check and restore admin state if applicable
restoreAdminStateAfterReload();
});
let firstName =''
let lastName =''
let username =''
let phone =''
let street =''
let city =''
let state =''
let zipcode =''
let email =''
// Create a global object to store the current generated user data
let generatedUserData = {
userId: '',
anonymousId: '',
traits: {}
};
const getUserData = async () => {
console.log('Fetching user data...');
try {
// Save current admin state before fetching new user data
if (adminState.isEnabled) {
saveAdminStateForReload();
}
const response = await fetch('./users.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
console.log('User data fetched successfully:');
if (users.length === 0) {
console.log('No users found in users.json.');
return;
}
// Select a random user from the array
const randomIndex = Math.floor(Math.random() * users.length);
const user = users[randomIndex];
console.log('CURRENT USER : ', user);
// Update UI elements
document.getElementById('firstName-span').innerHTML = user.firstName;
document.getElementById('lastName-span').innerHTML = user.lastName;
document.getElementById('username-span').innerHTML = user.username;
document.getElementById('phone-span').innerHTML = user.phone;
document.getElementById('email-span').innerHTML = user.email;
document.getElementById('street-span').innerHTML = user.streetAddress;
document.getElementById('city-span').innerHTML = user.city;
document.getElementById('state-span').innerHTML = user.state;
document.getElementById('zipcode-span').innerHTML = user.zipcode;
// Store traits in userTraits variable for backward compatibility
userTraits = {
firstName: user.firstName,
lastName: user.lastName,
username: user.username,
phone: user.phone,
street: user.streetAddress,
city: user.city,
state: user.state,
zipcode: user.zipcode,
email: user.email,
};
document.getElementById('userTraits').innerText = `traits : ${JSON.stringify(userTraits)}`;
// Get the IDs by calling syncIds
const syncResult = await syncIds();
// Store the complete user data in the global object
generatedUserData = {
userId: document.getElementById('userId').innerText.split(': ')[1] || '',
anonymousId: document.getElementById('anonymousId').innerText.split(': ')[1] || '',
traits: userTraits
};
console.log('Generated user data stored:', generatedUserData);
// Update Global Variables for backward compatibility
firstName = user.firstName;
lastName = user.lastName;
username = user.username;
phone = user.phone;
street = user.streetAddress;
city = user.city;
state = user.state;
zipcode = user.zipcode;
email = user.email;
return generatedUserData;
} catch (err) {
console.error('Error fetching user data:', err);
return null;
}
};
// Add a new function to handle the Reset User button click
function handleResetUser() {
// First save admin state
saveAdminStateForReload();
// Perform reset
cookieReset();
// Reload the page with admin state preserved
window.location.reload();
}
// Function to send anonymousId to the server and receive userId
let tempUserId
const syncIds = async () => {
// Get anonymousId from Segment's Analytics
const anonymousId = window.analytics.user().anonymousId();
// Simulated Segment Analytics user
const analytics = {
user: () => ({
anonymousId : anonymousId,
id: (userId) => console.log(`User ID set to: ${userId}`)
}),
};
try {
// Send anonymousId to the server
const response = await fetch(`/api/share-ids`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ anonymousId }),
});
// Handle server response
if (response.ok) {
const { userId } = await response.json();
console.log('1 - User ID :', userId);
// Update userId
tempUserId = userId
document.getElementById('userId').innerText = `userId : ${userId}`;
analytics.user().id(tempUserId);
console.log('2 - User ID cookie : ', tempUserId);
window.localStorage.ajs_user_id = tempUserId;
console.log('analytics.user().id(); : ', analytics.user().id())
console.log('3 - User ID synchronized and saved:', userId);
console.log('4 - Anonymous ID cookie : ', anonymousId);
} else {
console.error('Failed to synchronize user ID:', response.statusText);
}
} catch (error) {
console.error('Error syncing user ID:', error);
}
}
// FAKERS DATA : USERS.JSON FILE
const userList = document.getElementById('user-list');
let fakerUserData;
// SPEC : COMMON FIELDS : CONTEXT OBJECT @ https://segment.com/docs/connections/spec/common/#context
const getClientData = () => {
return new Promise((resolve) => {
// Make sure analytics is ready before collecting data
window.analytics.ready(() => {
// Get user identifiers after analytics is ready
const userId = window.analytics.user().id();
const anonymousId = window.analytics.user().anonymousId();
const userTraits = window.analytics.user().traits();
const context = {
campaign : {
name: document.location.href,
source: document.location.origin,
medium: document.location.protocol.replace(':', ''),
term: document.location.search,
content: document.location.pathname
},
locale : navigator.language,
os : {
name : navigator.platform,
version : navigator.appVersion
},
page : {
path : window.location.pathname,
referrer : document.referrer,
search : window.location.search,
title : document.title,
url : window.location.href
},
screen : {
height : window.screen.height,
width : window.screen.width
},
timezone : Intl.DateTimeFormat().resolvedOptions().timeZone,
userAgentData : {
userAgent : navigator.userAgent,
platform : navigator.userAgentData.platform || '',
brands : navigator.userAgentData.brands || []
},
test : 'test'
};
let clientUserId = analytics.user().id()
console.log('CONTEXT clientUserId : ', clientUserId)
let clientAnonymousId = analytics.user().anonymousId()
let clientUserTraits = analytics.user().traits()
console.log('Client data collected:', { clientUserId, clientAnonymousId, clientUserTraits, context });
resolve({
clientUserId,
clientAnonymousId,
traits: clientUserTraits,
context
});
});
});
};
// TRIGGER SEGMENT EVENTS FROM CLIENT OR SERVER
const triggerEvent = async (eventType, sourceType, data) => {
// Check for admin mode restrictions
if (adminState.isEnabled && sourceType === 'client') {
console.warn('Client-side events are disabled in admin mode');
return;
}
// Ensure we have synced IDs if in admin mode
if (adminState.isEnabled && sourceType === 'server') {
await syncIds();
}
// Get the current user data displayed in UI
let userIdValue = document.getElementById('userId').innerText.split(': ')[1] || '';
if (userIdValue === "null") userIdValue = null;
const currentUIData = {
userId: userIdValue,
anonymousId: document.getElementById('anonymousId').innerText.split(': ')[1] || '',
traits: {
firstName: document.getElementById('firstName-span').innerText || '',
lastName: document.getElementById('lastName-span').innerText || '',
username: document.getElementById('username-span').innerText || '',
phone: document.getElementById('phone-span').innerText || '',
email: document.getElementById('email-span').innerText || '',
street: document.getElementById('street-span').innerText || '',
city: document.getElementById('city-span').innerText || '',
state: document.getElementById('state-span').innerText || '',
zipcode: document.getElementById('zipcode-span').innerText || ''
}
};
try {
// Get client data
let clientData = await getClientData();
console.log('clientData : ', clientData);
// Set appropriate data sources based on event type
if (sourceType === 'server') {
// For server-side events, prioritize generatedUserData
userId = generatedUserData.userId || currentUIData.userId || clientData.userId;
anonymousId = generatedUserData.anonymousId || currentUIData.anonymousId || clientData.anonymousId;
traits = generatedUserData.traits || data.traits || currentUIData.userTraits || clientData.traits || {};
// Ensure context includes traits
context = {
...clientData.context,
traits: traits
};
// Add admin data if in admin mode
if (adminState.isEnabled && adminState.currentAdmin && sourceType === 'server') {
context.isAdmin = true;
context.admin = {
adminUserId: adminState.currentAdmin.userId,
firstName: adminState.currentAdmin.firstName,
lastName: adminState.currentAdmin.lastName,
adminEmail: adminState.currentAdmin.adminEmail
};
console.log('Added admin context:', context.admin);
}
} else {
// For client-side events, use client data or fallback to existing values
userId = generatedUserData.userId || clientData.clientUserId || userId;
anonymousId = generatedUserData.anonymousId || clientData.clientAnonymousId || anonymousId;
traits = generatedUserData.traits || clientData.traits || userTraits;
context = {...clientData.context, traits: traits};
}
console.log('Using data:', {
sourceType,
userId,
anonymousId,
traits,
context
});
console.log('context : ', context);
page = clientData.context.page;
name = page.title;
category = 'Viewed';
let payload = {userId, anonymousId, traits, context};
console.log('payload : ', payload);
// Spec Track : https://segment.com/docs/connections/spec/track/
// The Track method follows this format :
// analytics.track(event, [properties], [options], [callback]);
if (eventType === 'track') {
console.log('Track: Started');
let eventName = data.event ? data.event : 'Button Clicked';
let properties = {
...data.properties ? data.properties : null,
button: data.button ? data.button : `${sourceType}TrackTrigger`,
...page
};
if (sourceType === 'client') {
console.log('T- eventName:', eventName);
console.log('T- properties:', properties);
console.log('T- context:', context);
console.log('T- userId:', userId);
console.log('T- anonymousId:', anonymousId);
analytics.track(eventName, properties, {context: context, userId: userId, anonymousId: anonymousId});
renderResponse('Track', {
properties,
event: eventName,
context,
userId,
anonymousId
}, 'client');
console.log(`CLIENT: Track event ${eventName} sent successfully`);
} else if (sourceType === 'server') {
console.log('SERVER : context contain traits? ', context);
fetch('http://localhost:4100/track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payload : {
userId,
anonymousId,
context,
event: eventName,
properties
}
}),
})
.then(response => {
console.log('Server-side Track:', response);
if (!response.ok) {
throw new Error(`HTTP error! status on Server-side Track: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log('Server-side Track response:', data);
renderResponse('Track', data, 'server');
})
.catch((err) => {
console.error('Error triggering server-side Track:', err);
});
}
console.log('Track: Completed');
}
// Spec Identify : https://segment.com/docs/connections/spec/identify/
// The Identify method follows this format :
// analytics.identify([userId], [traits], [options], [callback]);
if (eventType === 'identify'){
console.log('Identify : Started')
if (sourceType ==='client'){
analytics.identify(userId, traits, {context, anonymousId})
if (sourceType === 'client') {
analytics.identify(userId, traits, {
context,
anonymousId
});
console.log('CLIENT: Identify event sent successfully');
renderResponse('Identify', {
traits,
context,
userId,
anonymousId
}, 'client');
}
console.log('CLIENT : Identify event sent successfully');
} else if (sourceType ==='server'){
fetch('http://localhost:4100/identify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payload : {
userId: userId,
anonymousId: anonymousId,
traits: traits,
context: context
}