-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_manager.py
More file actions
1224 lines (1042 loc) · 45.8 KB
/
task_manager.py
File metadata and controls
1224 lines (1042 loc) · 45.8 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
#!/usr/bin/env python3
"""
Task Timer Manager - A Python terminal application for managing tasks with time tracking.
"""
import json
import os
import time
import threading
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import sys
class Task:
"""Represents a single task with time tracking capabilities."""
def __init__(self, title: str, description: str = "", project: str = "General",
category: str = "General", estimated_hours: float = 0.0, deadline: Optional[str] = None,
hourly_rate: float = 0.0):
self.id = self._generate_id()
self.title = title
self.description = description
self.project = project
self.category = category
self.estimated_hours = estimated_hours
self.actual_hours = 0.0
self.deadline = deadline
self.hourly_rate = hourly_rate
self.created_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
self.status = "Not Started" # Not Started, In Progress, Completed, On Hold
self.completed_at = None
self.timer_start_time = None
self.timer_running = False
self.session_time = 0.0 # Time accumulated in current session
def _generate_id(self) -> str:
"""Generate a unique ID for the task."""
return f"task_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
def add_time(self, hours: float) -> None:
"""Add actual time spent on the task."""
if hours > 0:
self.actual_hours += hours
self.updated_at = datetime.now().isoformat()
def start_timer(self) -> bool:
"""Start the timer for this task."""
if not self.timer_running:
self.timer_start_time = time.time()
self.timer_running = True
self.updated_at = datetime.now().isoformat()
return True
return False
def stop_timer(self) -> float:
"""Stop the timer and return the elapsed time in hours."""
if self.timer_running and self.timer_start_time:
elapsed_time = time.time() - self.timer_start_time
elapsed_hours = elapsed_time / 3600.0 # Convert seconds to hours
self.session_time += elapsed_hours
self.actual_hours += elapsed_hours
self.timer_running = False
self.timer_start_time = None
self.updated_at = datetime.now().isoformat()
return elapsed_hours
return 0.0
def restart_timer(self) -> float:
"""Restart the timer (stop current session and start new one)."""
elapsed = self.stop_timer()
self.start_timer()
return elapsed
def get_current_session_time(self) -> float:
"""Get the time elapsed in the current session."""
if self.timer_running and self.timer_start_time:
current_elapsed = time.time() - self.timer_start_time
return (self.session_time + current_elapsed / 3600.0)
return self.session_time
def get_total_time(self) -> float:
"""Get total time including current session."""
if self.timer_running and self.timer_start_time:
current_elapsed = time.time() - self.timer_start_time
return self.actual_hours + (current_elapsed / 3600.0)
return self.actual_hours
def get_current_value(self) -> float:
"""Calculate current value based on time spent and hourly rate."""
total_time = self.get_total_time()
return total_time * self.hourly_rate
def get_estimated_value(self) -> float:
"""Calculate estimated value based on estimated hours and hourly rate."""
return self.estimated_hours * self.hourly_rate
def format_time(self, hours: float) -> str:
"""Format hours as hh:mm:ss."""
total_seconds = int(hours * 3600)
hours_part = total_seconds // 3600
minutes_part = (total_seconds % 3600) // 60
seconds_part = total_seconds % 60
return f"{hours_part:02d}:{minutes_part:02d}:{seconds_part:02d}"
def update_status(self, status: str) -> None:
"""Update the task status."""
valid_statuses = ["Not Started", "In Progress", "Completed", "On Hold"]
if status in valid_statuses:
self.status = status
self.updated_at = datetime.now().isoformat()
if status == "Completed":
self.completed_at = datetime.now().isoformat()
def is_overdue(self) -> bool:
"""Check if the task is overdue."""
if not self.deadline or self.status == "Completed":
return False
try:
deadline_date = datetime.fromisoformat(self.deadline)
return datetime.now() > deadline_date
except ValueError:
return False
def get_progress_percentage(self) -> float:
"""Calculate progress percentage based on time spent vs estimated time."""
if self.estimated_hours == 0:
return 0.0
total_time = self.get_total_time()
return min(100.0, (total_time / self.estimated_hours) * 100)
def to_dict(self) -> Dict:
"""Convert task to dictionary for JSON serialization."""
return {
'id': self.id,
'title': self.title,
'description': self.description,
'project': self.project,
'category': self.category,
'estimated_hours': self.estimated_hours,
'actual_hours': self.actual_hours,
'deadline': self.deadline,
'hourly_rate': self.hourly_rate,
'created_at': self.created_at,
'updated_at': self.updated_at,
'status': self.status,
'completed_at': self.completed_at,
'timer_running': self.timer_running,
'session_time': self.session_time
}
@classmethod
def from_dict(cls, data: Dict) -> 'Task':
"""Create a Task instance from a dictionary."""
task = cls(
title=data['title'],
description=data.get('description', ''),
project=data.get('project', 'General'),
category=data.get('category', 'General'),
estimated_hours=data.get('estimated_hours', 0.0),
deadline=data.get('deadline'),
hourly_rate=data.get('hourly_rate', 0.0)
)
task.id = data['id']
task.actual_hours = data.get('actual_hours', 0.0)
task.created_at = data.get('created_at', datetime.now().isoformat())
task.updated_at = data.get('updated_at', datetime.now().isoformat())
task.status = data.get('status', 'Not Started')
task.completed_at = data.get('completed_at')
task.timer_running = data.get('timer_running', False)
task.session_time = data.get('session_time', 0.0)
# Reset timer state when loading from file
task.timer_start_time = None
return task
def __str__(self) -> str:
"""String representation of the task."""
overdue_indicator = " (OVERDUE)" if self.is_overdue() else ""
timer_indicator = " [TIMER RUNNING]" if self.timer_running else ""
progress = self.get_progress_percentage()
total_time = self.get_total_time()
estimated_time_str = self.format_time(self.estimated_hours) if self.estimated_hours > 0 else "00:00:00"
actual_time_str = self.format_time(total_time)
# Value information
value_info = ""
if self.hourly_rate > 0:
current_value = self.get_current_value()
estimated_value = self.get_estimated_value()
value_info = f"\n Rate: ${self.hourly_rate:.2f}/h | Current Value: ${current_value:.2f} | Estimated Value: ${estimated_value:.2f}"
return f"[{self.id}] {self.title} - {self.status}{overdue_indicator}{timer_indicator}\n" \
f" Project: {self.project} | Category: {self.category}\n" \
f" Estimated: {estimated_time_str} | Actual: {actual_time_str} | Progress: {progress:.1f}%{value_info}\n" \
f" Deadline: {self.deadline or 'No deadline'}\n" \
f" Description: {self.description}"
class TaskManager:
"""Manages a collection of tasks with persistence."""
def __init__(self, data_file: str = "tasks.json"):
self.data_file = data_file
self.tasks: List[Task] = []
self.load_tasks()
def load_tasks(self) -> None:
"""Load tasks from the JSON file."""
if os.path.exists(self.data_file):
try:
with open(self.data_file, 'r') as f:
data = json.load(f)
self.tasks = [Task.from_dict(task_data) for task_data in data]
except (json.JSONDecodeError, KeyError) as e:
print(f"Error loading tasks: {e}")
self.tasks = []
else:
self.tasks = []
def save_tasks(self) -> None:
"""Save tasks to the JSON file."""
try:
with open(self.data_file, 'w') as f:
json.dump([task.to_dict() for task in self.tasks], f, indent=2)
except Exception as e:
print(f"Error saving tasks: {e}")
def add_task(self, task: Task) -> None:
"""Add a new task."""
self.tasks.append(task)
self.save_tasks()
def get_task_by_id(self, task_id: str) -> Optional[Task]:
"""Get a task by its ID."""
for task in self.tasks:
if task.id == task_id:
return task
return None
def update_task(self, task_id: str, **kwargs) -> bool:
"""Update a task with new values."""
task = self.get_task_by_id(task_id)
if task:
for key, value in kwargs.items():
if hasattr(task, key):
setattr(task, key, value)
task.updated_at = datetime.now().isoformat()
self.save_tasks()
return True
return False
def delete_task(self, task_id: str) -> bool:
"""Delete a task by ID."""
for i, task in enumerate(self.tasks):
if task.id == task_id:
del self.tasks[i]
self.save_tasks()
return True
return False
def get_tasks_by_project(self, project: str) -> List[Task]:
"""Get all tasks in a specific project."""
return [task for task in self.tasks if task.project.lower() == project.lower()]
def get_tasks_by_category(self, category: str) -> List[Task]:
"""Get all tasks in a specific category."""
return [task for task in self.tasks if task.category.lower() == category.lower()]
def get_tasks_by_status(self, status: str) -> List[Task]:
"""Get all tasks with a specific status."""
return [task for task in self.tasks if task.status.lower() == status.lower()]
def get_overdue_tasks(self) -> List[Task]:
"""Get all overdue tasks."""
return [task for task in self.tasks if task.is_overdue()]
def get_all_projects(self) -> List[str]:
"""Get all unique projects."""
projects = set(task.project for task in self.tasks)
return sorted(list(projects))
def get_all_categories(self) -> List[str]:
"""Get all unique categories."""
categories = set(task.category for task in self.tasks)
return sorted(list(categories))
def get_running_timers(self) -> List[Task]:
"""Get all tasks with running timers."""
return [task for task in self.tasks if task.timer_running]
def stop_all_timers(self) -> None:
"""Stop all running timers."""
for task in self.tasks:
if task.timer_running:
task.stop_timer()
self.save_tasks()
def get_total_value(self) -> float:
"""Get total current value of all tasks."""
return sum(task.get_current_value() for task in self.tasks)
def get_estimated_total_value(self) -> float:
"""Get total estimated value of all tasks."""
return sum(task.get_estimated_value() for task in self.tasks)
def get_tasks_with_rates(self) -> List[Task]:
"""Get all tasks that have hourly rates set."""
return [task for task in self.tasks if task.hourly_rate > 0]
def get_statistics(self) -> Dict:
"""Get task statistics."""
total_tasks = len(self.tasks)
completed_tasks = len(self.get_tasks_by_status("Completed"))
overdue_tasks = len(self.get_overdue_tasks())
running_timers = len(self.get_running_timers())
total_estimated_hours = sum(task.estimated_hours for task in self.tasks)
total_actual_hours = sum(task.get_total_time() for task in self.tasks)
total_current_value = self.get_total_value()
total_estimated_value = self.get_estimated_total_value()
tasks_with_rates = len(self.get_tasks_with_rates())
return {
'total_tasks': total_tasks,
'completed_tasks': completed_tasks,
'overdue_tasks': overdue_tasks,
'running_timers': running_timers,
'total_estimated_hours': total_estimated_hours,
'total_actual_hours': total_actual_hours,
'total_current_value': total_current_value,
'total_estimated_value': total_estimated_value,
'tasks_with_rates': tasks_with_rates,
'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
}
def main():
"""Main application entry point."""
print("=" * 60)
print(" TASK TIMER MANAGER")
print("=" * 60)
task_manager = TaskManager()
while True:
print("\n" + "=" * 40)
print("MAIN MENU")
print("=" * 40)
print("1. View All Tasks")
print("2. Add New Task")
print("3. Update Task")
print("4. Delete Task")
print("5. Add Time to Task")
print("6. Start Timer")
print("7. Stop Timer")
print("8. Restart Timer")
print("9. View Running Timers")
print("10. Live Timer Display")
print("11. Set Hourly Rate")
print("12. View Tasks by Project")
print("13. View Tasks by Category")
print("14. View Tasks by Status")
print("15. View Overdue Tasks")
print("16. View Statistics")
print("17. Exit")
choice = input("\nEnter your choice (1-17): ").strip()
if choice == '1':
view_all_tasks(task_manager)
elif choice == '2':
add_new_task(task_manager)
elif choice == '3':
update_task(task_manager)
elif choice == '4':
delete_task(task_manager)
elif choice == '5':
add_time_to_task(task_manager)
elif choice == '6':
start_timer(task_manager)
elif choice == '7':
stop_timer(task_manager)
elif choice == '8':
restart_timer(task_manager)
elif choice == '9':
view_running_timers(task_manager)
elif choice == '10':
live_timer_display(task_manager)
elif choice == '11':
set_hourly_rate(task_manager)
elif choice == '12':
view_tasks_by_project(task_manager)
elif choice == '13':
view_tasks_by_category(task_manager)
elif choice == '14':
view_tasks_by_status(task_manager)
elif choice == '15':
view_overdue_tasks(task_manager)
elif choice == '16':
view_statistics(task_manager)
elif choice == '17':
print("\nThank you for using Task Timer Manager!")
break
else:
print("Invalid choice. Please try again.")
def view_all_tasks(task_manager: TaskManager) -> None:
"""Display all tasks."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print(f"\n{'='*60}")
print(f"ALL TASKS ({len(task_manager.tasks)} total)")
print(f"{'='*60}")
for i, task in enumerate(task_manager.tasks, 1):
print(f"\n{i}. {task}")
def add_new_task(task_manager: TaskManager) -> None:
"""Add a new task."""
print("\n" + "="*40)
print("ADD NEW TASK")
print("="*40)
title = input("Enter task title: ").strip()
if not title:
print("Title cannot be empty.")
return
description = input("Enter task description (optional): ").strip()
project = input("Enter project name (default: General): ").strip() or "General"
category = input("Enter category (default: General): ").strip() or "General"
try:
estimated_hours = float(input("Enter estimated hours: ") or "0")
except ValueError:
print("Invalid hours format. Using 0 hours.")
estimated_hours = 0.0
try:
hourly_rate = float(input("Enter hourly rate (optional, $0.00): ") or "0")
except ValueError:
print("Invalid rate format. Using $0.00.")
hourly_rate = 0.0
deadline = input("Enter deadline (YYYY-MM-DD, optional): ").strip()
if deadline:
try:
datetime.strptime(deadline, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Ignoring deadline.")
deadline = None
task = Task(title, description, project, category, estimated_hours, deadline, hourly_rate)
task_manager.add_task(task)
print(f"\nTask '{title}' added successfully to project '{project}' with ID: {task.id}")
if hourly_rate > 0:
print(f"Hourly rate set to ${hourly_rate:.2f}/hour")
def update_task(task_manager: TaskManager) -> None:
"""Update an existing task."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print("\n" + "="*40)
print("UPDATE TASK")
print("="*40)
# Show available tasks
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
print(f"{i}. [{task.id}] {task.title}")
try:
task_index = int(input("\nEnter task number to update: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
print(f"\nUpdating task: {task.title}")
# Update fields
new_title = input(f"Enter new title (current: {task.title}): ").strip()
if new_title:
task.title = new_title
new_description = input(f"Enter new description (current: {task.description}): ").strip()
if new_description:
task.description = new_description
new_project = input(f"Enter new project (current: {task.project}): ").strip()
if new_project:
task.project = new_project
new_category = input(f"Enter new category (current: {task.category}): ").strip()
if new_category:
task.category = new_category
new_estimated = input(f"Enter new estimated hours (current: {task.estimated_hours}): ").strip()
if new_estimated:
try:
task.estimated_hours = float(new_estimated)
except ValueError:
print("Invalid hours format. Keeping current value.")
new_status = input(f"Enter new status (current: {task.status}): ").strip()
if new_status:
task.update_status(new_status)
new_deadline = input(f"Enter new deadline (current: {task.deadline or 'None'}): ").strip()
if new_deadline:
try:
datetime.strptime(new_deadline, "%Y-%m-%d")
task.deadline = new_deadline
except ValueError:
print("Invalid date format. Keeping current deadline.")
new_hourly_rate = input(f"Enter new hourly rate (current: ${task.hourly_rate:.2f}): ").strip()
if new_hourly_rate:
try:
task.hourly_rate = float(new_hourly_rate)
except ValueError:
print("Invalid rate format. Keeping current rate.")
task_manager.save_tasks()
print("Task updated successfully!")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def delete_task(task_manager: TaskManager) -> None:
"""Delete a task."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print("\n" + "="*40)
print("DELETE TASK")
print("="*40)
# Show available tasks
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
print(f"{i}. [{task.id}] {task.title}")
try:
task_index = int(input("\nEnter task number to delete: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
confirm = input(f"Are you sure you want to delete '{task.title}'? (y/N): ").strip().lower()
if confirm == 'y':
task_manager.delete_task(task.id)
print("Task deleted successfully!")
else:
print("Deletion cancelled.")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def add_time_to_task(task_manager: TaskManager) -> None:
"""Add time spent to a task."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print("\n" + "="*40)
print("ADD TIME TO TASK")
print("="*40)
# Show available tasks
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
print(f"{i}. [{task.id}] {task.title} (Current: {task.actual_hours}h)")
try:
task_index = int(input("\nEnter task number: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
hours = float(input(f"Enter hours to add to '{task.title}': "))
if hours > 0:
task.add_time(hours)
task_manager.save_tasks()
print(f"Added {hours} hours to '{task.title}'. Total: {task.actual_hours}h")
else:
print("Hours must be positive.")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def view_tasks_by_project(task_manager: TaskManager) -> None:
"""View tasks filtered by project."""
projects = task_manager.get_all_projects()
if not projects:
print("\nNo projects found.")
return
print("\n" + "="*40)
print("VIEW TASKS BY PROJECT")
print("="*40)
print("Available projects:")
for i, project in enumerate(projects, 1):
print(f"{i}. {project}")
try:
proj_index = int(input("\nEnter project number: ")) - 1
if 0 <= proj_index < len(projects):
project = projects[proj_index]
tasks = task_manager.get_tasks_by_project(project)
if tasks:
print(f"\nTasks in project '{project}':")
for task in tasks:
print(f"\n{task}")
else:
print(f"No tasks found in project '{project}'.")
else:
print("Invalid project number.")
except ValueError:
print("Invalid input. Please enter a number.")
def view_tasks_by_category(task_manager: TaskManager) -> None:
"""View tasks filtered by category."""
categories = task_manager.get_all_categories()
if not categories:
print("\nNo categories found.")
return
print("\n" + "="*40)
print("VIEW TASKS BY CATEGORY")
print("="*40)
print("Available categories:")
for i, category in enumerate(categories, 1):
print(f"{i}. {category}")
try:
cat_index = int(input("\nEnter category number: ")) - 1
if 0 <= cat_index < len(categories):
category = categories[cat_index]
tasks = task_manager.get_tasks_by_category(category)
if tasks:
print(f"\nTasks in category '{category}':")
for task in tasks:
print(f"\n{task}")
else:
print(f"No tasks found in category '{category}'.")
else:
print("Invalid category number.")
except ValueError:
print("Invalid input. Please enter a number.")
def view_tasks_by_status(task_manager: TaskManager) -> None:
"""View tasks filtered by status."""
statuses = ["Not Started", "In Progress", "Completed", "On Hold"]
print("\n" + "="*40)
print("VIEW TASKS BY STATUS")
print("="*40)
print("Available statuses:")
for i, status in enumerate(statuses, 1):
print(f"{i}. {status}")
try:
status_index = int(input("\nEnter status number: ")) - 1
if 0 <= status_index < len(statuses):
status = statuses[status_index]
tasks = task_manager.get_tasks_by_status(status)
if tasks:
print(f"\nTasks with status '{status}':")
for task in tasks:
print(f"\n{task}")
else:
print(f"No tasks found with status '{status}'.")
else:
print("Invalid status number.")
except ValueError:
print("Invalid input. Please enter a number.")
def view_overdue_tasks(task_manager: TaskManager) -> None:
"""View overdue tasks."""
overdue_tasks = task_manager.get_overdue_tasks()
print("\n" + "="*40)
print("OVERDUE TASKS")
print("="*40)
if overdue_tasks:
print(f"Found {len(overdue_tasks)} overdue tasks:")
for task in overdue_tasks:
print(f"\n{task}")
else:
print("No overdue tasks found.")
def view_statistics(task_manager: TaskManager) -> None:
"""View task statistics."""
stats = task_manager.get_statistics()
print("\n" + "="*40)
print("TASK STATISTICS")
print("="*40)
print(f"Total Tasks: {stats['total_tasks']}")
print(f"Completed Tasks: {stats['completed_tasks']}")
print(f"Overdue Tasks: {stats['overdue_tasks']}")
print(f"Running Timers: {stats['running_timers']}")
print(f"Completion Rate: {stats['completion_rate']:.1f}%")
# Create a dummy task to use the format_time method
dummy_task = Task("dummy", "", "", "", 0)
estimated_str = dummy_task.format_time(stats['total_estimated_hours'])
actual_str = dummy_task.format_time(stats['total_actual_hours'])
print(f"Total Estimated Time: {estimated_str}")
print(f"Total Actual Time: {actual_str}")
# Show value information
if stats['tasks_with_rates'] > 0:
current_value_str = f"${stats['total_current_value']:.2f}"
estimated_value_str = f"${stats['total_estimated_value']:.2f}"
print(f"\nValue Information:")
print(f"Tasks with Rates: {stats['tasks_with_rates']}")
print(f"Total Current Value: {current_value_str}")
print(f"Total Estimated Value: {estimated_value_str}")
if stats['total_estimated_hours'] > 0:
efficiency = (stats['total_actual_hours'] / stats['total_estimated_hours']) * 100
print(f"Time Efficiency: {efficiency:.1f}%")
# Show project breakdown
projects = task_manager.get_all_projects()
if projects:
print(f"\nProject Breakdown:")
for project in projects:
project_tasks = task_manager.get_tasks_by_project(project)
completed = len([t for t in project_tasks if t.status == "Completed"])
total_estimated = sum(t.estimated_hours for t in project_tasks)
total_actual = sum(t.get_total_time() for t in project_tasks)
total_value = sum(t.get_current_value() for t in project_tasks)
completion_rate = (completed / len(project_tasks) * 100) if project_tasks else 0
estimated_str = dummy_task.format_time(total_estimated)
actual_str = dummy_task.format_time(total_actual)
value_str = f"${total_value:.2f}" if total_value > 0 else "No rates set"
print(f" {project}: {len(project_tasks)} tasks, {completed} completed ({completion_rate:.1f}%), {estimated_str} estimated, {actual_str} actual, {value_str} value")
def start_timer(task_manager: TaskManager) -> None:
"""Start a timer for a task."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
# Check if any timers are already running
running_timers = task_manager.get_running_timers()
if running_timers:
print(f"\nWarning: {len(running_timers)} timer(s) are already running:")
for task in running_timers:
print(f" - {task.title}")
choice = input("\nDo you want to stop all running timers and start a new one? (y/N): ").strip().lower()
if choice == 'y':
task_manager.stop_all_timers()
else:
return
print("\n" + "="*40)
print("START TIMER")
print("="*40)
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
status_indicator = " [TIMER RUNNING]" if task.timer_running else ""
print(f"{i}. [{task.id}] {task.title}{status_indicator}")
try:
task_index = int(input("\nEnter task number: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
if task.start_timer():
task_manager.save_tasks()
print(f"\nTimer started for '{task.title}' at {datetime.now().strftime('%H:%M:%S')}")
else:
print(f"Timer is already running for '{task.title}'")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def stop_timer(task_manager: TaskManager) -> None:
"""Stop a timer for a task."""
running_timers = task_manager.get_running_timers()
if not running_timers:
print("\nNo timers are currently running.")
return
print("\n" + "="*40)
print("STOP TIMER")
print("="*40)
print("Running timers:")
for i, task in enumerate(running_timers, 1):
current_time = task.get_current_session_time()
current_time_str = task.format_time(current_time)
print(f"{i}. [{task.id}] {task.title} - {current_time_str}")
try:
timer_index = int(input("\nEnter timer number to stop: ")) - 1
if 0 <= timer_index < len(running_timers):
task = running_timers[timer_index]
elapsed = task.stop_timer()
task_manager.save_tasks()
elapsed_str = task.format_time(elapsed)
total_str = task.format_time(task.actual_hours)
print(f"\nTimer stopped for '{task.title}'")
print(f"Session time: {elapsed_str}")
print(f"Total time: {total_str}")
else:
print("Invalid timer number.")
except ValueError:
print("Invalid input. Please enter a number.")
def restart_timer(task_manager: TaskManager) -> None:
"""Restart a timer for a task (reset to zero and start new timer)."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print("\n" + "="*40)
print("RESTART TIMER")
print("="*40)
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
status_indicator = " [TIMER RUNNING]" if task.timer_running else ""
total_time_str = task.format_time(task.get_total_time())
print(f"{i}. [{task.id}] {task.title}{status_indicator} - Total: {total_time_str}")
try:
task_index = int(input("\nEnter task number to restart timer: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
# Stop any running timer first
if task.timer_running:
elapsed = task.stop_timer()
elapsed_str = task.format_time(elapsed)
print(f"Stopped previous timer: {elapsed_str}")
# Reset timer data to zero
task.session_time = 0.0
task.actual_hours = 0.0
task.timer_start_time = None
task.timer_running = False
# Start new timer
task.start_timer()
task_manager.save_tasks()
print(f"\nTimer restarted for '{task.title}'")
print("Previous time reset to zero")
print(f"New timer started at {datetime.now().strftime('%H:%M:%S')}")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def view_running_timers(task_manager: TaskManager) -> None:
"""View all currently running timers."""
running_timers = task_manager.get_running_timers()
print("\n" + "="*40)
print("RUNNING TIMERS")
print("="*40)
if running_timers:
print(f"Found {len(running_timers)} running timer(s):")
for task in running_timers:
current_time = task.get_current_session_time()
total_time = task.get_total_time()
current_time_str = task.format_time(current_time)
total_time_str = task.format_time(total_time)
print(f"\n{task}")
print(f" Current Session: {current_time_str}")
print(f" Total Time: {total_time_str}")
else:
print("No timers are currently running.")
def set_hourly_rate(task_manager: TaskManager) -> None:
"""Set hourly rate for a task."""
if not task_manager.tasks:
print("\nNo tasks found.")
return
print("\n" + "="*40)
print("SET HOURLY RATE")
print("="*40)
print("Available tasks:")
for i, task in enumerate(task_manager.tasks, 1):
rate_info = f" (Rate: ${task.hourly_rate:.2f}/h)" if task.hourly_rate > 0 else " (No rate set)"
print(f"{i}. [{task.id}] {task.title}{rate_info}")
try:
task_index = int(input("\nEnter task number: ")) - 1
if 0 <= task_index < len(task_manager.tasks):
task = task_manager.tasks[task_index]
print(f"\nSetting hourly rate for: {task.title}")
print(f"Current rate: ${task.hourly_rate:.2f}/hour")
try:
new_rate = float(input("Enter new hourly rate ($0.00): "))
if new_rate >= 0:
task.hourly_rate = new_rate
task_manager.save_tasks()
if new_rate > 0:
current_value = task.get_current_value()
estimated_value = task.get_estimated_value()
print(f"\nHourly rate set to ${new_rate:.2f}/hour")
print(f"Current value: ${current_value:.2f}")
print(f"Estimated value: ${estimated_value:.2f}")
else:
print("Hourly rate cleared (set to $0.00)")
else:
print("Invalid rate. Rate must be 0 or positive.")
except ValueError:
print("Invalid rate format. Please enter a number.")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")
def live_timer_display(task_manager: TaskManager) -> None:
"""Display real-time timer updates for running tasks with interactive controls."""
print("\n" + "="*60)
print("LIVE TIMER DISPLAY")
print("="*60)
print("Choose display mode:")
print("1. Live Display (real-time updates)")
print("2. Interactive Menu")
print("3. Return to Main Menu")
print("="*60)
try:
choice = input("\nEnter your choice (1-3): ").strip()
if choice == '1':
live_display_mode(task_manager)
elif choice == '2':
interactive_menu_mode(task_manager)
elif choice == '3':
print("\nReturning to main menu...")
return
else:
print("Invalid choice. Returning to main menu...")
except KeyboardInterrupt:
print("\n\nReturning to main menu...")
time.sleep(1)
def live_display_mode(task_manager: TaskManager) -> None:
"""Pure live display mode with real-time updates."""
print("\n" + "="*60)
print("LIVE TIMER DISPLAY - LIVE MODE")
print("="*60)
print("Press Ctrl+C to return to main menu")
print("="*60)
try:
while True:
# Clear screen (works on most terminals)
os.system('clear' if os.name == 'posix' else 'cls')
print("="*60)
print("LIVE TIMER DISPLAY - LIVE MODE")
print("="*60)
print(f"Current Time: {datetime.now().strftime('%H:%M:%S')}")
print("Press Ctrl+C to return to main menu")
print("="*60)
# Check for running timers
running_timers = task_manager.get_running_timers()
if running_timers:
print(f"\nRUNNING TIMERS ({len(running_timers)} active):")
print("-" * 40)
for i, task in enumerate(running_timers, 1):
current_time = task.get_current_session_time()
total_time = task.get_total_time()
current_time_str = task.format_time(current_time)
total_time_str = task.format_time(total_time)