-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.py
More file actions
523 lines (460 loc) · 17.5 KB
/
ui.py
File metadata and controls
523 lines (460 loc) · 17.5 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
import customtkinter
import requests
from CTkMessagebox import CTkMessagebox
from fresh import FreshServiceAPI
from dotenv import load_dotenv
import json
import os
customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("dark-blue")
# Load environment variables
load_dotenv()
API_KEY = os.getenv("API_KEY")
TICKET_API_URL = os.getenv("API_URL")
REQUESTERS_API_URL = os.getenv("REQUESTER_URL")
# Ensure API_KEY and URLs are set
if not API_KEY or not TICKET_API_URL or not REQUESTERS_API_URL:
raise ValueError(
"API_KEY, TICKET_API_URL, and REQUESTERS_API_URL must be set in the environment variables."
)
# Init API class
api = FreshServiceAPI(TICKET_API_URL, REQUESTERS_API_URL, API_KEY)
# Verify that the requesters.json file exists
if not os.path.exists("requesters.json"):
api.get_requesters()
print(
"Requesters file not found. Fetching requesters from API and creating requesters.json."
)
else:
print("Requesters file found. Using existing data.")
request_type_values = [
"",
"Incident",
"Service Request",
]
# Map display names to Freshservice API values
service_field_map = {
"Password Reset": "Active Directory",
"Account Lockout": "Active Directory",
"Software Installation": "Software",
"Laptop Issue": "Laptop",
"DOMO": "DOMO",
"Desktop Issue": "Desktop",
"Network Connectivity": "Network",
"Wi-Fi": "Wi-Fi",
"WorkDay": "WorkDay",
"Printer Issue": "Printer",
"Hardware Request": "Hardware Refresh",
"Other": "Other",
"WorldShip": "WorldShip",
"RF Gun": "RF Guns",
"Apex": "Apex",
"": "Other", # fallback for blank
}
ticket_categories = [
"",
"Apex",
"Password Reset",
"Account Lockout",
"Software Installation",
"Laptop Issue",
"Desktop Issue",
"DOMO",
"Network Connectivity",
"Printer Issue",
"Hardware Request",
"Other",
"WorldShip",
"WorkDay",
"Wi-Fi",
"RF Gun",
]
ticket_priorities = [
"Low",
"Medium",
"High",
]
class ProgressDialog(customtkinter.CTkToplevel):
def __init__(self, parent, title="Progress"):
super().__init__(parent)
# Configure window
self.title(title)
self.geometry("400x150")
self.resizable(False, False)
self.transient(parent)
self.grab_set()
# Center the dialog over parent
parent_x = parent.winfo_x()
parent_y = parent.winfo_y()
parent_width = parent.winfo_width()
parent_height = parent.winfo_height()
x = parent_x + (parent_width // 2) - 200
y = parent_y + (parent_height // 2) - 75
self.geometry(f"400x150+{x}+{y}")
# Progress label
self.progress_label = customtkinter.CTkLabel(
self,
text="Initializing...",
font=customtkinter.CTkFont("Roboto", size=14),
width=360
)
self.progress_label.pack(pady=20)
# Progress bar
self.progress_bar = customtkinter.CTkProgressBar(
self,
width=360,
height=20,
mode="indeterminate"
)
self.progress_bar.pack(pady=10)
self.progress_bar.start()
# Status label for completion
self.status_label = customtkinter.CTkLabel(
self,
text="",
font=customtkinter.CTkFont("Roboto", size=12),
width=360
)
self.status_label.pack(pady=5)
# Initially disable close button
self.protocol("WM_DELETE_WINDOW", self.on_close_disabled)
self.can_close = False
def update_progress(self, text):
"""Update the progress text"""
self.progress_label.configure(text=text)
self.update()
def on_completion(self, success, message):
"""Called when the operation completes"""
self.progress_bar.stop()
self.progress_bar.set(1.0 if success else 0.0)
if success:
self.progress_label.configure(text="✓ Complete!")
self.status_label.configure(text=message, text_color="green")
else:
self.progress_label.configure(text="✗ Failed!")
self.status_label.configure(text=message, text_color="red")
self.can_close = True
self.protocol("WM_DELETE_WINDOW", self.destroy)
# Auto-close after 2 seconds if successful
if success:
self.after(2000, self.destroy)
def on_close_disabled(self):
"""Prevent closing while operation is in progress"""
pass
class App(customtkinter.CTk):
HEIGHT = 600
WIDTH = 900
def __init__(self):
super().__init__()
self.title("Easy Ticket v0.1")
self.geometry(f"{App.WIDTH}x{App.HEIGHT}")
self.resizable(False, False)
self.left_frame = customtkinter.CTkFrame(self, height=580)
self.left_frame.place(x=10, y=10)
self.about_label = customtkinter.CTkLabel(
self,
bg_color=["gray86", "gray17"], # ty:ignore[invalid-argument-type]
font=customtkinter.CTkFont("Roboto", size=13, underline=1), # ty:ignore[invalid-argument-type]
width=140,
text="Built in GSN",
)
self.about_label.place(x=40, y=550)
self.update_requesters_button = customtkinter.CTkButton(
self.left_frame,
width=140,
font=customtkinter.CTkFont("Roboto", size=12, weight="bold"),
text="Update Requesters",
fg_color="#0066cc",
command=self.update_requesters_with_progress,
)
self.update_requesters_button.place(x=30, y=500)
self.main_frame = customtkinter.CTkFrame(self, width=660, height=580)
self.main_frame.place(x=225, y=10)
self.top_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=20, weight="bold", underline=1), # ty:ignore[invalid-argument-type]
width=330,
text="Report an Incident or Make a Request",
)
self.top_label.place(x=165, y=20)
self.ticket_type_selector = customtkinter.CTkOptionMenu(
self.main_frame, values=request_type_values, width=160
)
self.ticket_type_selector.place(x=250, y=50)
self.first_name_entry = customtkinter.CTkEntry(self.main_frame, width=180)
self.first_name_entry.place(x=240, y=110)
self.first_name_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold"),
width=180,
text="First Name",
)
self.first_name_label.place(x=240, y=80)
self.last_name_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold"),
width=180,
text="Last Name",
)
self.last_name_label.place(x=240, y=140)
self.last_name_entry = customtkinter.CTkEntry(self.main_frame, width=180)
self.last_name_entry.place(x=240, y=170)
self.category_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold", underline=1), # ty:ignore[invalid-argument-type]
width=260,
text="Select the category for your ticket",
)
self.category_label.place(x=200, y=230)
self.category_selector = customtkinter.CTkOptionMenu(
self.main_frame, values=ticket_categories, width=160
)
self.category_selector.place(x=250, y=260)
self.priority_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold", underline=1), # ty:ignore[invalid-argument-type]
width=200,
text="Priority Level",
)
self.priority_label.place(x=230, y=290)
self.priority_selector = customtkinter.CTkOptionMenu(
self.main_frame, values=ticket_priorities, width=160
)
self.priority_selector.place(x=250, y=320)
self.info_label = customtkinter.CTkLabel(
self.main_frame,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold", underline=1), # ty:ignore[invalid-argument-type]
width=160,
text="Describe your issue",
)
self.info_label.place(x=250, y=390)
self.description_box = customtkinter.CTkTextbox(
self.main_frame, width=600, height=100
)
self.description_box.place(x=30, y=420)
self.description_box.insert(1.0, "")
self.submit_button = customtkinter.CTkButton(
self.main_frame,
width=600,
font=customtkinter.CTkFont("Roboto", size=16, weight="bold", underline=1), # ty:ignore[invalid-argument-type]
text="Submit Ticket",
fg_color="#009f00",
command=lambda: self.create_ticket(),
)
self.submit_button.place(x=30, y=535)
def clear_entries(self):
"""
Clears all input fields in the UI.
"""
self.first_name_entry.delete(0, "end")
self.last_name_entry.delete(0, "end")
self.description_box.delete("1.0", "end")
self.category_selector.set("")
self.priority_selector.set("")
self.ticket_type_selector.set("")
print("All entries cleared.")
def show_error(self, message):
"""
Displays an error message in a message box.
"""
CTkMessagebox(title="Error", message=message, icon="cancel").show() # ty:ignore[unresolved-attribute]
print(f"Error: {message}")
def show_success(self, message):
CTkMessagebox(title="Success", message=message, icon="check")
print(f"Success: {message}")
def send_to_teams(
self,
message,
ticket_url=None,
requester=None,
subject=None,
category=None,
description=None,
priority=None,
):
"""
Sends a formatted message to Microsoft Teams using a webhook with an attachment (Adaptive Card).
"""
webhook_url = os.getenv("WEBHOOK")
# Build a nicely formatted message using Markdown
card_body = [
{"type": "TextBlock", "text": "**New ticket created:**", "wrap": True},
]
if requester:
card_body.append(
{
"type": "TextBlock",
"text": f"**Requester:** {requester}",
"wrap": True,
}
)
if subject:
card_body.append(
{"type": "TextBlock", "text": f"**Subject:** {subject}", "wrap": True}
)
if category:
card_body.append(
{"type": "TextBlock", "text": f"**Category:** {category}", "wrap": True}
)
if priority:
card_body.append(
{"type": "TextBlock", "text": f"**Priority:** {priority}", "wrap": True}
)
if description:
card_body.append(
{
"type": "TextBlock",
"text": f"**Description:** {description}",
"wrap": True,
}
)
if ticket_url:
card_body.append(
{
"type": "TextBlock",
"text": f"[Ticket URL]({ticket_url})",
"wrap": True,
}
)
payload = {
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": card_body,
},
}
]
}
response = requests.post(webhook_url, json=payload)
if response.status_code == 200:
print("Message sent to Teams successfully.")
return True
else:
print(f"Failed to send message to Teams: {response.status_code}")
print(f"Response: {response.text}")
return False
def create_ticket(self):
"""
Creates a ticket using the Freshservice API with the provided details.
"""
requester_name = f"{self.first_name_entry.get()} {self.last_name_entry.get()}"
subject = "Issue Reported by " + requester_name.title()
description = self.description_box.get("1.0", "end-1c")
category = self.category_selector.get()
email = f"{self.first_name_entry.get().lower()}.{self.last_name_entry.get().lower()}{os.getenv('EMAIL_DOMAIN')}"
requester_id = self.get_requester_id(email)
if not category or not description:
self.show_error("All fields are required.")
return
# Build ticket data
# Map priority string to integer as required by API
priority_map = {"Low": 1, "Medium": 2, "High": 3, "Urgent": 4}
priority_value = priority_map.get(self.priority_selector.get(), 1)
ticket_data = {
"subject": f"{subject} - {category}",
"description": description,
"type": self.ticket_type_selector.get(),
"email": email,
"priority": priority_value,
"status": 2,
"requester_id": requester_id,
"responder_id": None,
"group_id": None,
# int(os.getenv("GROUP_ID")), # Load your group ID in the .env file as int
"custom_fields": {
"please_select_the_service": service_field_map.get(category, "Other")
},
}
result = api.create_ticket(
subject=ticket_data["subject"],
description=ticket_data["description"],
email=ticket_data["email"],
priority=ticket_data["priority"],
status=ticket_data["status"],
type=ticket_data["type"],
requester_id=ticket_data["requester_id"],
responder_id=ticket_data["responder_id"],
group_id=ticket_data["group_id"],
category=ticket_data["custom_fields"]["please_select_the_service"], # ty:ignore[invalid-argument-type, non-subscriptable]
)
print("Clearing entries after ticket creation.")
# Try to get the ticket ID from the API response
ticket_id = None
if isinstance(result, dict):
if "id" in result:
ticket_id = result["id"]
elif "ticket" in result and "id" in result["ticket"]:
ticket_id = result["ticket"]["id"]
if ticket_id:
ticket_url = f"https://{os.getenv('DOMAIN')}.freshservice.com/helpdesk/tickets/{ticket_id}" # Replace 'domain' with your Freshservice domain
print(f"Ticket created successfully: {ticket_url}")
self.send_to_teams(
message=None,
ticket_url=ticket_url,
requester=requester_name.title(),
subject=f"Issue Reported by {requester_name.title()} - {category}",
category=category,
description=description,
priority=self.priority_selector.get(),
)
self.show_success("Ticket created successfully!")
else:
self.show_error(
"Ticket creation failed or ticket ID not found. No URL available."
)
self.clear_entries()
# Get the requester ID based on the email from requesters.json
def get_requester_id(self, email):
"""
Fetches the requester ID based on the provided email.
"""
with open("requesters.json", "r") as file:
data = json.load(file)
for requester in data["requesters"]:
if requester.get("email") == email:
return requester.get("id")
return None
def update_requesters_with_progress(self):
"""
Updates the requesters.json file with a progress dialog.
"""
# Create and show progress dialog
progress_dialog = ProgressDialog(self, "Updating Requesters")
# Define progress callback
def progress_callback(text):
progress_dialog.update_progress(text)
# Define completion callback
def completion_callback(success, message):
progress_dialog.on_completion(success, message)
if success:
# Optionally show a success message
self.after(2500, lambda: self.show_success("Requesters updated successfully!"))
else:
# Show error message
self.after(2500, lambda: self.show_error(message))
# Start the update process
api.update_requester_file(
progress_callback=progress_callback,
completion_callback=completion_callback
)
def clear_entries(self): # noqa: F811
"""
Clears all input fields in the UI.
"""
self.first_name_entry.delete(0, "end")
self.last_name_entry.delete(0, "end")
self.description_box.delete("1.0", "end")
self.category_selector.set("")
self.priority_selector.set("")
self.ticket_type_selector.set("")
print("All entries cleared.")
def show_error(self, message): # noqa: F811
CTkMessagebox(title="Error", message=message, icon="cancel")
if __name__ == "__main__":
app = App()
app.mainloop()