-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoordinator.js
More file actions
2694 lines (2311 loc) · 82.9 KB
/
coordinator.js
File metadata and controls
2694 lines (2311 loc) · 82.9 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
/**
* @fileoverview Addocu Main Coordinator v2.0 - Google Workspace Add-on
* @version 3.0
*/
// =================================================================
// ADD-ON BOOTSTRAP AND MENU
// =================================================================
/**
* Executed when a user installs the Add-on.
* @param {Object} e - Google Apps Script event object.
*/
function onInstall(e) {
onOpen(e);
// Installation log
logEvent('INSTALL', `Addocu installed for user: ${Session.getActiveUser().getEmail()}`);
flushLogs();
}
/**
* Executed when a user opens a spreadsheet with the Add-on.
* @param {Object} e - Google Apps Script event object.
*/
function onOpen(e) {
try {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('Configure Addocu', 'openConfigurationSidebar')
.addSeparator()
.addItem('Audit Complete Stack', 'startCompleteAudit')
.addItem('Force Full Audit (Reset Incremental)', 'startFullAudit')
.addSeparator()
.addItem('Audit GA4', 'syncGA4WithUI')
.addItem('Audit GTM', 'syncGTMWithUI')
.addItem('Audit Looker Studio', 'syncLookerStudioWithUI')
.addItem('Audit Search Console', 'syncSearchConsoleWithUI')
.addItem('Audit YouTube', 'syncYouTubeWithUI')
.addItem('Audit Google Business Profile', 'syncGBPWithUI')
.addItem('Audit Google Ads', 'syncGoogleAdsWithUI')
.addItem('Audit Merchant Center', 'syncGMCWithUI')
.addItem('Audit BigQuery', 'syncBigQueryWithUI')
.addItem('Audit AdSense', 'syncAdSenseWithUI')
.addItem('Interactive Dashboard', 'openHtmlDashboard')
.addSubMenu(SpreadsheetApp.getUi().createMenu('Tools')
.addItem('Test Connections', 'diagnoseConnections')
.addItem('Test OAuth2', 'testOAuth2')
.addItem('Analyze Changes', 'analyzeRecentChangesUI')
.addItem('View Sync History', 'showSyncHistory')
.addItem('Clear Sync State', 'clearAllSyncState')
.addItem('Clean Logs', 'cleanupLogsUI')
.addItem('Generate Dashboard', 'generateManualDashboard')
.addSeparator()
.addItem('🧠 Smart Discovery (PRO)', 'runSmartDiscovery')
.addItem('🫀 Heartbeat Alert (PRO)', 'runHeartbeatAlert')
.addItem('🔬 Dimensional Health (PRO)', 'runDimensionalHealthCheck')
.addItem('📚 Data Inventory (PRO)', 'runDataInventory')
)
.addSubMenu(SpreadsheetApp.getUi().createMenu('🛡️ Governance')
.addItem('User Access Audit', 'runUserAccessAudit')
.addItem('🧟 Zombie Hunter', 'runZombieHunter')
)
.addSubMenu(SpreadsheetApp.getUi().createMenu('Troubleshooting')
.addItem('Verify Accounts (IMPORTANT)', 'showAccountVerification')
.addItem('Reauthorize Permissions', 'forcedPermissionReauthorization')
.addItem('Force All Permissions', 'forceAllPermissions')
.addItem('Simplified Diagnostics', 'showSimplifiedDiagnostics')
)
.addToUi();
} catch (error) {
// If complete menu fails, try creating a basic one
try {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('Reauthorize Addocu', 'forcedPermissionReauthorization')
.addItem('Diagnostics', 'showCompleteDiagnostics')
.addToUi();
} catch (e) {
// If even this fails, log to console
console.error('Critical error creating Addocu menu:', e.message);
}
}
}
// =================================================================
// USER INTERFACE MANAGEMENT (HTML)
// =================================================================
/**
* Shows the new configuration sidebar v2.0.
*/
function openConfigurationSidebar() {
try {
const html = HtmlService.createHtmlOutputFromFile('configuration')
.setTitle('Addocu Configuration')
.setWidth(320); // Optimized width for Google Sheets
SpreadsheetApp.getUi().showSidebar(html);
logEvent('CONFIG', 'Configuration sidebar opened');
} catch (e) {
logError('CONFIG', `Error opening sidebar: ${e.message}`);
SpreadsheetApp.getUi().alert(
'Error',
`Could not open configuration. Error: ${e.message}`,
SpreadsheetApp.getUi().ButtonSet.OK
);
}
}
/**
* Opens the interactive HTML dashboard.
*/
function openHtmlDashboard() {
try {
const html = HtmlService.createHtmlOutputFromFile('interactive_dashboard')
.setWidth(1400)
.setHeight(850);
SpreadsheetApp.getUi().showModalDialog(html, 'Dashboard - Addocu');
logEvent('DASHBOARD', 'HTML dashboard opened');
} catch (e) {
logError('DASHBOARD', `Error opening dashboard: ${e.message}`);
SpreadsheetApp.getUi().alert(
'Error Opening Dashboard',
`Could not open dashboard. Error: ${e.message}`,
SpreadsheetApp.getUi().ButtonSet.OK
);
}
}
/**
* Alias for openHtmlDashboard() - called from sidebar.
*/
function openDashboard() {
return openHtmlDashboard();
}
// =================================================================
// SIDEBAR COMMUNICATION V2.0
// =================================================================
/**
* Enhanced getUserConfig with robust error handling - used by sidebar.
* @returns {Object} User configuration with safe fallbacks.
*/
function getUserConfig() {
// Use enhanced version with better error handling
return typeof getUserConfigSafe !== 'undefined' ?
getUserConfigSafe() :
readUserConfiguration();
}
/**
* Executed when file-specific permissions are granted to the Add-on.
* This function is required by the appsscript.json onFileScopeGrantedTrigger.
* @param {Object} e - Google Apps Script event object.
*/
function onFileScopeGranted(e) {
try {
logEvent('PERMISSIONS', `File permissions granted for user: ${Session.getActiveUser().getEmail()}`);
// Initialize user configuration safely
initializeUserConfigurationSafe();
logEvent('PERMISSIONS', 'File permission initialization completed');
} catch (error) {
logError('PERMISSIONS', `Error in onFileScopeGranted: ${error.message}`);
// Don't throw - this should fail silently
}
}
/**
* Initializes user configuration safely.
*/
function initializeUserConfigurationSafe() {
try {
const userProperties = PropertiesService.getUserProperties();
// Check if configuration already exists
const existingConfig = userProperties.getProperty('ADDOCU_INITIALIZED');
if (!existingConfig) {
// Default initial configuration
const defaultConfig = {
'ADDOCU_INITIALIZED': 'true',
'ADDOCU_FIRST_TIME': 'true',
'ADDOCU_SYNC_GA4': 'true',
'ADDOCU_SYNC_GTM': 'true',
'ADDOCU_SYNC_LOOKER': 'true',
'ADDOCU_SYNC_GSC': 'true',
'ADDOCU_SYNC_YOUTUBE': 'true',
'ADDOCU_LOG_LEVEL': 'INFO',
'ADDOCU_REQUEST_TIMEOUT': '60'
};
userProperties.setProperties(defaultConfig);
logEvent('INIT', 'Initial user configuration created');
}
} catch (error) {
logError('INIT', `Error initializing configuration: ${error.message}`);
}
}
/**
* Gets user email safely.
*/
function getUserEmailSafe() {
try {
return Session.getActiveUser().getEmail() || 'unknown@unknown.com';
} catch (error) {
return 'permission-error@unknown.com';
}
}
/**
* Reads the complete configuration of the current user (OAuth2 + Looker API Key).
* @returns {Object} User configuration with Looker API Key, services, etc.
*/
function readUserConfiguration() {
try {
const userProperties = PropertiesService.getUserProperties();
const config = {
// API Configuration (NOTE: Looker Studio now uses OAuth2, not API Key)
lookerApiKey: userProperties.getProperty('ADDOCU_LOOKER_API_KEY') || '', // Kept for compatibility
gtmFilter: userProperties.getProperty('ADDOCU_GTM_FILTER') || '',
// Advanced Filters
ga4Properties: userProperties.getProperty('ADDOCU_GA4_PROPERTIES_FILTER') || '',
gtmWorkspaces: userProperties.getProperty('ADDOCU_GTM_WORKSPACES_FILTER') || '',
// Service Configuration
syncFrequency: userProperties.getProperty('ADDOCU_SYNC_FREQUENCY') || 'manual',
requestTimeout: parseInt(userProperties.getProperty('ADDOCU_REQUEST_TIMEOUT')) || 60,
// Services Status - All available
syncLooker: userProperties.getProperty('ADDOCU_SYNC_LOOKER') !== 'false', // Default true
syncGA4: userProperties.getProperty('ADDOCU_SYNC_GA4') !== 'false', // Default true
syncGTM: userProperties.getProperty('ADDOCU_SYNC_GTM') !== 'false', // Default true
syncSearchConsole: userProperties.getProperty('ADDOCU_SYNC_GSC') !== 'false', // Default true
syncYouTube: userProperties.getProperty('ADDOCU_SYNC_YOUTUBE') !== 'false', // Default true
syncGBP: userProperties.getProperty('ADDOCU_SYNC_GBP') !== 'false', // Default true
syncGoogleAds: userProperties.getProperty('ADDOCU_SYNC_ADS') !== 'false', // Default true
googleAdsDevToken: userProperties.getProperty('ADDOCU_GOOGLE_ADS_DEV_TOKEN') || '',
// OAuth2 Information
oauth2Ready: true, // OAuth2 always available
userEmail: getUserEmailSafe(),
// Alert Configuration
alertEmail: userProperties.getProperty('ADDOCU_ALERT_EMAIL') || '',
alertErrors: userProperties.getProperty('ADDOCU_ALERT_ERRORS') !== 'false', // Default true
alertChanges: userProperties.getProperty('ADDOCU_ALERT_CHANGES') === 'true',
alertSuccess: userProperties.getProperty('ADDOCU_ALERT_SUCCESS') === 'true',
alertWarnings: userProperties.getProperty('ADDOCU_ALERT_WARNINGS') === 'true',
weeklySummary: userProperties.getProperty('ADDOCU_WEEKLY_SUMMARY') === 'true',
// Advanced Configuration
logLevel: userProperties.getProperty('ADDOCU_LOG_LEVEL') || 'INFO',
logRetention: parseInt(userProperties.getProperty('ADDOCU_LOG_RETENTION')) || 30,
// User Status
isFirstTime: userProperties.getProperty('ADDOCU_FIRST_TIME') !== 'false',
isPro: true, // All users have complete access
// BigQuery Configuration
bqTableDateRange: userProperties.getProperty('ADDOCU_BQ_TABLE_DATE_RANGE') || '30'
};
return config;
} catch (e) {
logError('CONFIG', `Error reading configuration: ${e.message}`);
// Return default configuration with error indicator
return {
oauth2Ready: true,
userEmail: getUserEmailSafe(),
permissionsError: true,
permissionsErrorMessage: e.message,
isFirstTime: true,
isPro: true,
syncGA4: true,
syncGTM: true,
syncLooker: true,
syncSearchConsole: true,
lookerApiKey: '',
gtmFilter: '',
ga4Properties: '',
gtmWorkspaces: '',
syncFrequency: 'manual',
requestTimeout: 60
};
}
}
/**
* Enhanced saveUserConfiguration with better error handling.
* @param {Object} config - Object with configuration to save.
* @returns {Object} Operation result.
*/
function saveUserConfiguration(config) {
// Use enhanced version if available
if (typeof saveUserConfigurationEnhanced !== 'undefined') {
return saveUserConfigurationEnhanced(config);
}
// Fallback to original implementation
try {
const userProperties = PropertiesService.getUserProperties();
// Map configuration properties
if (config.lookerApiKey !== undefined) {
if (config.lookerApiKey.trim()) {
userProperties.setProperty('ADDOCU_LOOKER_API_KEY', config.lookerApiKey.trim());
} else {
userProperties.deleteProperty('ADDOCU_LOOKER_API_KEY');
}
}
if (config.googleAdsDevToken !== undefined) {
try {
if (config.googleAdsDevToken.trim()) {
const tokenValue = config.googleAdsDevToken.trim();
userProperties.setProperty('ADDOCU_GOOGLE_ADS_DEV_TOKEN', tokenValue);
// Verify persistence (best practice: verify after write)
const verifyToken = userProperties.getProperty('ADDOCU_GOOGLE_ADS_DEV_TOKEN');
if (verifyToken !== tokenValue) {
logError('CONFIG', 'Google Ads Dev Token verification failed - value not persisted');
return {
success: false,
error: 'Dev Token failed to persist to UserProperties. Check if Chrome and Sheets use the same Google account.',
field: 'googleAdsDevToken',
requiresPermissionRecovery: true
};
}
logEvent('CONFIG', `Google Ads Dev Token saved and verified: ${tokenValue.substring(0, 10)}...`);
} else {
userProperties.deleteProperty('ADDOCU_GOOGLE_ADS_DEV_TOKEN');
logEvent('CONFIG', 'Google Ads Dev Token removed (empty value)');
}
} catch (tokenError) {
logError('CONFIG', `Failed to save Google Ads Dev Token: ${tokenError.message}`);
return {
success: false,
error: `Dev Token save failed: ${tokenError.message}`,
field: 'googleAdsDevToken',
requiresPermissionRecovery: tokenError.message.includes('PERMISSION_DENIED')
};
}
}
if (config.gtmFilter !== undefined) {
userProperties.setProperty('ADDOCU_GTM_FILTER', config.gtmFilter);
}
// Save advanced filters
if (config.ga4Properties !== undefined) {
if (config.ga4Properties.trim()) {
userProperties.setProperty('ADDOCU_GA4_PROPERTIES_FILTER', config.ga4Properties.trim());
} else {
userProperties.deleteProperty('ADDOCU_GA4_PROPERTIES_FILTER');
}
}
if (config.gtmWorkspaces !== undefined) {
if (config.gtmWorkspaces.trim()) {
userProperties.setProperty('ADDOCU_GTM_WORKSPACES_FILTER', config.gtmWorkspaces.trim());
} else {
userProperties.deleteProperty('ADDOCU_GTM_WORKSPACES_FILTER');
}
}
// Save BigQuery Project ID
if (config.bqProjectId !== undefined) {
if (config.bqProjectId.trim()) {
userProperties.setProperty('ADDOCU_BQ_PROJECT_ID', config.bqProjectId.trim());
logEvent('CONFIG', `BigQuery Project ID set to: ${config.bqProjectId.trim()}`);
} else {
userProperties.deleteProperty('ADDOCU_BQ_PROJECT_ID');
logEvent('CONFIG', 'BigQuery Project ID removed (empty value)');
}
}
// Save BigQuery table date range
if (config.bqTableDateRange !== undefined) {
userProperties.setProperty('ADDOCU_BQ_TABLE_DATE_RANGE', config.bqTableDateRange.toString());
logEvent('CONFIG', `BigQuery table date range set to: ${config.bqTableDateRange}`);
}
// Save incremental audit enabled setting
if (config.incrementalAuditEnabled !== undefined) {
userProperties.setProperty('ADDOCU_INCREMENTAL_AUDIT_ENABLED', config.incrementalAuditEnabled.toString());
logEvent('CONFIG', `Incremental audit enabled: ${config.incrementalAuditEnabled}`);
}
// Mark as not first time (OAuth2 is always ready)
userProperties.setProperty('ADDOCU_FIRST_TIME', 'false');
logEvent('CONFIG', `Configuration saved: ${Object.keys(config).join(', ')}`);
return { success: true };
} catch (e) {
logError('CONFIG', `Error saving configuration: ${e.message}`);
return {
success: false,
error: e.message,
requiresPermissionRecovery: e.message.includes('PERMISSION_DENIED')
};
}
}
/**
* Enhanced connection testing with robust permission handling.
* @returns {Array} Array with accurate service status.
*/
function testCompleteConnection() {
try {
// First test basic permissions using enhanced functions
const permissionTest = testBasicPermissionsEnhanced();
if (!permissionTest.success) {
// If basic permissions fail, return enhanced diagnostic information
return diagnoseConnectionsEnhanced();
}
// If permissions work, use normal diagnostics
return typeof diagnoseConnectionsComplete !== 'undefined' ?
diagnoseConnectionsComplete() :
simplifiedConnectionDiagnostics();
} catch (error) {
logError('PROBE_CONNECTION', `Error in enhanced connection testing: ${error.message}`);
return [
['Addocu System', 'Critical Error', 'ERROR', `System error: ${error.message}`],
['Solution', 'Reauthorize Permissions', 'ACTION', 'Extensions > Addocu > Reauthorize Permissions'],
['Alternative', 'Manual Account Check', 'ACTION', 'Manually verify Chrome/Sheets use same account']
];
}
}
/**
* Enhanced permission recovery with robust error handling.
* @returns {Object} Accurate recovery result.
*/
function attemptPermissionRecovery() {
try {
logEvent('RECOVERY_ENHANCED', 'Starting enhanced permission recovery...');
// Use enhanced recovery function if available
if (typeof attemptPermissionRecoveryEnhanced !== 'undefined') {
return attemptPermissionRecoveryEnhanced();
}
// Fallback to basic recovery
return {
success: false,
message: 'Enhanced recovery functions not available',
requiresReauth: true
};
} catch (error) {
logError('RECOVERY_ENHANCED', `Error in enhanced permission recovery: ${error.message}`);
return {
success: false,
message: `Error: ${error.message}`,
requiresReauth: true,
recommendation: 'Try reauthorization first: Extensions > Addocu > Reauthorize Permissions. If problems persist, manually verify account consistency.'
};
}
}
/**
* Tests basic required permissions.
* @returns {Object} Test results.
*/
function testBasicPermissions() {
const results = {
success: true,
permissions: {},
errors: []
};
// Test 1: UserProperties
try {
const userProps = PropertiesService.getUserProperties();
userProps.setProperty('ADDOCU_PERMISSION_TEST', Date.now().toString());
const testValue = userProps.getProperty('ADDOCU_PERMISSION_TEST');
results.permissions.userProperties = !!testValue;
} catch (error) {
results.permissions.userProperties = false;
results.errors.push(`UserProperties: ${error.message}`);
results.success = false;
}
// Test 2: Spreadsheet
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
results.permissions.spreadsheet = !!ss;
} catch (error) {
results.permissions.spreadsheet = false;
results.errors.push(`Spreadsheet: ${error.message}`);
results.success = false;
}
// Test 3: OAuth Token
try {
const token = ScriptApp.getOAuthToken();
results.permissions.oauth = !!token;
} catch (error) {
results.permissions.oauth = false;
results.errors.push(`OAuth: ${error.message}`);
results.success = false;
}
return results;
}
/**
* Executes an audit with advanced filters.
* @param {Object} auditConfig - Audit configuration with services and filters.
* @returns {Object} Audit result.
*/
function executeAuditWithFilters(auditConfig) {
const startTime = Date.now();
logEvent('AUDIT_FILTERED', `Starting filtered audit: ${JSON.stringify(auditConfig)}`);
try {
const services = auditConfig.services || [];
const filters = auditConfig.filters || {};
const results = {};
let totalRecords = 0;
let sheetsCreated = 0;
// Save filters to user configuration
if (filters.ga4Properties || filters.gtmWorkspaces) {
const userProperties = PropertiesService.getUserProperties();
if (filters.ga4Properties && filters.ga4Properties.length > 0) {
userProperties.setProperty('ADDOCU_GA4_PROPERTIES_FILTER', filters.ga4Properties.join(','));
}
if (filters.gtmWorkspaces && filters.gtmWorkspaces.length > 0) {
userProperties.setProperty('ADDOCU_GTM_WORKSPACES_FILTER', filters.gtmWorkspaces.join(','));
}
logEvent('AUDIT_FILTERED', `Filters saved: GA4=${filters.ga4Properties?.length || 0}, GTM=${filters.gtmWorkspaces?.length || 0}`);
}
// Audit GA4 with filters
if (services.includes('ga4')) {
try {
logEvent('AUDIT_FILTERED', 'Starting GA4 audit with property filters');
const ga4Result = syncGA4Core();
results.ga4 = ga4Result;
if (ga4Result.status === 'SUCCESS') {
totalRecords += ga4Result.records || 0;
sheetsCreated += ga4Result.details ? Object.keys(ga4Result.details).length : 4; // GA4 creates ~4 sheets
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in GA4 audit: ${e.message}`);
results.ga4 = { success: false, error: e.message };
}
}
// Audit GTM with filters
if (services.includes('gtm')) {
try {
logEvent('AUDIT_FILTERED', 'Starting GTM audit with workspace filters');
const gtmResult = syncGTMCore();
results.gtm = gtmResult;
if (gtmResult.status === 'SUCCESS') {
totalRecords += gtmResult.records || 0;
sheetsCreated += 3; // GTM creates 3 sheets (tags, triggers, variables)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in GTM audit: ${e.message}`);
results.gtm = { success: false, error: e.message };
}
}
// Audit Looker Studio
if (services.includes('looker')) {
try {
logEvent('AUDIT_FILTERED', 'Starting Looker Studio audit');
const lookerResult = syncLookerStudioCore();
results.looker = lookerResult;
if (lookerResult.status === 'SUCCESS') {
totalRecords += lookerResult.records || 0;
sheetsCreated += 1; // Looker creates 1 sheet
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in Looker Studio audit: ${e.message}`);
results.looker = { success: false, error: e.message };
}
}
// Audit Search Console
if (services.includes('gsc') || services.includes('searchConsole')) {
logEvent('AUDIT_FILTERED', 'Starting Search Console audit');
try {
const gscResult = syncSearchConsoleCore();
results.searchConsole = gscResult;
if (gscResult.status === 'SUCCESS') {
totalRecords += gscResult.records || 0;
sheetsCreated += 3; // GSC creates 3 sheets (sites, sitemaps, search appearance)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in Search Console audit: ${e.message}`);
results.searchConsole = { success: false, error: e.message };
}
}
// Audit YouTube
if (services.includes('youtube')) {
logEvent('AUDIT_FILTERED', 'Starting YouTube audit');
try {
const youtubeResult = syncYouTubeCore();
results.youtube = youtubeResult;
if (youtubeResult.status === 'SUCCESS') {
totalRecords += youtubeResult.records || 0;
sheetsCreated += 3; // YouTube creates 3 sheets (channels, playlists, videos)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in YouTube audit: ${e.message}`);
results.youtube = { success: false, error: e.message };
}
}
// Audit GBP
if (services.includes('googleBusinessProfile') || services.includes('gbp')) {
logEvent('AUDIT_FILTERED', 'Starting GBP audit');
try {
const gbpResult = syncGBPCore();
results.googleBusinessProfile = gbpResult;
if (gbpResult.status === 'SUCCESS' || gbpResult.success) {
totalRecords += gbpResult.records || 0;
sheetsCreated += 2; // GBP creates 2 sheets (accounts, locations)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in GBP audit: ${e.message}`);
results.googleBusinessProfile = { success: false, error: e.message };
}
}
// Audit Merchant Center
if (services.includes('googleMerchantCenter') || services.includes('gmc')) {
logEvent('AUDIT_FILTERED', 'Starting Merchant Center audit');
try {
const gmcResult = syncGMCCore();
results.googleMerchantCenter = gmcResult;
if (gmcResult.status === 'SUCCESS' || gmcResult.success) {
totalRecords += gmcResult.records || 0;
sheetsCreated += 3; // GMC creates 3 sheets (accounts, data sources, products)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in Merchant Center audit: ${e.message}`);
results.googleMerchantCenter = { success: false, error: e.message };
}
}
// Audit Google Ads
if (services.includes('googleAds') || services.includes('ads')) {
logEvent('AUDIT_FILTERED', 'Starting Google Ads audit');
try {
const adsResult = syncGoogleAdsCore();
results.googleAds = adsResult;
if (adsResult.status === 'SUCCESS' || adsResult.success) {
totalRecords += adsResult.records || 0;
sheetsCreated += 3; // Ads creates 3 sheets (campaigns, conversions, audiences)
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in Google Ads audit: ${e.message}`);
results.googleAds = { success: false, error: e.message };
}
}
// Audit BigQuery
if (services.includes('bigquery')) {
logEvent('AUDIT_FILTERED', 'Starting BigQuery audit');
try {
const bqResult = syncBigQueryCore({
forceFullAudit: false,
incrementalEnabled: true
});
results.bigquery = bqResult;
if (bqResult.status === 'SUCCESS' || bqResult.success) {
totalRecords += bqResult.records || 0;
sheetsCreated += 3; // BQ creates 3 sheets
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in BigQuery audit: ${e.message}`);
results.bigquery = { success: false, error: e.message };
}
}
// Audit AdSense
if (services.includes('adsense')) {
logEvent('AUDIT_FILTERED', 'Starting AdSense audit');
try {
const adsenseResult = syncAdSenseCore();
results.adsense = adsenseResult;
if (adsenseResult.status === 'SUCCESS' || adsenseResult.success) {
totalRecords += adsenseResult.records || 0;
sheetsCreated += 4; // AdSense creates 4 sheets
}
} catch (e) {
logError('AUDIT_FILTERED', `Error in AdSense audit: ${e.message}`);
results.adsense = { success: false, error: e.message };
}
}
// Generate executive dashboard
generateExecutiveDashboard(results);
sheetsCreated += 1; // Dashboard sheet
const duration = Date.now() - startTime;
logEvent('AUDIT_FILTERED', `Filtered audit completed in ${Math.round(duration / 1000)}s. Total: ${totalRecords} records, ${sheetsCreated} sheets`);
flushLogs();
return {
success: true,
services: services,
filters: filters,
results: results,
totalAssets: totalRecords,
sheetsCreated: sheetsCreated,
duration: duration
};
} catch (e) {
const duration = Date.now() - startTime;
logError('AUDIT_FILTERED', `Error in filtered audit: ${e.message}`);
flushLogs();
return {
success: false,
error: e.message,
duration: duration
};
}
}
/**
* Executes a complete audit of specified services.
* @param {Array} services - Array with services to audit ['ga4', 'gtm', 'looker'].
* @param {Object} options - Audit options {forceFullAudit, incrementalEnabled}
* @returns {Object} Audit result with auditModes summary.
*/
function executeCompleteAudit(services, options = {}) {
const startTime = Date.now();
const forceFullAudit = options.forceFullAudit || false;
const incrementalEnabled = options.incrementalEnabled !== false;
logEvent('AUDIT', `Starting complete audit: ${services.join(', ')} | Mode: ${forceFullAudit ? 'FULL' : 'INCREMENTAL'}`);
try {
const results = {};
const auditModes = { FULL: 0, INCREMENTAL: 0 };
let totalRecords = 0;
// Audit GA4 (Free)
if (services.includes('ga4')) {
try {
logEvent('AUDIT', 'Starting GA4 audit');
const ga4Result = syncGA4Core({
forceFullAudit: forceFullAudit,
incrementalEnabled: incrementalEnabled
});
results.ga4 = ga4Result;
totalRecords += ga4Result.records || 0;
if (ga4Result.syncMode) {
auditModes[ga4Result.syncMode]++;
}
} catch (e) {
logError('AUDIT', `Error in GA4 audit: ${e.message}`);
results.ga4 = { success: false, error: e.message };
}
}
// Audit GTM
if (services.includes('gtm')) {
try {
logEvent('AUDIT', 'Starting GTM audit');
const gtmResult = syncGTMCore();
results.gtm = gtmResult;
totalRecords += gtmResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in GTM audit: ${e.message}`);
results.gtm = { success: false, error: e.message };
}
}
// Audit Looker Studio
if (services.includes('lookerStudio') || services.includes('looker')) {
try {
logEvent('AUDIT', 'Starting Looker Studio audit');
const lookerResult = syncLookerStudioCore();
results.looker = lookerResult;
totalRecords += lookerResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in Looker Studio audit: ${e.message}`);
results.looker = { success: false, error: e.message };
}
}
// Audit Search Console
if (services.includes('searchConsole') || services.includes('gsc')) {
try {
logEvent('AUDIT', 'Starting Search Console audit');
const gscResult = syncSearchConsoleCore();
results.searchConsole = gscResult;
totalRecords += gscResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in Search Console audit: ${e.message}`);
results.searchConsole = { success: false, error: e.message };
}
}
// Audit YouTube
if (services.includes('youtube')) {
try {
logEvent('AUDIT', 'Starting YouTube audit');
const youtubeResult = syncYouTubeCore();
results.youtube = youtubeResult;
totalRecords += youtubeResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in YouTube audit: ${e.message}`);
results.youtube = { success: false, error: e.message };
}
}
// Audit GBP
if (services.includes('googleBusinessProfile') || services.includes('gbp')) {
try {
logEvent('AUDIT', 'Starting GBP audit');
const gbpResult = syncGBPCore();
results.googleBusinessProfile = gbpResult;
totalRecords += gbpResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in GBP audit: ${e.message}`);
results.googleBusinessProfile = { success: false, error: e.message };
}
}
// Audit Google Ads
if (services.includes('googleAds') || services.includes('ads')) {
try {
logEvent('AUDIT', 'Starting Google Ads audit');
const adsResult = syncGoogleAdsCore();
results.googleAds = adsResult;
totalRecords += adsResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in Google Ads audit: ${e.message}`);
results.googleAds = { success: false, error: e.message };
}
}
// Audit Merchant Center
if (services.includes('googleMerchantCenter') || services.includes('gmc')) {
try {
logEvent('AUDIT', 'Starting Merchant Center audit');
const gmcResult = syncGMCCore();
results.googleMerchantCenter = gmcResult;
totalRecords += gmcResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in Merchant Center audit: ${e.message}`);
results.googleMerchantCenter = { success: false, error: e.message };
}
}
// Audit BigQuery
if (services.includes('bigQuery') || services.includes('bigquery')) {
try {
logEvent('AUDIT', 'Starting BigQuery audit');
const bqResult = syncBigQueryCore({
forceFullAudit: forceFullAudit,
incrementalEnabled: incrementalEnabled
});
results.bigquery = bqResult;
totalRecords += bqResult.records || 0;
if (bqResult.syncMode) {
auditModes[bqResult.syncMode]++;
}
} catch (e) {
logError('AUDIT', `Error in BigQuery audit: ${e.message}`);
results.bigquery = { success: false, error: e.message };
}
}
// Audit AdSense
if (services.includes('adSense') || services.includes('adsense')) {
try {
logEvent('AUDIT', 'Starting AdSense audit');
const adSenseResult = syncAdSenseCore();
results.adsense = adSenseResult;
totalRecords += adSenseResult.records || 0;
} catch (e) {
logError('AUDIT', `Error in AdSense audit: ${e.message}`);
results.adsense = { success: false, error: e.message };
}
}
// Generate executive dashboard
generateExecutiveDashboard(results);
const duration = Date.now() - startTime;
logEvent('AUDIT', `Audit completed in ${Math.round(duration / 1000)}s. Total: ${totalRecords} records | Mode Summary: FULL=${auditModes.FULL}, INCREMENTAL=${auditModes.INCREMENTAL}`);
flushLogs();
return {
success: true,
services: services,
results: results,
totalRecords: totalRecords,
auditModes: auditModes,
duration: duration
};
} catch (e) {
const duration = Date.now() - startTime;
logError('AUDIT', `Error in audit: ${e.message}`);
flushLogs();
return {
success: false,
error: e.message,
duration: duration
};
}
}
// =================================================================
// SHEET ORDERING UTILITY
// =================================================================
/**
* Sorts all sheets in the spreadsheet alphabetically.
* Keeps special sheets (DASHBOARD, LOGS) at the end in fixed order.
*/
function sortSheetsAlphabetically() {
try {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheets = spreadsheet.getSheets();
// Define special sheets that should stay at the end
const specialSheets = ['DASHBOARD', 'LOGS'];
// Separate regular sheets from special sheets
const regularSheets = [];
const specialSheetsMap = {};
for (const sheet of sheets) {
const name = sheet.getName();
if (specialSheets.includes(name)) {
specialSheetsMap[name] = sheet;
} else {
regularSheets.push(sheet);
}
}
// Sort regular sheets alphabetically by name
regularSheets.sort((a, b) => a.getName().localeCompare(b.getName()));
// Reorder sheets: regular (alphabetical) then special (fixed order)
let position = 1;
for (const sheet of regularSheets) {
spreadsheet.moveSheet(sheet, position);
position++;
}
// Add special sheets in fixed order at the end
for (const specialName of specialSheets) {
if (specialSheetsMap[specialName]) {
spreadsheet.moveSheet(specialSheetsMap[specialName], position);
position++;
}
}
logEvent('SHEET_ORDERING', 'Sheets sorted alphabetically');
} catch (e) {
logError('SHEET_ORDERING', `Error sorting sheets: ${e.message}`);
}
}
// =================================================================
// SYNCHRONIZATION ORCHESTRATION WITH UI
// =================================================================
/**
* Function to start complete audit from menu.
*/