-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
562 lines (453 loc) · 23.6 KB
/
main.py
File metadata and controls
562 lines (453 loc) · 23.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
import threading
import tkinter as tk
from tkinter import messagebox, ttk, simpledialog
from datetime import datetime
from filtry_sortowanie import FiltrySortowanie
from powiadomienia import SendingReminder
from statystyki import TaskStats
from categories_tags import CategoryTagManager
import json
import matplotlib.pyplot as plt # Importujemy matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from tkcalendar import DateEntry
# File path for tasks
TASKS_FILE = "tasks.json"
DEFAULT_EMAIL = "common.email@example.com"
class TaskManagerApp:
def __init__(self, root):
self.root = root
self.root.title("Task Management Application")
self.root.geometry("1200x600")
# Initialize necessary classes
self.filtry_sortowanie = FiltrySortowanie(TASKS_FILE)
self.reminder = SendingReminder(TASKS_FILE)
self.stats = TaskStats(TASKS_FILE)
self.category_manager = CategoryTagManager(TASKS_FILE)
# Start the reminder system in a separate thread
reminder_thread = threading.Thread(target=self.reminder.run_in_background, args=(TASKS_FILE,), daemon=True)
reminder_thread.start()
# Setup GUI
self.setup_gui()
# Load tasks into the GUI on startup
self.refresh_task_list()
def setup_gui(self):
# Frame for buttons
button_frame = tk.Frame(self.root, padx=10, pady=10)
button_frame.pack(side=tk.LEFT, fill=tk.Y)
# Buttons for actions
tk.Button(button_frame, text="Set Default Email", command=self.set_default_email, width=20).pack(pady=5)
tk.Button(button_frame, text="Add Task", command=self.add_task_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Remove Task", command=self.remove_task_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Filter Tasks by Key", command=self.filter_tasks_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Filter Tasks by Date", command=self.filter_tasks_date_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Sort Tasks", command=self.sort_tasks_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Task Statistics", command=self.view_statistics, width=20).pack(pady=5)
tk.Button(button_frame, text="Manage Categories", command=self.manage_categories_window, width=20).pack(pady=5)
tk.Button(button_frame, text="Exit", command=self.root.quit, width=20).pack(pady=5)
# Frame for task list display
self.display_frame = tk.Frame(self.root, padx=10, pady=10)
self.display_frame.pack(side=tk.RIGHT, expand=True, fill=tk.BOTH)
self.task_tree = ttk.Treeview(self.display_frame, columns=("ID", "Description", "Priority", "Deadline", "Time", "Status", "Category"), show="headings")
for col in self.task_tree["columns"]:
self.task_tree.heading(col, text=col)
self.task_tree.column(col, width=100)
self.task_tree.pack(expand=True, fill=tk.BOTH)
# Bind the task click event to mark it as completed
self.task_tree.bind("<ButtonRelease-1>", self.on_task_click)
def on_task_click(self, event):
# Get the item that was clicked
item_id = self.task_tree.selection()
if item_id:
task_id = self.task_tree.item(item_id[0], "values")[0] # Get task ID from clicked item
self.mark_task_completed(int(task_id))
def mark_task_completed(self, task_id):
# Find the task by its ID and change its status to "completed"
task_found = False
for task in self.filtry_sortowanie.tasks:
if task["id"] == task_id:
task["status"] = "completed"
task_found = True
break
if task_found:
# Save updated tasks to file
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
# Refresh the task list in the UI
self.refresh_task_list()
messagebox.showinfo("Success", f"Task {task_id} marked as completed.")
else:
messagebox.showerror("Error", f"Task with ID {task_id} not found.")
def load_categories(self):
"""
Load available categories from the tasks JSON file.
"""
try:
with open(TASKS_FILE, "r", encoding="utf-8") as file:
data = json.load(file)
# Extract unique categories from the tasks
return list({task["kategoria"] for task in data.get("zadania", [])})
except (FileNotFoundError, json.JSONDecodeError):
# If the file doesn't exist or is invalid, return an empty list
return []
def add_task_window(self):
# Create a new window for adding tasks
window = tk.Toplevel(self.root)
window.title("Add Task")
window.geometry("400x400")
# Labels and entries for task attributes
tk.Label(window, text="Description:").pack(pady=4)
description_entry = tk.Entry(window)
description_entry.pack(pady=4)
tk.Label(window, text="Priority:").pack(pady=4)
priority_options = ["wysoki", "średni", "niski"]
priority_combobox = ttk.Combobox(window, values=priority_options, state="readonly")
priority_combobox.set("średni") # Set default value
priority_combobox.pack(pady=4)
tk.Label(window, text="Deadline (choose date):").pack(pady=4)
# Use DateEntry for selecting a date
deadline_entry = DateEntry(window, date_pattern="yyyy-MM-dd", width=12, background="black",
foreground="white", borderwidth=2)
deadline_entry.pack(pady=4)
tk.Label(window, text="Time (HH:MM):").pack(pady=5)
# Create a Frame to place hour and minute controls on the same row
time_frame = tk.Frame(window)
time_frame.pack(pady=4)
# Hour Spinbox (0 to 23)
hour_spinbox = tk.Spinbox(time_frame, from_=0, to=23, width=5)
hour_spinbox.pack(side="left", padx=5)
hour_spinbox.delete(0, 'end') # Usuwamy domyślną wartość
hour_spinbox.insert(0, '12') # Wstawiamy wartość '12'
# Minute Spinbox (0 to 59)
minute_spinbox = tk.Spinbox(time_frame, from_=0, to=59, width=5)
minute_spinbox.pack(side="left", padx=5)
minute_spinbox.delete(0, 'end') # Usuwamy domyślną wartość
minute_spinbox.insert(0, '12')
tk.Label(window, text="Category:").pack(pady=4)
categories = self.load_categories()
category_combobox = ttk.Combobox(window, values=categories, state="normal")
category_combobox.pack(pady=4)
def save_task():
try:
id = max((task["id"] for task in self.filtry_sortowanie.tasks), default=0) + 1
description = description_entry.get()
priority = priority_combobox.get()
deadline = deadline_entry.get()
hour = hour_spinbox.get()
minute = minute_spinbox.get()
time = f"{int(hour):02}:{int(minute):02}"
category = category_combobox.get()
status = "not completed"
# Validate inputs
datetime.strptime(deadline, "%Y-%m-%d") # Validate date
datetime.strptime(time, "%H:%M") # Validate time
if priority not in {"wysoki", "średni", "niski"}:
raise ValueError("Invalid priority value!")
# Add task
new_task = {
"id": id,
"opis": description,
"priorytet": priority,
"termin": deadline,
"godzina": time,
"email": DEFAULT_EMAIL, # Use the default email
"status": status,
"kategoria": category
}
self.filtry_sortowanie.tasks.append(new_task)
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
self.category_manager.add_category(category)
# Refresh task list
self.refresh_task_list()
window.destroy()
messagebox.showinfo("Success", "Task added successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to add task: {e}")
tk.Button(window, text="Save Task", command=save_task, width=10, height=1, font=("Helvetica", 10)).pack(pady=20)
def remove_task_window(self):
window = tk.Toplevel(self.root)
window.title("Remove Task")
window.geometry("300x200")
tk.Label(window, text="Select Task to Remove:").pack(pady=5)
# Przygotowanie listy dostępnych zadań z ID i opisami
task_options = [f"{task['id']} - {task['opis']}" for task in self.filtry_sortowanie.tasks]
# ComboBox do wyboru zadania
task_combobox = ttk.Combobox(window, values=task_options, state="normal")
task_combobox.pack(pady=5)
def remove_task():
selected_task = task_combobox.get()
if selected_task:
task_id_str = selected_task.split(" - ")[0] # Wyciągamy ID z wybranego tekstu
task_id = int(task_id_str)
# Usuwamy zadanie z listy
self.filtry_sortowanie.tasks = [task for task in self.filtry_sortowanie.tasks if task["id"] != task_id]
# Zapisujemy zmienioną listę zadań do pliku
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
# Odświeżamy listę zadań w GUI
self.refresh_task_list()
window.destroy()
messagebox.showinfo("Success", "Task removed successfully!")
else:
messagebox.showerror("Error", "No task selected!")
tk.Button(window, text="Remove Task", command=remove_task).pack(pady=20)
def view_all_tasks(self):
self.refresh_task_list()
def view_statistics(self):
# Sprawdzamy, czy wykres jest już widoczny i ukrywamy go jeśli tak
if hasattr(self, 'chart_canvas') and self.chart_canvas.get_tk_widget().winfo_ismapped():
self.chart_canvas.get_tk_widget().pack_forget()
# Tworzymy nowe okno wyboru statystyki
stat_window = tk.Toplevel(self.root)
stat_window.title("Select Statistic Type")
stat_window.geometry("300x200")
# Opis dostępnych statystyk
tk.Label(stat_window, text="Select the statistics to display:").pack(pady=10)
# Lista dostępnych opcji statystyk
options = ["Status", "Category", "Deadline"]
stat_choice = tk.StringVar(stat_window)
stat_choice.set(options[0]) # Domyślnie wybrana opcja
# Tworzymy rozwijane menu z opcjami
option_menu = tk.OptionMenu(stat_window, stat_choice, *options)
option_menu.pack(pady=10)
# Funkcja do generowania wykresu na podstawie wybranej opcji
def show_chart():
selected_stat = stat_choice.get()
if selected_stat == "Status":
self.plot_status_statistics() # Rysowanie wykresu dla statusu
elif selected_stat == "Category":
self.plot_category_statistics() # Rysowanie wykresu dla kategorii
elif selected_stat == "Deadline":
self.plot_deadline_statistics() # Rysowanie wykresu dla deadline
stat_window.destroy() # Zamykamy okno wyboru po narysowaniu wykresu
# Przycisk do zatwierdzenia wyboru
tk.Button(stat_window, text="Show Statistics", command=show_chart).pack(pady=20)
def plot_status_statistics(self):
# Wykres dla statusu (wykorzystanie istniejącej funkcji)
status_data = self.stats.c_by_status()
status_labels = list(status_data.keys())
status_counts = list(status_data.values())
colors = ['green' if status == 'completed' else 'red' for status in status_labels]
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(status_labels, status_counts, color=colors)
ax.set_title('Task Statuses')
ax.set_xlabel('Status')
ax.set_ylabel('Count')
self.chart_canvas = FigureCanvasTkAgg(fig, master=self.root)
self.chart_canvas.draw()
self.chart_canvas.get_tk_widget().pack()
def filter_tasks_window(self):
window = tk.Toplevel(self.root)
window.title("Filter Tasks by Key")
window.geometry("300x250")
tk.Label(window, text="Select filtering key:").pack(pady=5)
# Mapa kluczy do tłumaczenia na nazwy w zadaniach
key_mapping = {
"Priority": "priorytet",
"Status": "status",
"Category": "kategoria",
"Description": "opis",
"Deadline": "termin",
"Time": "godzina",
"ID": "id"
}
key_var = tk.StringVar(value="Priority")
key_menu = tk.OptionMenu(window, key_var, *key_mapping.keys())
key_menu.pack(pady=5)
tk.Label(window, text="Enter value to filter by:").pack(pady=5)
# Pole tekstowe do podania wartości
filter_value_entry = tk.Entry(window)
filter_value_entry.pack(pady=5)
def apply_filter():
try:
# Pobierz wybrany klucz oraz wprowadzaną wartość
key = key_mapping[key_var.get()]
filter_value = filter_value_entry.get()
# Filtrowanie zadań na podstawie wybranego klucza i wartości
try:
# Zapisz przefiltrowane zadania do pliku JSON
self.filtry_sortowanie.tasks = self.filtry_sortowanie.filter_tasks(key, filter_value)
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
self.refresh_task_list()
window.destroy()
messagebox.showinfo("Success", "Tasks filtered and saved successfully!")
except:
messagebox.showwarning("No tasks found", "No tasks match the selected filter.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
tk.Button(window, text="Apply Filter", command=apply_filter).pack(pady=20)
def filter_tasks_date_window(self):
window = tk.Toplevel(self.root)
window.title("Filter Tasks by Date Range")
window.geometry("300x250")
tk.Label(window, text="Select Start Date:").pack(pady=5)
# DateEntry widget to select start date
start_date_entry = DateEntry(window, width=12, background='darkblue', foreground='white', borderwidth=2)
start_date_entry.pack(pady=5)
tk.Label(window, text="Select End Date:").pack(pady=5)
# DateEntry widget to select end date
end_date_entry = DateEntry(window, width=12, background='darkblue', foreground='white', borderwidth=2)
end_date_entry.pack(pady=5)
def apply_filter():
try:
# Get the selected start and end dates
start_date = start_date_entry.get_date()
end_date = end_date_entry.get_date()
# Convert dates to string format (YYYY-MM-DD)
start_date_str = start_date.strftime("%Y-%m-%d")
end_date_str = end_date.strftime("%Y-%m-%d")
# Filter tasks based on selected date range using filter_tasks_by_date function
self.filtry_sortowanie.tasks = self.filtry_sortowanie.filter_tasks_by_date(start_date_str, end_date_str)
try:
# Save filtered tasks to the JSON file
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
self.refresh_task_list()
window.destroy()
messagebox.showinfo("Success", "Tasks filtered and saved successfully!")
except:
messagebox.showwarning("No tasks found", "No tasks match the selected date range.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
tk.Button(window, text="Apply Filter", command=apply_filter).pack(pady=20)
def sort_tasks_window(self):
window = tk.Toplevel(self.root)
window.title("Sort Tasks")
window.geometry("300x200")
tk.Label(window, text="Select sorting key:").pack(pady=5)
key_mapping = {
"ID": "id",
"Description": "opis",
"Priority": "priorytet",
"Deadline": "termin",
"Time": "godzina",
"Status": "status",
"Category": "kategoria"
}
key_var = tk.StringVar(value="ID")
key_menu = tk.OptionMenu(window, key_var, *key_mapping.keys())
key_menu.pack(pady=5)
tk.Label(window, text="Select sorting order:").pack(pady=5)
order_var = tk.StringVar(value="ascending")
ascending_radio = tk.Radiobutton(window, text="Ascending", variable=order_var, value="ascending")
ascending_radio.pack()
descending_radio = tk.Radiobutton(window, text="Descending", variable=order_var, value="descending")
descending_radio.pack()
def apply_sorting():
key = key_mapping[key_var.get()]
order = order_var.get()
try:
reverse = True if order == "descending" else False
self.filtry_sortowanie.tasks = self.filtry_sortowanie.sort_tasks(key, reverse)
with open(TASKS_FILE, 'w', encoding='utf-8') as file:
json.dump({"zadania": self.filtry_sortowanie.tasks}, file, ensure_ascii=False, indent=4)
self.refresh_task_list()
window.destroy()
messagebox.showinfo("Success", "Tasks sorted successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to sort tasks: {e}")
tk.Button(window, text="Sort", command=apply_sorting).pack(pady=20)
def plot_category_statistics(self):
# Wykres dla kategorii
categories_data = self.stats.c_by_categories()
category_labels = list(categories_data.keys())
category_counts = list(categories_data.values())
fig, ax = plt.subplots(figsize=(10, 8))
ax.bar(category_labels, category_counts, color='blue')
# Dodaj set_xticks przed set_xticklabels
ax.set_xticks(range(len(category_labels)))
ax.set_xticklabels(category_labels, rotation=90)
ax.set_title('Task Categories')
ax.set_xlabel('Category')
ax.set_ylabel('Count')
self.chart_canvas = FigureCanvasTkAgg(fig, master=self.root)
self.chart_canvas.draw()
self.chart_canvas.get_tk_widget().pack()
def plot_deadline_statistics(self):
# Wykres dla deadline (ile zadań do zrobienia dzisiaj, jutro, w tym tygodniu)
deadline_data = self.stats.close_to_deadline()
deadline_labels = list(deadline_data.keys())
deadline_counts = list(deadline_data.values())
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(deadline_labels, deadline_counts, color='purple')
ax.set_title('Tasks Close to Deadline')
ax.set_xlabel('Deadline')
ax.set_ylabel('Count')
self.chart_canvas = FigureCanvasTkAgg(fig, master=self.root)
self.chart_canvas.draw()
self.chart_canvas.get_tk_widget().pack()
def manage_categories_window(self):
# Tworzenie nowego okna do zarządzania kategoriami
window = tk.Toplevel(self.root)
window.title("Manage Categories")
window.geometry("400x300")
tk.Label(window, text="Manage Categories", font=("Helvetica", 14)).pack(pady=10)
# Lista kategorii w oknie
category_listbox = tk.Listbox(window, selectmode=tk.SINGLE)
category_listbox.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
# Pobranie kategorii z CategoryTagManager
categories = self.category_manager.view_categories()
for category in categories:
category_listbox.insert(tk.END, category)
def add_category():
"""Dodawanie nowej kategorii."""
new_category = simpledialog.askstring("Add Category", "Enter the name of the new category:")
if new_category and new_category.strip():
if new_category in categories:
messagebox.showerror("Error", f"Category '{new_category}' already exists.")
else:
try:
self.category_manager.add_category(new_category)
category_listbox.insert(tk.END, new_category)
categories.append(new_category)
messagebox.showinfo("Success", f"Category '{new_category}' added successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to add category: {e}")
else:
messagebox.showerror("Error", "Category name cannot be empty.")
def remove_category():
"""Usuwanie wybranej kategorii."""
selected = category_listbox.curselection()
if selected:
category = category_listbox.get(selected[0])
try:
self.category_manager.remove_category(category)
category_listbox.delete(selected)
categories.remove(category)
messagebox.showinfo("Success", f"Category '{category}' removed successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to remove category: {e}")
else:
messagebox.showerror("Error", "No category selected.")
# Przyciski do zarządzania kategoriami
button_frame = tk.Frame(window)
button_frame.pack(pady=10)
tk.Button(button_frame, text="Add Category", command=add_category, width=15).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="Remove Category", command=remove_category, width=15).pack(side=tk.LEFT, padx=5)
tk.Button(window, text="Close", command=window.destroy, width=15).pack(pady=10)
def refresh_task_list(self):
# Czyszczenie obecnych wpisów w widoku drzewa
for item in self.task_tree.get_children():
self.task_tree.delete(item)
# Dodawanie tylko zadań, które nie są ukończone
for task in self.filtry_sortowanie.tasks:
if task["status"] != "completed":
self.task_tree.insert("", tk.END, values=(
task["id"], task["opis"], task["priorytet"], task["termin"], task["godzina"], task["status"],
task["kategoria"]
))
def set_default_email(self):
# Prompt the user to input a new default email
new_email = simpledialog.askstring("Set Default Email", "Enter the default email address:")
if new_email:
global DEFAULT_EMAIL
DEFAULT_EMAIL = new_email
messagebox.showinfo("Success", f"Default email set to: {DEFAULT_EMAIL}")
# Main function
def main():
root = tk.Tk()
app = TaskManagerApp(root)
root.mainloop()
if __name__ == "__main__":
main()