-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
3289 lines (2822 loc) · 117 KB
/
Copy pathbackground.js
File metadata and controls
3289 lines (2822 loc) · 117 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
// Background script for GD Recruit Assistant
// This script handles data processing and communication between content scripts and popup
import { multiTeamStorage } from './lib/multi-team-storage.js';
import {
calculateRoleRating,
recalculateRoleRatings,
recalculateRoleRatingsForTeam,
saveRoleRatings,
getCurrentRoleRatings,
resetRoleRatingsToDefaults,
initializeDefaultRatings
} from './lib/calculator.js';
// Configuration constants
const SEASON_RECRUITING_URL_KEY = 'seasonRecruitingUrl';
// Team-specific configuration keys - used for routing to appropriate storage
const TEAM_SPECIFIC_CONFIG_KEYS = ['currentSeason', 'lastUpdated', 'seasonRecruitingUrl', 'teamId', 'teamInfo', 'watchListCount'];
// Helper function to save configuration with multi-team storage
async function saveConfigSmart(key, value) {
await multiTeamStorage.init();
if (TEAM_SPECIFIC_CONFIG_KEYS.includes(key)) {
// Use multi-team storage for team-specific data
try {
// Ensure we have team context before saving team-specific data
if (!multiTeamStorage.getCurrentTeamStorage()) {
console.log('No active team context, attempting to establish from cookies before saving config');
const teamInfo = await getTeamInfoFromCookies();
if (teamInfo?.teamId) {
console.log(`Establishing team context ${teamInfo.teamId} for config save: ${key}`);
await multiTeamStorage.setActiveTeam(teamInfo.teamId, teamInfo);
} else {
throw new Error(`Cannot save team-specific config '${key}' - no team context available`);
}
}
await multiTeamStorage.saveConfig(key, value);
console.log(`✅ Saved team-specific config to team ${multiTeamStorage.getCurrentTeamId()}: ${key}`);
return true;
} catch (error) {
console.error(`❌ Error saving team-specific config '${key}':`, error);
throw error;
}
} else {
// Use multi-team storage for global configurations
await multiTeamStorage.saveGlobalConfig(key, value);
console.log(`✅ Saved global config: ${key}`);
return true;
}
}
// Helper function to get configuration with multi-team storage
async function getConfigSmart(key) {
await multiTeamStorage.init();
if (TEAM_SPECIFIC_CONFIG_KEYS.includes(key)) {
// Use multi-team storage for team-specific data
try {
// Ensure we have team context before getting team-specific data
if (!multiTeamStorage.getCurrentTeamStorage()) {
console.log('No active team context, attempting to establish from cookies before getting config');
const teamInfo = await getTeamInfoFromCookies();
if (teamInfo?.teamId) {
console.log(`Establishing team context ${teamInfo.teamId} for config get: ${key}`);
await multiTeamStorage.setActiveTeam(teamInfo.teamId, teamInfo);
} else {
console.warn(`Cannot get team-specific config '${key}' - no team context available`);
return null;
}
}
const value = await multiTeamStorage.getConfig(key);
console.log(`✅ Retrieved team-specific config from team ${multiTeamStorage.getCurrentTeamId()}: ${key} = ${value}`);
return value;
} catch (error) {
console.error(`❌ Error getting team-specific config '${key}':`, error);
return null;
}
} else {
// Use multi-team storage for global configurations
const value = await multiTeamStorage.getGlobalConfig(key);
console.log(`✅ Retrieved global config: ${key} = ${value}`);
return value;
}
}
// Handle extension icon click - open popup as new tab for better user experience
chrome.action.onClicked.addListener(async (tab) => {
try {
// Check if popup tab is already open
const existingTabs = await chrome.tabs.query({
url: chrome.runtime.getURL('popup/popup.html')
});
if (existingTabs.length > 0) {
// Focus existing tab
chrome.tabs.update(existingTabs[0].id, { active: true });
chrome.windows.update(existingTabs[0].windowId, { focused: true });
} else {
// Create new tab
chrome.tabs.create({
url: chrome.runtime.getURL('popup/popup.html'),
active: true
});
}
} catch (error) {
console.error('Error opening popup tab:', error);
}
});
// Add this code near the top of your background file, where other initialization happens
// Note: Main startup handler is located later in the file with team monitoring
// Also check when the extension is installed or updated
chrome.runtime.onInstalled.addListener(checkAllTabsForGDOffice);
// Function to scan all open tabs for GD Office page
function checkAllTabsForGDOffice() {
console.log('Scanning all open tabs for GD Office page');
chrome.tabs.query({
// Filter to only include normal web pages
url: ['*://*/*'] // This excludes chrome://, about:, etc.
}, (tabs) => {
console.log(`Checking ${tabs.length} valid tabs (filtered from all tabs)`);
// Additional filtering and validation
const validTabs = tabs.filter(tab => {
return tab &&
tab.id &&
tab.url &&
tab.status === 'complete' && // Only check fully loaded tabs
!tab.url.startsWith('chrome://') &&
!tab.url.startsWith('chrome-extension://') &&
!tab.url.startsWith('about:') &&
!tab.url.startsWith('edge://') &&
!tab.url.startsWith('moz-extension://');
});
console.log(`Processing ${validTabs.length} valid tabs`);
validTabs.forEach(tab => {
checkIfGDOfficePage(tab);
});
});
}
// Initialize when the extension is installed or updated
chrome.runtime.onInstalled.addListener(async () => {
console.log('GD Recruit Assistant extension installed');
try {
// Initialize default role ratings FIRST, before other setup
await initializeDefaultRatings();
console.log('Default role ratings initialized successfully');
} catch (error) {
console.error('Error initializing default role ratings:', error);
// Continue with other initialization even if this fails
}
// Set initial stats using multi-team storage
try {
await multiTeamStorage.init();
await multiTeamStorage.saveGlobalConfig('lastUpdated', new Date().toISOString());
await multiTeamStorage.saveGlobalConfig('watchlistCount', 0);
console.log('Initial stats saved to multi-team storage');
} catch (error) {
console.error('Error saving initial stats:', error);
}
// Extension uses popup window instead of side panel
console.log('Extension initialized - popup ready');
});
// Handle action clicks - popup will open automatically via manifest
chrome.action.onClicked.addListener((tab) => {
// Scan all open tabs for GD Office page when extension is clicked
checkAllTabsForGDOffice();
// Also check for wispersisted cookie directly
checkForWispersistedCookie().then(cookie => {
if (cookie) {
console.log('Found wispersisted cookie on extension click');
}
}).catch(error => {
console.error('Error checking for cookie on extension click:', error);
});
// Note: Popup will open automatically due to default_popup in manifest
console.log('Extension action clicked - popup should open automatically');
});
// Listen for messages from content scripts or popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Background received message:', message);
// Handle error reporting messages
if (message.type === 'popup_error') {
console.error('Popup reported error:', message.error);
// Don't send response for error reports
return false;
}
// Handle different types of messages
switch (message.action) {
case 'ping':
// Simple ping response for testing
sendResponse({ success: true, message: 'Extension is active' });
return false;
case 'saveRecruits':
console.log('Saving recruits to storage');
// Save scraped recruits to database
saveRecruits(message.data).then(async result => {
// Update last updated timestamp using smart router
try {
await saveConfigSmart('lastUpdated', new Date().toISOString());
} catch (error) {
console.warn('Error updating lastUpdated timestamp:', error);
}
sendResponse({ success: true, count: message.data.length });
}).catch(error => {
console.error('Error saving recruits:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'openAdvancedRecruitingPage':
// Open the Advanced Recruiting page in a new tab
console.log('Opening Advanced Recruiting page');
chrome.tabs.create({ url: message.url })
.then(() => {
sendResponse({ success: true });
})
.catch(error => {
console.error('Error opening tab:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'checkLogin':
// Check if user has valid cookies for whatifsports.com
console.log('Checking login status');
checkLogin().then(result => {
sendResponse(result);
}).catch(error => {
console.error('Error checking login:', error);
sendResponse({ loggedIn: false, error: error.message });
}); return true; // Indicate asynchronous response case 'syncRecruits':
console.log('Syncing recruits from existing tab');
// Get the tab ID, either from sender or find active tab
if (sender.tab && sender.tab.id) {
// Check if tab is valid before injecting
isValidTabForInjection(sender.tab.id).then(isValid => {
if (!isValid) {
sendResponse({
success: false,
error: 'Current tab is not on whatifsports.com or not fully loaded. Please navigate to a recruiting page first.'
});
return;
}
// Inject directly if we have the tab ID
injectContentScript('content/scraper.js', sender.tab.id)
.then(() => {
sendResponse({ success: true });
})
.catch(error => {
console.error('Error injecting script:', error);
sendResponse({ success: false, error: error.message });
});
}).catch(error => {
sendResponse({ success: false, error: 'Error validating tab: ' + error.message });
});
} else {
// Find the active tab and inject there
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs && tabs.length > 0) {
isValidTabForInjection(tabs[0].id).then(isValid => {
if (!isValid) {
sendResponse({
success: false,
error: 'Active tab is not on whatifsports.com or not fully loaded. Please navigate to a recruiting page first.'
});
return;
}
injectContentScript('content/scraper.js', tabs[0].id)
.then(() => {
sendResponse({ success: true });
})
.catch(error => {
console.error('Error injecting script:', error);
sendResponse({ success: false, error: error.message });
});
}).catch(error => {
sendResponse({ success: false, error: 'Error validating tab: ' + error.message });
});
} else {
sendResponse({ success: false, error: 'No active tab found' });
}
});
}
return true; // Indicate asynchronous response
case 'updateConsidering':
console.log('Handling updateConsidering request');
updateConsideringStatus()
.then(result => {
sendResponse({ success: true, result });
})
.catch(error => {
console.error('Error updating considering status:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response case 'scrapeRecruits':
console.log('Handling scrapeRecruits request');
// This can be handled similarly to syncRecruits
if (sender.tab && sender.tab.id) {
isValidTabForInjection(sender.tab.id).then(isValid => {
if (!isValid) {
sendResponse({
success: false,
error: 'Current tab is not on whatifsports.com or not fully loaded. Please navigate to a recruiting page first.'
});
return;
}
injectContentScript('content/scraper.js', sender.tab.id)
.then(() => {
sendResponse({ success: true });
})
.catch(error => {
console.error('Error injecting script:', error);
sendResponse({ success: false, error: error.message });
});
}).catch(error => {
sendResponse({ success: false, error: 'Error validating tab: ' + error.message });
});
} else {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs && tabs.length > 0) {
isValidTabForInjection(tabs[0].id).then(isValid => {
if (!isValid) {
sendResponse({
success: false,
error: 'Active tab is not on whatifsports.com or not fully loaded. Please navigate to a recruiting page first.'
});
return;
}
injectContentScript('content/scraper.js', tabs[0].id)
.then(() => {
sendResponse({ success: true });
})
.catch(error => {
console.error('Error injecting script:', error);
sendResponse({ success: false, error: error.message });
});
}).catch(error => {
sendResponse({ success: false, error: 'Error validating tab: ' + error.message });
});
} else {
sendResponse({ success: false, error: 'No active tab found' });
}
});
}
return true; // Indicate asynchronous response
case 'exportData':
console.log('Handling exportData request');
exportAllData()
.then(data => {
sendResponse({ success: true, data });
})
.catch(error => {
console.error('Error exporting data:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response case 'importData':
console.log('Handling importData request');
importData(message.data)
.then(result => {
sendResponse({ success: true, result });
})
.catch(error => {
console.error('Error importing data:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'fetchAndScrapeRecruits':
console.log('Fetching and scraping recruits from new tab');
// Handle refresh mode
const isRefreshOnly = message.isRefreshOnly || false;
const fieldsToUpdate = message.fieldsToUpdate || [];
// Get season number if provided - Save it BEFORE proceeding with other operations
let seasonPromise = Promise.resolve();
if (message.seasonNumber !== undefined && !isRefreshOnly) {
console.log(`Setting current season to ${message.seasonNumber}`);
seasonPromise = saveConfigSmart('currentSeason', message.seasonNumber)
.then(() => console.log('Season number saved successfully'))
.catch(err => console.error('Error saving season number:', err));
} // Only proceed with team info AFTER season number is saved
seasonPromise.then(() => {
// Get team info to determine appropriate URL
return getTeamInfoFromCookies();
}).then(async (teamInfo) => {
// Determine URL based on selected divisions or team division
const selectedDivisions = message.selectedDivisions || [];
let url;
if (selectedDivisions.length > 0 && !isRefreshOnly) {
// Use selected divisions from the modal for new season initialization
url = getUrlForSelectedDivisions(selectedDivisions);
console.log('Using selected divisions:', selectedDivisions);
// Store the URL for future refresh operations
try {
await saveConfigSmart(SEASON_RECRUITING_URL_KEY, url);
console.log('Stored recruiting URL for future refresh operations:', url);
} catch (error) {
console.error('Error storing recruiting URL:', error);
}
} else if (isRefreshOnly) {
// For refresh operations, try to use the stored URL first
try {
const storedUrl = await getConfigSmart(SEASON_RECRUITING_URL_KEY);
if (storedUrl) {
url = storedUrl;
console.log('✓ Using stored recruiting URL for refresh:', url);
} else {
// Fallback to team division if no stored URL
url = getUrlForDivision(teamInfo?.division);
console.log('⚠ No stored URL found, using team division fallback:', teamInfo?.division);
}
} catch (error) {
console.error('Error retrieving stored URL, using team division:', error);
url = getUrlForDivision(teamInfo?.division);
}
} else {
// Fallback to team division for new seasons when no divisions selected
url = getUrlForDivision(teamInfo?.division);
console.log('Using team division:', teamInfo?.division);
}
// Add url parameters for auto scrape mode
const urlWithParams = isRefreshOnly ?
`${url}&auto_scrape=true&refresh_mode=true` :
`${url}&auto_scrape=true`;
console.log(`Final recruiting URL with parameters: ${urlWithParams}`);
return { urlWithParams, teamInfo };
}).then(({ urlWithParams, teamInfo }) => {
// Store the fields to update if this is a refresh
if (isRefreshOnly && fieldsToUpdate.length > 0) {
saveConfigSmart('refreshFieldsToUpdate', JSON.stringify(fieldsToUpdate))
.catch(error => console.error('Error storing fields to update:', error));
} // Store the new tab ID when created for future reference
// Create tab in background (inactive) to make scraping less intrusive
chrome.tabs.create({
url: urlWithParams,
active: false // This keeps the tab in background
}).then(tab => {
currentScrapeTabId = tab.id;
console.log(`Created background tab with ID ${tab.id} for scraping`); // The background-overlay.js script will automatically load via manifest
// and detect the auto_scrape parameter to show the overlay
console.log('Background tab created, overlay script will auto-detect and display');
// Listen for tab to finish loading before injecting the scraper
const tabListener = (tabId, changeInfo) => {
if (tabId === tab.id && changeInfo.status === 'complete') {
console.log(`Tab ${tabId} finished loading, injecting scraper`);
// Remove the listener since we only need it once
chrome.tabs.onUpdated.removeListener(tabListener);
// Wait a moment for page to fully initialize
setTimeout(() => {
// Check if tab still exists before trying to inject script
chrome.tabs.get(tab.id).then(tabInfo => {
injectContentScript('content/scraper.js', tab.id)
.then(() => {
console.log('Scraper script injected successfully');
})
.catch(error => {
console.error('Error injecting scraper script:', error);
});
}).catch(error => {
console.error('Tab no longer exists, cannot inject script:', error);
// Remove the listener if not already removed
chrome.tabs.onUpdated.removeListener(tabListener);
});
}, 1000); // 1 second delay
}
};
// Add the listener
chrome.tabs.onUpdated.addListener(tabListener);
sendResponse({ success: true, tabId: tab.id });
}).catch(error => {
console.error('Error creating tab for scraping:', error);
sendResponse({ success: false, error: error.message });
});
}).catch(error => {
console.error('Error getting team info:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'refreshRecruitsComplete':
console.log(`Received ${message.recruits.length} updated recruits from refresh operation`);
// Update the recruits in the database
updateRefreshedRecruits(message.recruits).then(async result => {
// Clean up the temporary config
saveConfigSmart('refreshFieldsToUpdate', null)
.catch(error => console.error('Error clearing fields to update:', error));
// Update the last updated timestamp
saveConfigSmart('lastUpdated', new Date().toISOString());
// Recalculate and update the watchlist count to ensure it's accurate
const stats = await getStats(); // This will recalculate watchlist count
// Send a scrapeComplete message to notify the UI
chrome.runtime.sendMessage({
action: 'scrapeComplete',
success: true,
count: result.updated,
watchlistCount: stats.watchlistCount
});
// Respond to the content script
sendResponse({
success: true,
updated: result.updated,
watchlistCount: stats.watchlistCount
});
// Close the tab if requested
if (message.closeTab && sender.tab && sender.tab.id) {
chrome.tabs.remove(sender.tab.id)
.catch(error => console.error('Error closing tab:', error));
}
}).catch(error => {
console.error('Error updating refreshed recruits:', error);
sendResponse({
success: false,
error: error.message
});
});
return true; // Indicate asynchronous response
case 'recruitsScraped':
// Handle scraped recruits from the content script
console.log(`Received ${message.recruits.length} scraped recruits from content script`);
// Check for error message
if (message.error) {
console.error('Error reported from scraper:', message.error);
// Notify listeners of error
chrome.runtime.sendMessage({
action: 'scrapeComplete',
success: false,
error: message.error,
count: 0
});
sendResponse({
success: false,
error: message.error
});
return true;
}
// Save the scraped recruits
saveRecruits(message.recruits).then(async result => {
// Update last updated timestamp using smart router
try {
await saveConfigSmart('lastUpdated', new Date().toISOString());
console.log('✅ Updated lastUpdated timestamp via smart router');
} catch (error) {
console.warn('⚠️ Error updating lastUpdated timestamp:', error);
}
// Update team counts after bulk operation (performance optimized)
try {
await multiTeamStorage.updateTeamCountsIfNeeded();
console.log('Team counts updated after bulk recruit save operation');
} catch (error) {
console.warn('Error updating team counts after bulk save:', error);
}
// Notify any listeners (such as the popup) that scraping is complete
chrome.runtime.sendMessage({
action: 'scrapeComplete',
success: true,
count: result.count
});
sendResponse({
success: true,
count: result.count
});
}).catch(error => {
console.error('Error saving scraped recruits:', error);
// Notify listeners of error
chrome.runtime.sendMessage({
action: 'scrapeComplete',
success: false,
error: error.message,
count: 0
});
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'closeScraperTab':
// Close the tab after the content script has received our response
if (message.tabId) {
chrome.tabs.get(message.tabId)
.then(tabInfo => {
// Tab still exists, close it
chrome.tabs.remove(message.tabId)
.then(() => {
console.log(`Tab with ID ${message.tabId} closed successfully`);
// Clear the stored tab ID if it matches
if (currentScrapeTabId === message.tabId) {
currentScrapeTabId = null;
}
// Send success response
sendResponse({ success: true });
})
.catch(error => {
console.error('Error closing tab:', error);
sendResponse({ success: false, error: error.message });
});
})
.catch(error => {
// Tab doesn't exist anymore
console.log(`Tab with ID ${message.tabId} no longer exists:`, error);
if (currentScrapeTabId === message.tabId) {
currentScrapeTabId = null;
}
sendResponse({ success: true, message: 'Tab already closed' });
});
} else if (sender.tab) {
chrome.tabs.get(sender.tab.id)
.then(tabInfo => {
// Tab still exists, close it
chrome.tabs.remove(sender.tab.id)
.then(() => {
console.log(`Tab with ID ${sender.tab.id} closed successfully`);
// Clear the stored tab ID if it matches
if (currentScrapeTabId === sender.tab.id) {
currentScrapeTabId = null;
}
// Send success response
sendResponse({ success: true });
})
.catch(error => {
console.error('Error closing tab:', error);
sendResponse({ success: false, error: error.message });
});
})
.catch(error => {
// Tab doesn't exist anymore
console.log(`Tab with ID ${sender.tab.id} no longer exists:`, error);
if (currentScrapeTabId === sender.tab.id) {
currentScrapeTabId = null;
} sendResponse({ success: true, message: 'Tab already closed' });
});
} else {
sendResponse({ success: false, error: 'No tab ID provided' });
} return true; // Indicate asynchronous response
case 'getRecruits':
// Retrieve recruits from database using multi-team storage
console.log('Getting all recruits from multi-team storage');
(async () => {
try {
await multiTeamStorage.init();
const recruits = await multiTeamStorage.getAllRecruits();
sendResponse({ recruits });
} catch (error) {
console.error('Error getting recruits:', error);
sendResponse({ error: error.message });
}
})();
return true; // Indicate asynchronous response
case 'getStats':
// Get extension stats using multi-team storage
console.log('Handling getStats request');
(async () => {
try {
await multiTeamStorage.init();
// Get current team info
const currentTeam = await multiTeamStorage.getCurrentTeam();
if (currentTeam) {
// Get team-specific stats
const stats = await multiTeamStorage.getTeamStats(currentTeam.teamId);
sendResponse(stats);
} else {
// Fallback to legacy storage if no active team
const stats = await getStats();
sendResponse(stats);
}
} catch (error) {
console.error('Error getting stats:', error);
sendResponse({ error: error.message });
}
})();
return true; // Indicate asynchronous response
case 'clearTeamData':
// Clear data for a specific team
console.log('Handling clearTeamData request for team:', message.teamId);
clearTeamData(message.teamId)
.then(result => {
sendResponse(result);
})
.catch(error => {
console.error('Error clearing team data:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'clearCurrentTeamOnly':
// Clear data for current team only (new action for single-team clearing)
console.log('Handling clearCurrentTeamOnly request');
clearCurrentTeamOnly()
.then(result => {
sendResponse(result);
})
.catch(error => {
console.error('Error clearing current team data:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'clearAllData':
// Clear all extension data
console.log('Handling clearAllData request');
clearAllData()
.then(result => {
sendResponse(result);
})
.catch(error => {
console.error('Error clearing data:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'resetAllSettings':
// Reset all extension settings to defaults
console.log('Handling resetAllSettings request');
resetAllSettings()
.then(result => {
sendResponse(result);
})
.catch(error => {
console.error('Error resetting settings:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'checkDatabaseStatus':
// Check database diagnostic status
console.log('Handling checkDatabaseStatus request');
checkDatabaseStatus()
.then(dbInfo => {
sendResponse({ success: true, dbInfo });
})
.catch(error => {
console.error('Error checking database status:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Indicate asynchronous response
case 'saveConfig':
// Save configuration setting - use appropriate storage based on data type
console.log(`Saving config: ${message.key} = ${message.value}`);
if (TEAM_SPECIFIC_CONFIG_KEYS.includes(message.key)) {
// Use smart router for team-specific data - NEVER fall back to legacy
(async () => {
try {
await saveConfigSmart(message.key, message.value);
sendResponse({ success: true });
} catch (error) {
console.error('Error saving team-specific config via smart router:', error);
sendResponse({ success: false, error: error.message });
}
})();
} else {
// Use multi-team storage for global configurations
(async () => {
try {
await multiTeamStorage.saveGlobalConfig(message.key, message.value);
sendResponse({ success: true });
} catch (error) {
console.error('Error saving global config:', error);
sendResponse({ success: false, error: error.message });
}
})();
}
return true; // Indicate asynchronous response
case 'getConfig':
// Get configuration setting - use appropriate storage based on data type
console.log(`Getting config: ${message.key}`);
if (TEAM_SPECIFIC_CONFIG_KEYS.includes(message.key)) {
// Use smart router for team-specific data - NEVER fall back to legacy
(async () => {
try {
const value = await getConfigSmart(message.key);
sendResponse({ success: true, value });
} catch (error) {
console.error('Error getting team-specific config via smart router:', error);
sendResponse({ success: false, error: error.message });
}
})();
} else {
// Use multi-team storage for global configurations
(async () => {
try {
const value = await multiTeamStorage.getGlobalConfig(message.key);
sendResponse({ success: true, value });
} catch (error) {
console.error('Error getting global config:', error);
sendResponse({ success: false, error: error.message });
}
})();
}
return true; // Indicate asynchronous response
case 'getRoleRatings':
// Get current role ratings for editing
console.log('Getting current role ratings');
getCurrentRoleRatings()
.then(ratings => {
sendResponse({ success: true, ratings: ratings });
})
.catch(error => {
console.error('Error getting role ratings:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'calculateRoleRating':
// Calculate role ratings for a specific recruit
console.log('Calculating role rating for recruit:', message.recruit);
calculateRoleRating(message.recruit)
.then(ratings => {
sendResponse({ success: true, data: ratings });
})
.catch(error => {
console.error('Error calculating role rating:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'saveRoleRatings':
// Save custom role ratings and recalculate across all teams
console.log('Saving custom role ratings with cross-team support');
saveRoleRatings(message.ratings)
.then(async () => {
const changedPositions = message.changedPositions || null;
console.log('Role ratings saved, starting cross-team recalculation...');
// Use cross-team recalculation for immediate consistency
const recalcResult = await recalculateRoleRatingsAllTeams(changedPositions);
// Broadcast the update
broadcastDataUpdate('roleRatingsSaved', {
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits,
teamsProcessed: recalcResult.teamsProcessed,
changedPositions: changedPositions
});
sendResponse({
success: true,
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits,
teamsProcessed: recalcResult.teamsProcessed
});
})
.catch(error => {
console.error('Error saving role ratings:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'resetRoleRatings':
// Reset role ratings to defaults with cross-team recalculation
console.log('Resetting role ratings to defaults with cross-team support');
resetRoleRatingsToDefaults()
.then(async () => {
console.log('Role ratings reset, starting cross-team recalculation...');
// Recalculate all role ratings across all teams
const recalcResult = await recalculateRoleRatingsAllTeams();
// Broadcast the update
broadcastDataUpdate('roleRatingsReset', {
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits,
teamsProcessed: recalcResult.teamsProcessed
});
sendResponse({
success: true,
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits,
teamsProcessed: recalcResult.teamsProcessed
});
})
.catch(error => {
console.error('Error resetting role ratings:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'resetPositionRoleRatings':
// Reset role ratings for a specific position
console.log('Resetting role ratings for position:', message.position);
resetRoleRatingsToDefaults(message.position)
.then(async () => {
// Recalculate role ratings for this position
const recalcResult = await recalculateRoleRatings([message.position]);
// Broadcast the update
broadcastDataUpdate('positionRoleRatingsReset', {
position: message.position,
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits
});
sendResponse({
success: true,
position: message.position,
recalculated: recalcResult.updatedCount,
totalRecruits: recalcResult.totalRecruits
});
})
.catch(error => {
console.error('Error resetting position role ratings:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'recalculateRoleRatings':
// Manually trigger recalculation with cross-team support
console.log('Manually recalculating role ratings with cross-team support');
recalculateRoleRatingsAllTeams(message.positions)
.then(result => {
// Broadcast the update
broadcastDataUpdate('roleRatingsRecalculated', {
recalculated: result.updatedCount,
totalRecruits: result.totalRecruits,
teamsProcessed: result.teamsProcessed,
positions: message.positions
});
sendResponse({
success: true,
recalculated: result.updatedCount,
totalRecruits: result.totalRecruits,
teamsProcessed: result.teamsProcessed
});
})
.catch(error => {
console.error('Error recalculating role ratings:', error);
sendResponse({ success: false, error: error.message });
});
return true;
case 'checkRoleRatingsStatus':
// Check role ratings status for diagnostics
console.log('Checking role ratings status');
(async () => {
try {
// Load settings from global storage to check status
const customRatings = await multiTeamStorage.getGlobalConfig('customRoleRatings');
const defaultRatings = await multiTeamStorage.getGlobalConfig('defaultRoleRatings');
const currentSeason = await getConfigSmart('currentSeason');
// Parse data for validation if available
let customRatingsValid = false;