-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathscrumHelper.js
More file actions
2094 lines (1890 loc) · 73.6 KB
/
scrumHelper.js
File metadata and controls
2094 lines (1890 loc) · 73.6 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
const DEBUG = false;
function log(...args) {
if (DEBUG) {
console.log(`[SCRUM-HELPER]:`, ...args);
}
}
function logError(...args) {
if (DEBUG) {
console.error('[SCRUM-HELPER]:', ...args);
}
}
let refreshButton_Placed = false;
let enableToggle = true;
let hasInjectedContent = false;
let scrumGenerationInProgress = false;
let orgName = '';
let platform = 'github';
let platformUsername = '';
let gitlabToken = '';
let gitlabHelper = null;
function allIncluded(outputTarget = 'email') {
// Always re-instantiate gitlabHelper for gitlab platform to ensure fresh cache after refresh
if (platform === 'gitlab' || (typeof platform === 'undefined' && window.GitLabHelper)) {
gitlabHelper = new window.GitLabHelper();
}
if (scrumGenerationInProgress) {
return;
}
scrumGenerationInProgress = true;
console.log('allIncluded called with outputTarget:', outputTarget);
let scrumBody = null;
let scrumSubject = null;
let startingDate = '';
let endingDate = '';
let platformUsernameLocal = '';
let githubToken = '';
let projectName = '';
let lastWeekArray = [];
let nextWeekArray = [];
let reviewedPrsArray = [];
let githubIssuesData = null;
let yesterdayContribution = false;
let githubPrsReviewData = null;
let githubUserData = null;
let githubPrsReviewDataProcessed = {};
let issuesDataProcessed = false;
let prsReviewDataProcessed = false;
let showOpenLabel = true;
let showCommits = false;
let userReason = '';
let subjectForEmail = null;
let onlyIssues = false;
let onlyPRs = false;
let onlyRevPRs = false;
const pr_open_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #2cbe4e;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--green">open</div>';
const pr_closed_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color:rgb(210, 20, 39);border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--red">closed</div>';
const pr_merged_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #6f42c1;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--purple">merged</div>';
const pr_draft_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #808080;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--gray">draft</div>';
const issue_closed_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #d73a49;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--red">closed</div>';
const issue_opened_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #2cbe4e;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--green">open</div>';
const issue_closed_completed_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #6f42c1;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--purple">closed</div>';
const issue_closed_notplanned_button =
'<div style="vertical-align:middle;display: inline-block;padding: 0px 4px;font-size:9px;font-weight: 600;color: #fff;text-align: center;background-color: #808080;border-radius: 3px;line-height: 12px;margin-bottom: 2px;" class="State State--gray">closed</div>';
function getChromeData() {
console.log('[DEBUG] getChromeData called for outputTarget:', outputTarget);
chrome.storage.local.get(
[
'platform',
'githubUsername',
'gitlabUsername',
'githubToken',
'gitlabToken',
'projectName',
'enableToggle',
'startingDate',
'endingDate',
'showOpenLabel',
'yesterdayContribution',
'userReason',
'githubCache',
'cacheInput',
'orgName',
'selectedRepos',
'useRepoFilter',
'showCommits',
'onlyIssues',
'onlyPRs',
'onlyRevPRs',
],
(items) => {
console.log('[DEBUG] Storage items received:', items);
platform = items.platform || 'github';
// Load platform-specific username
const platformUsernameKey = `${platform}Username`;
platformUsername = items[platformUsernameKey] || '';
platformUsernameLocal = platformUsername;
console.log(`[DEBUG] platform: ${platform}, platformUsername: ${platformUsername}`);
if (outputTarget === 'popup') {
const usernameFromDOM = document.getElementById('platformUsername')?.value;
const projectFromDOM = document.getElementById('projectName')?.value;
const tokenFromDOM = document.getElementById('githubToken')?.value;
const gitlabTokenFromDOM = document.getElementById('gitlabToken')?.value;
// Save to platform-specific storage
if (usernameFromDOM) {
chrome.storage.local.set({ [platformUsernameKey]: usernameFromDOM });
platformUsername = usernameFromDOM;
platformUsernameLocal = usernameFromDOM;
}
items.projectName = projectFromDOM || items.projectName;
items.githubToken = tokenFromDOM || items.githubToken;
items.gitlabToken = gitlabTokenFromDOM || items.gitlabToken;
chrome.storage.local.set({
projectName: items.projectName,
githubToken: items.githubToken,
gitlabToken: items.gitlabToken,
});
}
projectName = items.projectName;
userReason = 'No Blocker at the moment';
chrome.storage.local.remove(['userReason']);
githubToken = items.githubToken;
gitlabToken = items.gitlabToken || '';
yesterdayContribution = items.yesterdayContribution;
if (typeof items.enableToggle !== 'undefined') {
enableToggle = items.enableToggle;
}
onlyIssues = items.onlyIssues === true;
onlyPRs = items.onlyPRs === true;
onlyRevPRs = items.onlyRevPRs === true;
console.log('[SCRUM-DEBUG] loaded flags:', { onlyIssues, onlyPRs, onlyRevPRs });
// Enforce mutual exclusivity between onlyIssues and onlyPRs to avoid filtering out everything
if (onlyIssues && onlyPRs) {
console.warn('[SCRUM-HELPER]: Detected both onlyIssues and onlyPRs enabled; normalizing to onlyIssues.');
onlyPRs = false;
}
showCommits = items.showCommits || false;
showOpenLabel = items.showOpenLabel !== false; // Default to true if not explicitly set to false
orgName = items.orgName || '';
if (items.yesterdayContribution) {
handleYesterdayContributionChange();
} else if (items.startingDate && items.endingDate) {
startingDate = items.startingDate;
endingDate = items.endingDate;
} else {
handleYesterdayContributionChange();
if (outputTarget === 'popup') {
chrome.storage.local.set({ yesterdayContribution: true });
}
}
if (platform === 'github') {
if (platformUsernameLocal) {
fetchGithubData();
} else {
if (outputTarget === 'popup') {
console.log('[DEBUG] No username found - popup context');
const scrumReport = document.getElementById('scrumReport');
const generateBtn = document.getElementById('generateReport');
if (scrumReport) {
scrumReport.innerHTML =
'<div class="error-message" style="color: #dc2626; font-weight: bold; padding: 10px;">Please enter your username to generate a report.</div>';
}
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
scrumGenerationInProgress = false;
} else {
console.warn('[DEBUG] No username found in storage');
scrumGenerationInProgress = false;
}
return;
}
} else if (platform === 'gitlab') {
if (!gitlabHelper) gitlabHelper = new window.GitLabHelper();
if (platformUsernameLocal) {
const generateBtn = document.getElementById('generateReport');
if (generateBtn && outputTarget === 'popup') {
generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating...';
generateBtn.disabled = true;
}
if (outputTarget === 'email') {
(async () => {
try {
const data = await gitlabHelper.fetchGitLabData(
platformUsernameLocal,
startingDate,
endingDate,
gitlabToken,
);
function mapGitLabItem(item, projects, type) {
const project = projects.find((p) => p.id === item.project_id);
const repoName = project ? project.name : 'unknown';
return {
...item,
repository_url: `https://gitlab.com/api/v4/projects/${item.project_id}`,
html_url:
type === 'issue'
? item.web_url || (project ? `${project.web_url}/-/issues/${item.iid}` : '')
: item.web_url || (project ? `${project.web_url}/-/merge_requests/${item.iid}` : ''),
number: item.iid,
title: item.title,
state: type === 'issue' && item.state === 'opened' ? 'open' : item.state,
project: repoName,
pull_request: type === 'mr',
};
}
const mappedIssues = (data.issues || []).map((issue) => mapGitLabItem(issue, data.projects, 'issue'));
const mappedMRs = (data.mergeRequests || data.mrs || []).map((mr) =>
mapGitLabItem(mr, data.projects, 'mr'),
);
const mappedData = {
githubIssuesData: { items: mappedIssues },
githubPrsReviewData: { items: mappedMRs },
githubUserData: data.user || {},
};
githubUserData = mappedData.githubUserData;
const name =
githubUserData?.name || githubUserData?.username || platformUsernameLocal || platformUsername;
const project = projectName;
const curDate = new Date();
const year = curDate.getFullYear().toString();
let date = curDate.getDate();
let month = curDate.getMonth() + 1;
if (month < 10) month = '0' + month;
if (date < 10) date = '0' + date;
const dateCode = year.toString() + month.toString() + date.toString();
const subject = `[Scrum]${project ? ' - ' + project : ''} - ${dateCode}`;
subjectForEmail = subject;
await processGithubData(mappedData, true, subjectForEmail);
scrumGenerationInProgress = false;
} catch (err) {
console.error('GitLab fetch failed:', err);
if (outputTarget === 'popup') {
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
const scrumReport = document.getElementById('scrumReport');
if (scrumReport) {
scrumReport.innerHTML = `<div class=\"error-message\" style=\"color: #dc2626; font-weight: bold; padding: 10px;\">${err.message || 'An error occurred while fetching GitLab data.'}</div>`;
}
}
scrumGenerationInProgress = false;
}
})();
} else {
gitlabHelper
.fetchGitLabData(platformUsernameLocal, startingDate, endingDate, gitlabToken)
.then((data) => {
function mapGitLabItem(item, projects, type) {
const project = projects.find((p) => p.id === item.project_id);
const repoName = project ? project.name : 'unknown';
return {
...item,
repository_url: `https://gitlab.com/api/v4/projects/${item.project_id}`,
html_url:
type === 'issue'
? item.web_url || (project ? `${project.web_url}/-/issues/${item.iid}` : '')
: item.web_url || (project ? `${project.web_url}/-/merge_requests/${item.iid}` : ''),
number: item.iid,
title: item.title,
state: type === 'issue' && item.state === 'opened' ? 'open' : item.state,
project: repoName,
pull_request: type === 'mr',
};
}
const mappedIssues = (data.issues || []).map((issue) => mapGitLabItem(issue, data.projects, 'issue'));
const mappedMRs = (data.mergeRequests || data.mrs || []).map((mr) =>
mapGitLabItem(mr, data.projects, 'mr'),
);
const mappedData = {
githubIssuesData: { items: mappedIssues },
githubPrsReviewData: { items: mappedMRs },
githubUserData: data.user || {},
};
processGithubData(mappedData);
scrumGenerationInProgress = false;
})
.catch((err) => {
console.error('GitLab fetch failed:', err);
if (outputTarget === 'popup') {
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
const scrumReport = document.getElementById('scrumReport');
if (scrumReport) {
scrumReport.innerHTML = `<div class=\"error-message\" style=\"color: #dc2626; font-weight: bold; padding: 10px;\">${err.message || 'An error occurred while fetching GitLab data.'}</div>`;
}
}
scrumGenerationInProgress = false;
});
}
// --- FIX END ---
} else {
if (outputTarget === 'popup') {
const scrumReport = document.getElementById('scrumReport');
const generateBtn = document.getElementById('generateReport');
if (scrumReport) {
scrumReport.innerHTML =
'<div class="error-message" style="color: #dc2626; font-weight: bold; padding: 10px;">Please enter your username to generate a report.</div>';
}
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
}
scrumGenerationInProgress = false;
}
} else {
// Unknown platform
if (outputTarget === 'popup') {
const scrumReport = document.getElementById('scrumReport');
if (scrumReport) {
scrumReport.innerHTML =
'<div class="error-message" style="color: #dc2626; font-weight: bold; padding: 10px;">Unknown platform selected.</div>';
}
}
scrumGenerationInProgress = false;
}
},
);
}
getChromeData();
function handleYesterdayContributionChange() {
endingDate = getToday();
startingDate = getYesterday();
}
function getYesterday() {
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
return yesterday.toISOString().split('T')[0];
}
function getToday() {
const today = new Date();
return today.toISOString().split('T')[0];
}
// Global cache object
const githubCache = {
data: null,
cacheKey: null,
timestamp: 0,
ttl: 10 * 60 * 1000, // cache valid for 10 mins
fetching: false,
queue: [],
errors: {},
errorTTL: 60 * 1000, // 1 min error cache
subject: null,
repoData: null,
repoCacheKey: null,
repoTimeStamp: 0,
repoFetching: false,
repoQueue: [],
};
async function getCacheTTL() {
return new Promise((resolve) => {
chrome.storage.local.get(['cacheInput'], (result) => {
const ttlMinutes = result.cacheInput || 10;
resolve(ttlMinutes * 60 * 1000);
});
});
}
function saveToStorage(data, subject = null) {
const cacheData = {
data: data,
cacheKey: githubCache.cacheKey,
timestamp: githubCache.timestamp,
subject: subject,
usedToken: !!githubToken,
};
log(`Saving data to storage:`, {
cacheKey: githubCache.cacheKey,
timestamp: githubCache.timestamp,
hasSubject: !!subject,
});
return new Promise((resolve) => {
chrome.storage.local.set({ githubCache: cacheData }, () => {
if (chrome.runtime.lastError) {
logError('Storage save failed: ', chrome.runtime.lastError);
resolve(false);
} else {
log('Cache saved successfuly');
githubCache.data = data;
githubCache.subject = subject;
resolve(true);
}
});
});
}
function loadFromStorage() {
log('Loading cache from storage');
return getCacheTTL().then((currentTTL) => {
return new Promise((resolve) => {
chrome.storage.local.get('githubCache', (result) => {
const cache = result.githubCache;
if (!cache) {
log('No cache found in storage');
resolve(false);
return;
}
const isCacheExpired = Date.now() - cache.timestamp > currentTTL;
if (isCacheExpired) {
log('Cached data is expired');
resolve(false);
return;
}
log('Found valid cache:', {
cacheKey: cache.cacheKey,
age: `${((Date.now() - cache.timestamp) / 1000 / 60).toFixed(1)} minutes`,
});
githubCache.data = cache.data;
githubCache.cacheKey = cache.cacheKey;
githubCache.timestamp = cache.timestamp;
githubCache.subject = cache.subject;
githubCache.usedToken = cache.usedToken || false;
if (cache.subject && scrumSubject) {
scrumSubject.value = cache.subject;
scrumSubject.dispatchEvent(new Event('input', { bubbles: true }));
}
resolve(true);
});
});
});
}
async function fetchGithubData() {
// Always load latest repo filter settings from storage
const filterSettings = await new Promise((resolve) => {
chrome.storage.local.get(['useRepoFilter', 'selectedRepos'], resolve);
});
useRepoFilter = filterSettings.useRepoFilter || false;
selectedRepos = Array.isArray(filterSettings.selectedRepos) ? filterSettings.selectedRepos : [];
// Get the correct date range for cache key
let startDateForCache;
let endDateForCache;
if (yesterdayContribution) {
const today = new Date();
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
startDateForCache = yesterday.toISOString().split('T')[0];
endDateForCache = today.toISOString().split('T')[0]; // Use yesterday for start and today for end
} else if (startingDate && endingDate) {
startDateForCache = startingDate;
endDateForCache = endingDate;
} else {
// Default to last 7 days if no date range is set
const today = new Date();
const lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
startDateForCache = lastWeek.toISOString().split('T')[0];
endDateForCache = today.toISOString().split('T')[0];
}
const cacheKey = `${platformUsernameLocal}-${startDateForCache}-${endDateForCache}-${orgName || 'all'}`;
if (githubCache.fetching || (githubCache.cacheKey === cacheKey && githubCache.data)) {
log('Fetch already in progress or data already fetched. Skipping fetch.');
return;
}
log('Fetching Github data:', {
username: platformUsernameLocal,
startDate: startingDate,
endDate: endingDate,
});
log('CacheKey in cache:', githubCache.cacheKey);
log('Incoming cacheKey:', cacheKey);
log('Has data:', !!githubCache.data);
// Check if we need to load from storage
if (!githubCache.data && !githubCache.fetching) {
await loadFromStorage();
}
const currentTTL = await getCacheTTL();
githubCache.ttl = currentTTL;
log(`Caching for ${currentTTL / (60 * 1000)} minutes`);
const now = Date.now();
const isCacheFresh = now - githubCache.timestamp < githubCache.ttl;
const isCacheKeyMatch = githubCache.cacheKey === cacheKey;
const needsToken = !!githubToken;
const cacheUsedToken = !!githubCache.usedToken;
if (githubCache.data && isCacheFresh && isCacheKeyMatch) {
if (needsToken && !cacheUsedToken) {
log('Cache was fetched without token, but user now has a token. Invalidating cache.');
githubCache.data = null;
} else {
log('Using cached data - cache is fresh and key matches');
processGithubData(githubCache.data);
return Promise.resolve();
}
}
if (!isCacheKeyMatch) {
log('Cache key mismatch - fetching new Data');
githubCache.data = null;
} else if (!isCacheFresh) {
log('Cache is stale - fetching new data');
}
if (githubCache.fetching) {
log('Fetch in progress, queuing requests');
return new Promise((resolve, reject) => {
githubCache.queue.push({ resolve, reject });
});
}
githubCache.fetching = true;
githubCache.cacheKey = cacheKey;
githubCache.usedToken = !!githubToken;
const headers = {
Accept: 'application/vnd.github.v3+json',
};
if (githubToken) {
log('Making authenticated requests.');
headers.Authorization = `token ${githubToken}`;
} else {
log('Making public requests');
}
console.log('[SCRUM-HELPER] orgName before API query:', orgName);
console.log('[SCRUM-HELPER] orgName type:', typeof orgName);
console.log('[SCRUM-HELPER] orgName length:', orgName ? orgName.length : 0);
const orgPart = orgName && orgName.trim() ? `+org%3A${orgName}` : '';
console.log('[SCRUM-HELPER] orgPart for API:', orgPart);
console.log('[SCRUM-HELPER] orgPart length:', orgPart.length);
let issueUrl;
let prUrl;
let userUrl;
if (useRepoFilter && selectedRepos && selectedRepos.length > 0) {
log('Using repo filter for api calls:', selectedRepos);
try {
await fetchReposIfNeeded();
} catch (err) {
logError('Failed to fetch repo data for filtering:', err);
}
const repoQueries = selectedRepos
.filter((repo) => repo !== null)
.map((repo) => {
if (typeof repo === 'object' && repo.fullName) {
const cleanName = repo.fullName.startsWith('/') ? repo.fullName.substring(1) : repo.fullName;
return `repo:${cleanName}`;
}
if (repo.includes('/')) {
const cleanName = repo.startsWith('/') ? repo.substring(1) : repo;
return `repo:${cleanName}`;
}
const fullRepoInfo = githubCache.repoData?.find((r) => r.name === repo);
if (fullRepoInfo && fullRepoInfo.fullName) {
return `repo:${fullRepoInfo.fullName}`;
}
logError(`Missing owner for repo ${repo} - search may fail`);
return `repo:${repo}`;
})
.join('+');
const orgQuery = orgPart ? `+${orgPart}` : '';
if (!repoQueries) {
loadFromStorage('Repo filter empty, using org wide search');
issueUrl = `https://api.github.com/search/issues?q=author%3A${platformUsernameLocal}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
prUrl = `https://api.github.com/search/issues?q=commenter%3A${platformUsernameLocal}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
userUrl = `https://api.github.com/users/${platformUsernameLocal}`;
} else {
issueUrl = `https://api.github.com/search/issues?q=author%3A${platformUsernameLocal}+${repoQueries}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
prUrl = `https://api.github.com/search/issues?q=commenter%3A${platformUsernameLocal}+${repoQueries}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
userUrl = `https://api.github.com/users/${platformUsernameLocal}`;
log('Repository-filtered URLs:', { issueUrl, prUrl });
}
} else {
loadFromStorage('Using org wide search');
const orgQuery = orgPart ? `+${orgPart}` : '';
issueUrl = `https://api.github.com/search/issues?q=author%3A${platformUsernameLocal}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
prUrl = `https://api.github.com/search/issues?q=commenter%3A${platformUsernameLocal}${orgQuery}+updated%3A${startDateForCache}..${endDateForCache}&per_page=100`;
userUrl = `https://api.github.com/users/${platformUsernameLocal}`;
}
try {
await new Promise((res) => setTimeout(res, 500));
log('Validating GitHub user existence for:', platformUsernameLocal);
const userCheckRes = await fetch(userUrl, { headers });
if (userCheckRes.status === 404) {
const errorMsg = `GitHub user "${platformUsernameLocal}" not found (404). Please check the username and try again.`;
logError(errorMsg);
throw new Error(errorMsg);
}
if (userCheckRes.status === 401 || userCheckRes.status === 403) {
showInvalidTokenMessage();
githubCache.fetching = false;
return;
}
if (!userCheckRes.ok) {
const errorMsg = `Error validating GitHub user: ${userCheckRes.status} ${userCheckRes.statusText}`;
logError(errorMsg);
throw new Error(errorMsg);
}
const [issuesRes, prRes, userRes] = await Promise.all([
fetch(issueUrl, { headers }),
fetch(prUrl, { headers }),
userCheckRes, // Reuse the already validated user response
]);
if (issuesRes.status === 401 || prRes.status === 401 || issuesRes.status === 403 || prRes.status === 403) {
showInvalidTokenMessage();
githubCache.fetching = false;
return;
}
if (issuesRes.status === 422 || prRes.status === 422) {
const errorMsg = `Invalid search query or date range. Please verify your date range format and try again.`;
logError(errorMsg);
if (outputTarget === 'popup') {
Materialize.toast && Materialize.toast(errorMsg, 4000);
}
throw new Error(errorMsg);
}
if (!issuesRes.ok) {
const errorMsg = `Error fetching GitHub issues: ${issuesRes.status} ${issuesRes.statusText}`;
logError(errorMsg);
if (outputTarget === 'popup') {
Materialize.toast && Materialize.toast(errorMsg, 4000);
}
throw new Error(errorMsg);
}
if (!prRes.ok) {
const errorMsg = `Error fetching GitHub PR review data: ${prRes.status} ${prRes.statusText}`;
logError(errorMsg);
if (outputTarget === 'popup') {
Materialize.toast && Materialize.toast(errorMsg, 4000);
}
throw new Error(errorMsg);
}
if (!userRes.ok) {
const errorMsg = `Error fetching GitHub user data: ${userRes.status} ${userRes.statusText}`;
logError(errorMsg);
throw new Error(errorMsg);
}
githubIssuesData = await issuesRes.json();
githubPrsReviewData = await prRes.json();
githubUserData = await userRes.json();
if (githubIssuesData && githubIssuesData.items) {
log('Fetched githubIssuesData:', githubIssuesData.items.length, 'items');
// Collect only open PRs for commit fetching
const openPRs = githubIssuesData.items.filter((item) => item.pull_request && item.state === 'open');
log(
'Open PRs for commit fetching:',
openPRs.map((pr) => pr.number),
);
// Fetch commits for open PRs (batch) if showCommits is enabled
if (openPRs.length && githubToken && showCommits) {
let startDateForCommits;
let endDateForCommits;
if (yesterdayContribution) {
const today = new Date();
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
startDateForCommits = yesterday.toISOString().split('T')[0];
endDateForCommits = today.toISOString().split('T')[0]; // Use yesterday for start and today for end
} else if (startingDate && endingDate) {
startDateForCommits = startingDate;
endDateForCommits = endingDate;
} else {
// Default to last 7 days if no date range is set
const today = new Date();
const lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
startDateForCommits = lastWeek.toISOString().split('T')[0];
endDateForCommits = today.toISOString().split('T')[0];
}
const commitMap = await fetchCommitsForOpenPRs(openPRs, githubToken, startDateForCommits, endDateForCommits);
log('Commit map returned from fetchCommitsForOpenPRs:', commitMap);
// Attach commits to PR objects
openPRs.forEach((pr) => {
pr._allCommits = commitMap[pr.number] || [];
log(`Attached ${pr._allCommits.length} commits to PR #${pr.number}`);
if (pr._allCommits.length > 0) {
log(
`Commits for PR #${pr.number}:`,
pr._allCommits.map((c) => `${c.messageHeadline} (${c.committedDate})`),
);
}
});
}
}
// Cache the data
githubCache.data = { githubIssuesData, githubPrsReviewData, githubUserData };
githubCache.timestamp = Date.now();
await saveToStorage(githubCache.data);
processGithubData(githubCache.data);
githubCache.queue.forEach(({ resolve }) => {
resolve();
});
githubCache.queue = [];
} catch (err) {
logError('Fetch Failed:', err);
// Reject queued calls on error
githubCache.queue.forEach(({ reject }) => {
reject(err);
});
githubCache.queue = [];
githubCache.fetching = false;
if (outputTarget === 'popup') {
const generateBtn = document.getElementById('generateReport');
if (scrumReport) {
let errorMsg = 'An error occurred while generating the report.';
if (err) {
if (typeof err === 'string') errorMsg = err;
else if (err.message) errorMsg = err.message;
else errorMsg = JSON.stringify(err);
}
scrumReport.innerHTML = `<div class="error-message" style="color: #dc2626; font-weight: bold; padding: 10px;">${err.message || 'An error occurred while generating the report.'}</div>`;
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
}
scrumGenerationInProgress = false;
throw err;
} finally {
githubCache.fetching = false;
}
}
async function fetchCommitsForOpenPRs(prs, githubToken, startDate, endDate) {
log(
'fetchCommitsForOpenPRs called with PRs:',
prs.map((pr) => pr.number),
'startDate:',
startDate,
'endDate:',
endDate,
);
if (!prs.length) return {};
const since = new Date(startDate + 'T00:00:00Z').toISOString();
const until = new Date(endDate + 'T23:59:59Z').toISOString();
const queries = prs
.map((pr, idx) => {
const repoParts = pr.repository_url.split('/');
const owner = repoParts[repoParts.length - 2];
const repo = repoParts[repoParts.length - 1];
return `
pr${idx}: repository(owner: "${owner}", name: "${repo}") {
pullRequest(number: ${pr.number}) {
commits(first: 100) {
nodes {
commit {
messageHeadline
committedDate
url
author {
name
user { login }
}
}
}
}
}
}`;
})
.join('\n');
const query = `query { ${queries} }`;
log('GraphQL query for commits:', query);
const res = await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(githubToken ? { Authorization: `bearer ${githubToken}` } : {}),
},
body: JSON.stringify({ query }),
});
log('fetchCommitsForOpenPRs response status:', res.status);
const data = await res.json();
log('fetchCommitsForOpenPRs response data:', data);
const commitMap = {};
prs.forEach((pr, idx) => {
const prData = data.data && data.data[`pr${idx}`] && data.data[`pr${idx}`].pullRequest;
if (prData && prData.commits && prData.commits.nodes) {
const allCommits = prData.commits.nodes.map((n) => n.commit);
log(`PR #${pr.number} allCommits:`, allCommits);
const filteredCommits = allCommits.filter((commit) => {
const commitDate = new Date(commit.committedDate);
const sinceDate = new Date(since);
const untilDate = new Date(until);
const isInRange = commitDate >= sinceDate && commitDate <= untilDate;
log(`PR #${pr.number} commit "${commit.messageHeadline}" (${commit.committedDate}) - in range: ${isInRange}`);
return isInRange;
});
log(`PR #${pr.number} filteredCommits:`, filteredCommits);
commitMap[pr.number] = filteredCommits;
} else {
log(`No commits found for PR #${pr.number}`);
}
});
return commitMap;
}
async function fetchReposIfNeeded() {
if (!useRepoFilter) {
log('Repo fiter disabled, skipping fetch');
return [];
}
const repoCacheKey = `repos-${platformUsernameLocal}-${orgName}-${startDateForCache}-${endDateForCache}`;
const now = Date.now();
const isRepoCacheFresh = now - githubCache.repoTimeStamp < githubCache.ttl;
const isRepoCacheKeyMatch = githubCache.repoCacheKey === repoCacheKey;
if (githubCache.repoData && isRepoCacheFresh && isRepoCacheKeyMatch) {
log('Using cached repo data');
return githubCache.repoData;
}
if (githubCache.repoFetching) {
log('Repo fetch is in progress, queuing request');
return new Promise((resolve, reject) => {
githubCache.repoQueue.push({ resolve, reject });
});
}
githubCache.repoFetching = true;
githubCache.repoCacheKey = repoCacheKey;
try {
log('Fetching repos automatically');
const repos = await fetchUserRepositories(platformUsernameLocal, githubToken, orgName);
githubCache.repoData = repos;
githubCache.repoTimeStamp = now;
chrome.storage.local.set({
repoCache: {
data: repos,
cacheKey: repoCacheKey,
timestamp: now,
},
});
githubCache.repoQueue.forEach(({ resolve }) => {
resolve(repos);
});
githubCache.repoQueue = [];
log(`Successfuly cached ${repos.length} repositories`);
return repos;
} catch (err) {
logError('Failed to fetch reppos:', err);
githubCache.repoQueue.forEach(({ reject }) => {
reject(err);
});
githubCache.repoQueue = [];
throw err;
} finally {
githubCache.repoFetching = false;
}
}
async function verifyCacheStatus() {
log('Cache Status: ', {
hasCachedData: !!githubCache.data,
cacheAge: githubCache.timestamp
? `${((Date.now() - githubCache.timestamp) / 1000 / 60).toFixed(1)} minutes`
: `no cache`,
cacheKey: githubCache.cacheKey,
isFetching: githubCache.fetching,
queueLength: githubCache.queue.length,
});
const storageData = await new Promise((resolve) => {
chrome.storage.local.get('githubCache', resolve);
});
log('Storage Status:', {
hasStoredData: !!storageData.githubCache,
storedCacheKey: storageData.githubCache?.cacheKey,
storageAge: storageData.githubCache?.timestamp
? `${((Date.now() - storageData.githubCache.timestamp) / 1000 / 60).toFixed(1)} minutes`
: 'no data',
});
}
verifyCacheStatus();
function showInvalidTokenMessage() {
if (outputTarget === 'popup') {
const reportDiv = document.getElementById('scrumReport');
if (reportDiv) {
reportDiv.innerHTML =
'<div class="error-message" style="color: #dc2626; font-weight: bold; padding: 10px;">Invalid or expired GitHub token. Please check your token in the settings and try again.</div>';
const generateBtn = document.getElementById('generateReport');
if (generateBtn) {
generateBtn.innerHTML = '<i class="fa fa-refresh"></i> Generate Report';
generateBtn.disabled = false;
}
} else {
alert('Invalid or expired GitHub token. Please check your token in the extension popup and try again.');
}
}
}
async function processGithubData(data) {
log('Processing Github data');
let filteredData = data;
// Always apply repo filter if it's enabled and repos are selected.
if (useRepoFilter && selectedRepos && selectedRepos.length > 0) {
log('[SCRUM-HELPER]: Filtering data by selected repos:', selectedRepos);
filteredData = filterDataByRepos(data, selectedRepos);
}
githubIssuesData = filteredData.githubIssuesData;
githubPrsReviewData = filteredData.githubPrsReviewData;
githubUserData = filteredData.githubUserData;
log('GitHub data set:', {
issues: githubIssuesData?.items?.length || 0,
prs: githubPrsReviewData?.items?.length || 0,
user: githubUserData?.login,
filtered: useRepoFilter,
});
lastWeekArray = [];
nextWeekArray = [];
reviewedPrsArray = [];
githubPrsReviewDataProcessed = {};
issuesDataProcessed = false;
prsReviewDataProcessed = false;
if (!githubCache.subject && scrumSubject) {
scrumSubjectLoaded();
}
log('[SCRUM-DEBUG] Processing issues for main activity:', githubIssuesData?.items);
if (platform === 'github') {
await writeGithubIssuesPrs(githubIssuesData?.items || []);
} else if (platform === 'gitlab') {
await writeGithubIssuesPrs(githubIssuesData?.items || []);
await writeGithubIssuesPrs(githubPrsReviewData?.items || []);
}
await writeGithubPrsReviews();
log('[DEBUG] Both data processing functions completed, generating scrum body');