-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjira_insights_tab.py
1609 lines (1376 loc) · 68.7 KB
/
jira_insights_tab.py
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
import sys
import os
import json
import requests
import markdown
from datetime import datetime
from cryptography.fernet import Fernet
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QProgressBar
from PyQt5.QtGui import QPainter, QColor
from requests.auth import HTTPBasicAuth
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QLabel,
QTableWidget, QTableWidgetItem, QTabWidget, QTextEdit,
QDialog, QFormLayout, QLineEdit, QDialogButtonBox, QMessageBox,
QSplitter, QFileDialog, QHeaderView, QTextBrowser)
from PyQt5.QtCore import Qt, QThreadPool, QRunnable, pyqtSlot, QObject, pyqtSignal
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QLabel, QScrollArea, QVBoxLayout, QHBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PyQt5.QtCore import QUrl, pyqtSignal
from PyQt5.QtWebEngineCore import QWebEngineCookieStore
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QPushButton, QLabel, QFrame
from PyQt5.QtGui import QPixmap, QImage, QTextCursor
from PyQt5.QtCore import Qt
from io import BytesIO
from jira import JIRA
from PyQt5.QtWidgets import QTextEdit, QCompleter
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtCore import QStringListModel
from PyQt5.QtWidgets import QTextEdit, QCompleter
from PyQt5.QtCore import Qt, QTimer
from helper_jira_insights_tab.rich_text_editor import RichTextEditor, AutocompleteComboBox
import logging
# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
JIRA_BASE_URL = "https://jira-pro.it.hpe.com:8443"
CREDS_FILE = os.path.expanduser("~/.jira_creds.enc")
KEY_FILE = os.path.expanduser("~/.jira_key")
PROJECTS_FILE = os.path.expanduser("~/.jira_selected_projects.json")
class CommentWidget(QWidget):
def __init__(self, comment, parent=None):
super().__init__(parent)
self.comment = comment
self.parent = parent
self.init_ui()
def init_ui(self):
layout = QVBoxLayout(self)
# Header
header_layout = QHBoxLayout()
author_label = QLabel(f"<b>{self.comment['author']['displayName']}</b>")
time_label = QLabel(self.parent.get_relative_time(self.comment['created']))
header_layout.addWidget(author_label)
header_layout.addWidget(time_label)
header_layout.addStretch()
layout.addLayout(header_layout)
# Comment body
body_label = QTextBrowser()
body_label.setHtml(self.parent.markdown_to_html(self.comment['body']))
body_label.setOpenExternalLinks(True)
layout.addWidget(body_label)
class MentionTextEdit(QTextEdit):
def __init__(self, fetch_users_callback, parent=None):
super().__init__(parent)
self.fetch_users_callback = fetch_users_callback
self.completer = QCompleter(self)
self.completer.setWidget(self)
self.completer.setCompletionMode(QCompleter.PopupCompletion)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.activated.connect(self.insert_completion)
self.mention_pos = 0
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.update_completions)
def keyPressEvent(self, event):
if self.completer.popup().isVisible():
if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab):
event.ignore()
return
super().keyPressEvent(event)
if event.key() == Qt.Key_At:
self.mention_pos = self.textCursor().position()
elif self.mention_pos:
cursor = self.textCursor()
if cursor.position() - self.mention_pos > 1:
self.timer.start(200) # Delay to avoid too frequent API calls
def update_completions(self):
cursor = self.textCursor()
current_pos = cursor.position()
if current_pos > self.mention_pos:
text = self.toPlainText()[self.mention_pos:current_pos]
users = self.fetch_users_callback(text)
self.completer.setModel(QStringListModel([user['displayName'] for user in users]))
self.completer.setCompletionPrefix(text)
popup = self.completer.popup()
popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
cursor.setPosition(self.mention_pos)
rect = self.cursorRect(cursor)
rect.setWidth(self.completer.popup().sizeHintForColumn(0) +
self.completer.popup().verticalScrollBar().sizeHint().width())
self.completer.complete(rect)
else:
self.mention_pos = 0
def insert_completion(self, completion):
cursor = self.textCursor()
cursor.setPosition(self.mention_pos - 1, QTextCursor.MoveAnchor)
cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)
cursor.insertText(f"@{completion} ")
self.setTextCursor(cursor)
self.mention_pos = 0
class WorkerSignals(QObject):
finished = pyqtSignal()
error = pyqtSignal(str)
result = pyqtSignal(object)
class Worker(QRunnable):
def __init__(self, fn, *args, **kwargs):
super().__init__()
self.fn = fn
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
@pyqtSlot()
def run(self):
try:
result = self.fn(*self.args, **self.kwargs)
self.signals.result.emit(result)
except Exception as e:
self.signals.error.emit(str(e))
finally:
self.signals.finished.emit()
class LoadingOverlay(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WA_TranslucentBackground)
layout = QVBoxLayout(self)
layout.setAlignment(Qt.AlignCenter)
self.loading_label = QLabel("Loading...", self)
self.loading_label.setStyleSheet("""
background-color: #2a2a2a;
color: white;
border: 2px solid #3a3a3a;
border-radius: 5px;
padding: 10px;
font-size: 16px;
""")
layout.addWidget(self.loading_label)
self.progress = QProgressBar()
self.progress.setRange(0, 0) # Indeterminate progress
self.progress.setTextVisible(False)
self.progress.setFixedSize(200, 20)
layout.addWidget(self.progress)
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(0, 0, 0, 128)) # # Semi-transparent black
def showEvent(self, event):
self.setGeometry(self.parent().rect())
class JiraAuthDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("JIRA Authentication")
layout = QVBoxLayout(self)
message = QLabel("Please enter your JIRA bearer token.")
layout.addWidget(message)
form_layout = QFormLayout()
self.token_input = QLineEdit(self)
self.token_input.setEchoMode(QLineEdit.Password)
form_layout.addRow("JIRA Bearer Token:", self.token_input)
layout.addLayout(form_layout)
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def get_credentials(self):
return self.token_input.text()
class JiraInsightsTab(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.session = requests.Session()
self.jira_token = self.get_jira_credentials()
self.session.headers.update({"Authorization": f"Bearer {self.jira_token}"})
self.current_start = 0
self.issues_per_load = 10
self.total_issues = 0
self.threadpool = QThreadPool()
self.is_loading = False
self.current_tab = "personal"
self.loading_overlay = LoadingOverlay(self)
self.loading_overlay.hide()
self.searched_issues = []
if self.jira_token:
self.selected_projects = self.load_selected_projects()
self.init_ui()
QTimer.singleShot(0, self.initialize_data)
else:
self.show_auth_failed_message()
def initialize_data(self):
self.show_loading_overlay()
self.load_data_async("personal")
def show_loading_overlay(self):
self.loading_overlay.show()
self.loading_overlay.raise_()
QApplication.processEvents()
def hide_loading_overlay(self):
self.loading_overlay.hide()
QApplication.processEvents()
def resizeEvent(self, event):
super().resizeEvent(event)
if self.loading_overlay:
self.loading_overlay.setGeometry(self.rect())
def get_jira_credentials(self):
if os.path.exists(CREDS_FILE) and os.path.exists(KEY_FILE):
with open(KEY_FILE, 'rb') as key_file:
key = key_file.read()
fernet = Fernet(key)
with open(CREDS_FILE, 'rb') as cred_file:
encrypted_creds = cred_file.read()
token = fernet.decrypt(encrypted_creds).decode()
return token
else:
return self.prompt_for_credentials()
def prompt_for_credentials(self):
dialog = JiraAuthDialog(self)
if dialog.exec_() == QDialog.Accepted:
token = dialog.get_credentials()
if self.verify_credentials(token):
self.save_credentials(token)
return token
else:
QMessageBox.critical(self, "Authentication Failed", "Invalid token. Please try again.")
return None
def verify_credentials(self, token):
try:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
response = requests.get(
f"{JIRA_BASE_URL}/rest/api/2/myself",
headers=headers
)
response.raise_for_status()
return True
except requests.RequestException:
return False
def save_credentials(self, token):
key = Fernet.generate_key()
fernet = Fernet(key)
encrypted_token = fernet.encrypt(token.encode())
with open(KEY_FILE, 'wb') as key_file:
key_file.write(key)
with open(CREDS_FILE, 'wb') as cred_file:
cred_file.write(encrypted_token)
def show_auth_failed_message(self):
QMessageBox.critical(self, "Authentication Required", "JIRA credentials are required to use this feature.")
def init_ui(self):
layout = QVBoxLayout(self)
self.tab_widget = QTabWidget(self)
layout.addWidget(self.tab_widget)
personal_tab = QWidget()
personal_layout = QVBoxLayout(personal_tab)
self.setup_common_tab(personal_layout, "personal")
self.tab_widget.addTab(personal_tab, "Personal Issues")
reported_tab = QWidget()
reported_layout = QVBoxLayout(reported_tab)
self.setup_common_tab(reported_layout, "reported")
self.tab_widget.addTab(reported_tab, "Reported by Me")
project_tab = QWidget()
project_layout = QVBoxLayout(project_tab)
self.setup_common_tab(project_layout, "project")
self.tab_widget.addTab(project_tab, "Project Issues")
search_tab = QWidget()
search_layout = QVBoxLayout(search_tab)
self.setup_search_tab(search_layout)
self.tab_widget.addTab(search_tab, "Search Issues")
self.tab_widget.currentChanged.connect(self.on_tab_change)
self.setLayout(layout)
def setup_common_tab(self, layout, tab_type):
splitter = QSplitter(Qt.Horizontal)
layout.addWidget(splitter)
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
filter_layout = QHBoxLayout()
severity_filter = QComboBox()
severity_filter.addItem("All Severities")
severity_filter.currentIndexChanged.connect(self.filter_issues)
status_filter = QComboBox()
status_filter.addItem("All Statuses")
status_filter.currentIndexChanged.connect(self.filter_issues)
release_filter = QComboBox()
release_filter.addItem("All Releases")
release_filter.currentIndexChanged.connect(self.filter_issues)
if tab_type == "project" or tab_type == "search":
project_filter = QComboBox()
self.selected_projects = self.load_selected_projects()
project_filter.addItems(self.selected_projects)
if tab_type == "project":
project_filter.currentIndexChanged.connect(self.load_project_issues)
filter_layout.addWidget(QLabel("Project:"))
filter_layout.addWidget(project_filter)
self.project_filter = project_filter
filter_layout.addWidget(QLabel("Severity:"))
filter_layout.addWidget(severity_filter)
filter_layout.addWidget(QLabel("Status:"))
filter_layout.addWidget(status_filter)
filter_layout.addWidget(QLabel("Release:"))
filter_layout.addWidget(release_filter)
left_layout.addLayout(filter_layout)
search_filter = QLineEdit()
search_filter.setPlaceholderText("Search issues...")
search_filter.textChanged.connect(self.filter_issues)
left_layout.addWidget(search_filter)
issues_table = QTableWidget()
self.setup_issues_table(issues_table, include_assignee=(tab_type != "personal"))
left_layout.addWidget(issues_table)
fetch_more_button = QPushButton("Fetch 10 more issues")
fetch_more_button.clicked.connect(self.load_more_data)
left_layout.addWidget(fetch_more_button)
splitter.addWidget(left_widget)
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
button_layout = QHBoxLayout()
download_btn = QPushButton("Download")
refresh_btn = QPushButton("Refresh")
edit_btn = QPushButton("Edit")
add_comment_btn = QPushButton("Add Comment")
for btn in [download_btn, refresh_btn, edit_btn, add_comment_btn]:
button_layout.addWidget(btn)
btn.setVisible(False)
right_layout.addLayout(button_layout)
details_tab_widget = QTabWidget()
description_tab = QTextBrowser()
description_tab.setStyleSheet("QTextBrowser { margin: 10px; }")
comments_tab = QWidget()
comments_tab_layout = QVBoxLayout(comments_tab)
comments_scroll_area = QScrollArea()
comments_scroll_area.setWidgetResizable(True)
comments_content = QWidget()
comments_content.setLayout(QVBoxLayout()) # Initialize the layout here
comments_scroll_area.setWidget(comments_content)
comments_tab_layout.addWidget(comments_scroll_area)
attachments_tab = QWidget()
activity_tab = QTextBrowser()
activity_tab.setStyleSheet("QTextBrowser { margin: 10px; }")
details_tab_widget.addTab(description_tab, "Description")
details_tab_widget.addTab(comments_tab, "Comments")
details_tab_widget.addTab(attachments_tab, "Attachments")
details_tab_widget.addTab(activity_tab, "Activity")
right_layout.addWidget(details_tab_widget)
splitter.addWidget(right_widget)
# Ensure the splitter is set to 50-50
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 1)
download_btn.clicked.connect(self.download_description)
refresh_btn.clicked.connect(self.refresh_issue)
edit_btn.clicked.connect(self.edit_issue)
add_comment_btn.clicked.connect(self.add_comment)
if tab_type == "personal":
self.personal_severity_filter = severity_filter
self.personal_status_filter = status_filter
self.personal_release_filter = release_filter
self.personal_search_filter = search_filter
self.personal_issues_table = issues_table
self.personal_fetch_more_button = fetch_more_button
self.personal_description_tab = description_tab
self.personal_comments_content = comments_content
self.personal_attachments_tab = attachments_tab
self.personal_activity_tab = activity_tab
self.personal_details_tab_widget = details_tab_widget
self.personal_download_btn = download_btn
self.personal_refresh_btn = refresh_btn
self.personal_edit_btn = edit_btn
self.personal_add_comment_btn = add_comment_btn
elif tab_type == "reported":
self.reported_severity_filter = severity_filter
self.reported_status_filter = status_filter
self.reported_release_filter = release_filter
self.reported_search_filter = search_filter
self.reported_issues_table = issues_table
self.reported_fetch_more_button = fetch_more_button
self.reported_description_tab = description_tab
self.reported_comments_content = comments_content
self.reported_attachments_tab = attachments_tab
self.reported_activity_tab = activity_tab
self.reported_details_tab_widget = details_tab_widget
self.reported_download_btn = download_btn
self.reported_refresh_btn = refresh_btn
self.reported_edit_btn = edit_btn
self.reported_add_comment_btn = add_comment_btn
if tab_type == "project":
self.project_severity_filter = severity_filter
self.project_status_filter = status_filter
self.project_release_filter = release_filter
self.project_search_filter = search_filter
self.project_issues_table = issues_table
self.project_fetch_more_button = fetch_more_button
self.project_description_tab = description_tab
self.project_comments_content = comments_content
self.project_attachments_tab = attachments_tab
self.project_activity_tab = activity_tab
self.project_details_tab_widget = details_tab_widget
self.project_download_btn = download_btn
self.project_refresh_btn = refresh_btn
self.project_edit_btn = edit_btn
self.project_add_comment_btn = add_comment_btn
# Load issues for the first project
if self.selected_projects:
self.load_project_issues()
elif tab_type == "search":
self.search_severity_filter = severity_filter
self.search_status_filter = status_filter
self.search_release_filter = release_filter
self.search_search_filter = search_filter
self.search_issues_table = issues_table
self.search_fetch_more_button = fetch_more_button
self.search_description_tab = description_tab
self.search_comments_content = comments_content
self.search_attachments_tab = attachments_tab
self.search_activity_tab = activity_tab
self.search_details_tab_widget = details_tab_widget
self.search_download_btn = download_btn
self.search_refresh_btn = refresh_btn
self.search_edit_btn = edit_btn
self.search_add_comment_btn = add_comment_btn
self.load_data_async(tab_type)
def setup_search_tab(self, layout):
splitter = QSplitter(Qt.Horizontal)
layout.addWidget(splitter)
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
# Search row: Project dropdown, Issue number input, and Apply button
search_row_layout = QHBoxLayout()
self.search_project_filter = QComboBox()
self.search_project_filter.addItems(self.selected_projects)
self.search_project_filter.setFixedWidth(100) # Set fixed width to 100px
search_row_layout.addWidget(QLabel("Project:"))
search_row_layout.addWidget(self.search_project_filter)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Enter JIRA issue number...")
search_row_layout.addWidget(self.search_input)
search_apply_btn = QPushButton("Apply")
search_apply_btn.clicked.connect(self.apply_search)
search_row_layout.addWidget(search_apply_btn)
left_layout.addLayout(search_row_layout)
# Issues table
self.search_issues_table = QTableWidget()
self.setup_issues_table(self.search_issues_table)
left_layout.addWidget(self.search_issues_table)
splitter.addWidget(left_widget)
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
button_layout = QHBoxLayout()
self.search_download_btn = QPushButton("Download")
self.search_refresh_btn = QPushButton("Refresh")
self.search_edit_btn = QPushButton("Edit")
self.search_add_comment_btn = QPushButton("Add Comment")
for btn in [self.search_download_btn, self.search_refresh_btn, self.search_edit_btn, self.search_add_comment_btn]:
button_layout.addWidget(btn)
btn.setVisible(False)
right_layout.addLayout(button_layout)
details_tab_widget = QTabWidget()
self.search_description_tab = QTextBrowser()
self.search_description_tab.setStyleSheet("QTextBrowser { margin: 10px; }")
self.search_comments_tab = QTextBrowser()
self.search_comments_tab.setStyleSheet("QTextBrowser { margin: 10px; }")
self.search_attachments_tab = QWidget()
details_tab_widget.addTab(self.search_description_tab, "Description")
details_tab_widget.addTab(self.search_comments_tab, "Comments")
details_tab_widget.addTab(self.search_attachments_tab, "Attachments")
right_layout.addWidget(details_tab_widget)
splitter.addWidget(right_widget)
# Set the splitter to 50-50
splitter.setSizes([int(self.width() * 0.5), int(self.width() * 0.5)])
self.search_download_btn.clicked.connect(self.download_description)
self.search_refresh_btn.clicked.connect(self.refresh_issue)
self.search_edit_btn.clicked.connect(self.edit_issue)
self.search_add_comment_btn.clicked.connect(self.add_comment)
layout.addWidget(splitter)
def apply_search(self):
project = self.search_project_filter.currentText()
issue_number = self.search_input.text().strip()
if project and issue_number:
query = f"{project}-{issue_number}"
self.search_issues_table.setRowCount(0) # Clear the table
self.load_single_issue(query)
else:
QMessageBox.warning(self, "Warning", "Please select a project and enter an issue number.")
def load_issue_and_add_to_table(self, issue_key):
try:
issue = self.fetch_issue_details(issue_key)
self.add_issue_to_table(self.search_issues_table, issue)
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to load issue: {str(e)}")
def load_data_async(self, tab_type, query=None):
if self.is_loading:
return
self.is_loading = True
self.show_loading_overlay()
worker = Worker(self.fetch_issues, tab_type, query)
worker.signals.result.connect(lambda issues: self.update_issues_table(tab_type, issues))
worker.signals.finished.connect(self.finish_loading)
worker.signals.error.connect(self.handle_error)
self.threadpool.start(worker)
def update_issues_table(self, tab_type, issues):
if tab_type == "personal":
self.update_personal_issues_table(issues)
elif tab_type == "reported":
self.update_reported_issues_table(issues)
elif tab_type == "project":
self.update_project_issues_table(issues)
elif tab_type == "search":
self.update_search_issues_table(issues)
def load_single_issue(self, issue_key):
print(f"Searching for issue: {issue_key}") # Debug print
headers = {
"Authorization": f"Bearer {self.jira_token}",
"Content-Type": "application/json"
}
try:
response = requests.get(
f"{JIRA_BASE_URL}/rest/api/2/issue/{issue_key}",
headers=headers
)
response.raise_for_status()
issue_data = response.json()
print(f"Issue data received: {issue_data}") # Debug print
# Check if the issue is already in the list
if not any(issue['key'] == issue_data['key'] for issue in self.searched_issues):
self.searched_issues.append(issue_data)
self.update_search_table(issue_data)
self.show_issue_details_async(issue_key)
except requests.RequestException as e:
print(f"Error fetching issue: {str(e)}") # Debug print
QMessageBox.warning(self, "Error", f"Failed to fetch issue: {str(e)}")
def update_search_table(self, issue_data):
self.search_issues_table.setRowCount(0)
for issue in self.searched_issues:
self.add_issue_to_table(self.search_issues_table, issue_data, include_assignee=True)
def load_project_issues(self):
try:
self.current_start = 0
self.project_issues_table.setRowCount(0)
selected_project = self.project_filter.currentText()
if not selected_project:
raise ValueError("No project selected")
self.load_data_async("project")
except ValueError as e:
QMessageBox.warning(self, "Warning", str(e))
def add_issue_to_table(self, table, issue, include_assignee=True):
row_position = table.rowCount()
table.insertRow(row_position)
table.setItem(row_position, 0, QTableWidgetItem(issue['key']))
table.setItem(row_position, 1, QTableWidgetItem(issue['fields']['summary']))
col = 2
if include_assignee:
assignee = issue['fields'].get('assignee', {})
assignee_name = assignee.get('displayName', 'Unassigned') if assignee else 'Unassigned'
table.setItem(row_position, col, QTableWidgetItem(assignee_name))
col += 1
table.setItem(row_position, col, QTableWidgetItem(issue['fields']['status']['name']))
col += 1
table.setItem(row_position, col, QTableWidgetItem(issue['fields'].get('priority', {}).get('name', 'N/A')))
col += 1
fix_versions = issue['fields'].get('fixVersions', [])
fix_version = fix_versions[0]['name'] if fix_versions else 'N/A'
table.setItem(row_position, col, QTableWidgetItem(fix_version))
col += 1
updated = self.get_relative_time(issue['fields']['updated'])
table.setItem(row_position, col, QTableWidgetItem(updated))
def finish_loading(self):
self.is_loading = False
self.hide_loading_overlay()
self.current_start += self.issues_per_load
def update_personal_issues_table(self, issues):
for issue in issues:
self.add_issue_to_table(self.personal_issues_table, issue, include_assignee=False)
self.update_filter_options(issues)
def update_reported_issues_table(self, issues):
for issue in issues:
self.add_issue_to_table(self.reported_issues_table, issue, include_assignee=True)
self.update_filter_options(issues)
def update_project_issues_table(self, issues):
for issue in issues:
self.add_issue_to_table(self.project_issues_table, issue, include_assignee=True)
self.update_filter_options(issues)
def update_search_issues_table(self, issues):
for issue in issues:
self.add_issue_to_table(self.search_issues_table, issue, include_assignee=True)
self.update_filter_options(issues)
def fetch_issues(self, tab_type, query=None):
jql = ""
if tab_type == "personal":
jql = "assignee=currentUser() ORDER BY updated DESC"
elif tab_type == "reported":
jql = "reporter=currentUser() ORDER BY updated DESC"
elif tab_type == "project":
project = self.project_filter.currentText()
if not project:
raise ValueError("No project selected")
jql = f'project="{project}" ORDER BY updated DESC'
elif tab_type == "search" and query:
jql = f"key={query}"
if not jql:
raise ValueError("Invalid tab type or missing query")
response = requests.get(
f"{JIRA_BASE_URL}/rest/api/2/search",
params={
"jql": jql,
"startAt": self.current_start,
"maxResults": self.issues_per_load
},
headers={"Authorization": f"Bearer {self.jira_token}"}
)
response.raise_for_status()
data = response.json()
self.total_issues = data.get('total', 0)
issues = data.get('issues', [])
return issues
def filter_issues(self):
if self.current_tab == "personal":
table = self.personal_issues_table
filter_text = self.personal_search_filter.text().lower()
selected_severity = self.personal_severity_filter.currentText()
selected_status = self.personal_status_filter.currentText()
selected_release = self.personal_release_filter.currentText()
elif self.current_tab == "reported":
table = self.reported_issues_table
filter_text = self.reported_search_filter.text().lower()
selected_severity = self.reported_severity_filter.currentText()
selected_status = self.reported_status_filter.currentText()
selected_release = self.reported_release_filter.currentText()
elif self.current_tab == "project":
table = self.project_issues_table
filter_text = self.project_search_filter.text().lower()
selected_severity = self.project_severity_filter.currentText()
selected_status = self.project_status_filter.currentText()
selected_release = self.project_release_filter.currentText()
elif self.current_tab == "search":
table = self.search_issues_table
filter_text = self.search_search_filter.text().lower()
selected_severity = self.search_severity_filter.currentText()
selected_status = self.search_status_filter.currentText()
selected_release = self.search_release_filter.currentText()
for row in range(table.rowCount()):
match = True
if filter_text:
match = any(
filter_text in table.item(row, col).text().lower()
for col in range(table.columnCount())
)
if selected_severity != "All Severities":
match &= (selected_severity == table.item(row, 3).text())
if selected_status != "All Statuses":
match &= (selected_status == table.item(row, 2).text())
if selected_release != "All Releases":
match &= (selected_release == table.item(row, 4).text())
table.setRowHidden(row, not match)
def setup_issues_table(self, table, include_assignee=True):
columns = ["Key", "Title", "Status", "Severity", "Release", "Updated"]
if include_assignee:
columns.insert(2, "Assignee") # Insert Assignee after Title
table.setColumnCount(len(columns))
table.setHorizontalHeaderLabels(columns)
table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) # Title column
for i in range(len(columns)):
if i != 1: # Skip Title column
table.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)
table.setSelectionBehavior(QTableWidget.SelectRows)
table.setSelectionMode(QTableWidget.SingleSelection)
table.itemSelectionChanged.connect(self.on_issue_selected)
table.setSortingEnabled(True)
def update_filter_options(self, issues):
severities = set()
statuses = set()
releases = set()
for issue in issues:
severities.add(issue['fields'].get('priority', {}).get('name', 'N/A'))
statuses.add(issue['fields']['status']['name'])
fix_versions = issue['fields'].get('fixVersions', [])
for version in fix_versions:
releases.add(version['name'])
if self.current_tab == "personal":
self.update_combobox(self.personal_severity_filter, severities, "All Severities")
self.update_combobox(self.personal_status_filter, statuses, "All Statuses")
self.update_combobox(self.personal_release_filter, releases, "All Releases")
elif self.current_tab == "reported":
self.update_combobox(self.reported_severity_filter, severities, "All Severities")
self.update_combobox(self.reported_status_filter, statuses, "All Statuses")
self.update_combobox(self.reported_release_filter, releases, "All Releases")
elif self.current_tab == "project":
self.update_combobox(self.project_severity_filter, severities, "All Severities")
self.update_combobox(self.project_status_filter, statuses, "All Statuses")
self.update_combobox(self.project_release_filter, releases, "All Releases")
elif self.current_tab == "search":
self.update_combobox(self.search_severity_filter, severities, "All Severities")
self.update_combobox(self.search_status_filter, statuses, "All Statuses")
self.update_combobox(self.search_release_filter, releases, "All Releases")
def update_combobox(self, combobox, items, default_item):
current_item = combobox.currentText()
combobox.blockSignals(True)
combobox.clear()
combobox.addItem(default_item)
combobox.addItems(sorted(items))
combobox.setCurrentText(current_item)
combobox.blockSignals(False)
def get_relative_time(self, timestamp):
then = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
now = datetime.now(then.tzinfo)
delta = now - then
if delta.days > 365:
return f"{delta.days // 365} years ago"
elif delta.days > 30:
return f"{delta.days // 30} months ago"
elif delta.days > 0:
return f"{delta.days} days ago"
elif delta.seconds > 3600:
return f"{delta.seconds // 3600} hours ago"
elif delta.seconds > 60:
return f"{delta.seconds // 60} minutes ago"
else:
return "Just now"
def load_more_data(self):
if not self.is_loading and self.current_start < self.total_issues:
self.load_data_async(self.current_tab)
def on_issue_selected(self):
selected_items = self.sender().selectedItems()
if selected_items:
issue_key = selected_items[0].text()
self.show_issue_details_async(issue_key)
if self.current_tab == "personal":
for btn in [self.personal_download_btn, self.personal_refresh_btn, self.personal_edit_btn, self.personal_add_comment_btn]:
btn.setVisible(True)
elif self.current_tab == "reported":
for btn in [self.reported_download_btn, self.reported_refresh_btn, self.reported_edit_btn, self.reported_add_comment_btn]:
btn.setVisible(True)
elif self.current_tab == "project":
for btn in [self.project_download_btn, self.project_refresh_btn, self.project_edit_btn, self.project_add_comment_btn]:
btn.setVisible(True)
elif self.current_tab == "search":
for btn in [self.search_download_btn, self.search_refresh_btn, self.search_edit_btn, self.search_add_comment_btn]:
btn.setVisible(True)
else:
if self.current_tab == "personal":
for btn in [self.personal_download_btn, self.personal_refresh_btn, self.personal_edit_btn, self.personal_add_comment_btn]:
btn.setVisible(False)
elif self.current_tab == "reported":
for btn in [self.reported_download_btn, self.reported_refresh_btn, self.reported_edit_btn, self.reported_add_comment_btn]:
btn.setVisible(False)
elif self.current_tab == "project":
for btn in [self.project_download_btn, self.project_refresh_btn, self.project_edit_btn, self.project_add_comment_btn]:
btn.setVisible(False)
elif self.current_tab == "search":
for btn in [self.search_download_btn, self.search_refresh_btn, self.search_edit_btn, self.search_add_comment_btn]:
btn.setVisible(False)
def show_issue_details_async(self, issue_key):
self.show_loading_overlay()
worker = Worker(self.fetch_issue_details, issue_key)
if self.current_tab == "personal":
worker.signals.result.connect(lambda data: self.display_issue_details(data, "personal"))
elif self.current_tab == "reported":
worker.signals.result.connect(lambda data: self.display_issue_details(data, "reported"))
elif self.current_tab == "project":
worker.signals.result.connect(lambda data: self.display_issue_details(data, "project"))
elif self.current_tab == "search":
worker.signals.result.connect(lambda data: self.display_issue_details(data, "search"))
worker.signals.finished.connect(self.hide_loading_overlay)
worker.signals.error.connect(lambda e: self.handle_error(e))
self.threadpool.start(worker)
def fetch_issue_details(self, issue_key):
response = requests.get(
f"{JIRA_BASE_URL}/rest/api/2/issue/{issue_key}",
headers={"Authorization": f"Bearer {self.jira_token}"}
)
response.raise_for_status()
return response.json()
def update_comments_tab(self, comments, tab_type):
if tab_type == "personal":
comments_content = self.personal_comments_content
elif tab_type == "reported":
comments_content = self.reported_comments_content
elif tab_type == "project":
comments_content = self.project_comments_content
elif tab_type == "search":
comments_content = self.search_comments_content
else:
return
# Initialize layout if it doesn't exist
if comments_content.layout() is None:
comments_content.setLayout(QVBoxLayout())
comments_layout = comments_content.layout()
# Clear existing comments
while comments_layout.count():
item = comments_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
for comment in comments:
comment_widget = CommentWidget(comment, self)
comments_layout.addWidget(comment_widget)
separator = QFrame()
separator.setFrameShape(QFrame.HLine)
separator.setFrameShadow(QFrame.Sunken)
comments_layout.addWidget(separator)
comments_layout.addStretch()
def display_issue_details(self, issue_data, tab_type):
description_markdown = issue_data['fields']['description'] or "No description available."
description_html = self.markdown_to_html(description_markdown)
comments = issue_data['fields']['comment']['comments']
attachments = issue_data['fields']['attachment']
activities = self.fetch_issue_activity(issue_data['key'])
activity_html = self.format_activity_log(activities)
if tab_type == "personal":
self.personal_description_tab.setHtml(description_html)
self.update_comments_tab(comments, "personal")
self.update_attachments_tab(self.personal_attachments_tab, attachments)
self.personal_activity_tab.setHtml(activity_html)
self.personal_details_tab_widget.setCurrentIndex(0) # Set to Description tab
elif tab_type == "reported":
self.reported_description_tab.setHtml(description_html)
self.update_comments_tab(comments, "reported")
self.update_attachments_tab(self.reported_attachments_tab, attachments)
self.reported_activity_tab.setHtml(activity_html)
self.reported_details_tab_widget.setCurrentIndex(0) # Set to Description tab
elif tab_type == "project":
self.project_description_tab.setHtml(description_html)
self.update_comments_tab(comments, "project")
self.update_attachments_tab(self.project_attachments_tab, attachments)
self.project_activity_tab.setHtml(activity_html)
self.project_details_tab_widget.setCurrentIndex(0) # Set to Description tab
elif tab_type == "search":
self.search_description_tab.setHtml(description_html)
self.update_comments_tab(comments, "search")
self.update_attachments_tab(self.search_attachments_tab, attachments)
self.search_activity_tab.setHtml(activity_html)
self.search_details_tab_widget.setCurrentIndex(0) # Set to Description tab
# Update issue details (you might want to add this information to a header or separate widget)
issue_key = issue_data['key']
summary = issue_data['fields']['summary']
status = issue_data['fields']['status']['name']
issue_type = issue_data['fields']['issuetype']['name']
priority = issue_data['fields']['priority']['name']
assignee = issue_data['fields']['assignee']['displayName'] if issue_data['fields']['assignee'] else "Unassigned"
reporter = issue_data['fields']['reporter']['displayName']
created_date = self.get_relative_time(issue_data['fields']['created'])
updated_date = self.get_relative_time(issue_data['fields']['updated'])
issue_details_html = f"""
<h2>{issue_key}: {summary}</h2>
<p><strong>Status:</strong> {status}</p>
<p><strong>Type:</strong> {issue_type}</p>
<p><strong>Priority:</strong> {priority}</p>
<p><strong>Assignee:</strong> {assignee}</p>
<p><strong>Reporter:</strong> {reporter}</p>
<p><strong>Created:</strong> {created_date}</p>
<p><strong>Updated:</strong> {updated_date}</p>
"""