tasksmanage.py (6169B)
1 import json as js 2 import os 3 from enum import Enum 4 from datetime import datetime 5 6 import taskprinter as tp 7 from config import Config 8 9 10 class TaskStatus(Enum): 11 ACTIVE = "active" 12 COMPLETED = "completed" 13 EXPIRED = "expired" 14 DELETED = "deleted" 15 16 17 class Task: 18 def __init__(self, name="Default Task", description=None, expiration_date=None): 19 self.name = name 20 self.description = description 21 self.creation_date = datetime.now() 22 self.expiration_date = expiration_date 23 self.status = TaskStatus.ACTIVE 24 25 def to_dict(self) -> dict: 26 """Class -> Dictionary; For future save into .json""" 27 return { 28 "name": self.name, 29 "description": self.description, 30 "status": self.status.value, 31 "creation_date": self.creation_date.isoformat(), 32 "expiration_date": self.expiration_date.isoformat() 33 if self.expiration_date 34 else None, 35 } 36 37 def db_append(self): 38 """Append task to DB""" 39 tasks = [] 40 tasks = Task.db_load() 41 tasks.append(self) 42 Task.db_dump(tasks) 43 44 @classmethod 45 def mark_done(cls, task_id): 46 """Set task.status = COMPLETED""" 47 tasks = cls.db_load() 48 49 for task in tasks: 50 if str(task.creation_date) == task_id: 51 if task.status != TaskStatus.DELETED: 52 task.status = TaskStatus.COMPLETED 53 cls.db_dump(tasks) 54 return 55 else: 56 raise ValueError("!> You can't complete deleted task") 57 58 print("!> Incorrect task ID") 59 60 @classmethod 61 def mark_deleted(cls, task_id): 62 """task.status = DELETED""" 63 tasks = cls.db_load() 64 65 for task in tasks: 66 if str(task.creation_date) == task_id: 67 task.status = TaskStatus.DELETED 68 cls.db_dump(tasks) 69 return 70 71 print("!> Incorrect task ID") 72 73 @classmethod 74 def update_expiration_statuses(cls): 75 """Load from .json -> Update exp. statuses -> Save to .json""" 76 tasks = [] 77 tasks_new = [] 78 79 tasks = cls.db_load() 80 81 for task in tasks: 82 if ( 83 task.expiration_date 84 and task.status == TaskStatus.ACTIVE 85 and task.expiration_date < datetime.now() 86 ): 87 task.status = TaskStatus.EXPIRED 88 89 tasks_new.append(task) 90 91 cls.db_dump(tasks_new) 92 93 @classmethod 94 def from_dict(cls, data): 95 """Convert ONE Dict -> Class""" 96 expiration_date = ( 97 datetime.fromisoformat(data["expiration_date"]) 98 if data["expiration_date"] 99 else None 100 ) 101 task = cls(data["name"], data["description"], expiration_date) 102 task.creation_date = datetime.fromisoformat(data["creation_date"]) 103 task.status = TaskStatus(data["status"]) 104 105 return task 106 107 @classmethod 108 def db_load(cls) -> list: 109 """Load tasks from .json into list (AS CLASSES)""" 110 if not os.path.exists(Config.DB_PATH): 111 print( 112 f"!> File {Config.DB_PATH} doesn't exist. Use -f flag to create DB or move existing." 113 ) 114 exit(1) 115 116 try: 117 with open(Config.DB_PATH, "r", encoding="utf-8") as f: 118 tasks_data = js.load(f) 119 if not isinstance(tasks_data, list): 120 tasks_data = [tasks_data] 121 return [cls.from_dict(task_data) for task_data in tasks_data] 122 except (js.JSONDecodeError, IOError) as e: 123 print(f"!> Can't read {Config.DB_PATH}: {e}") 124 exit(1) 125 126 @classmethod 127 def db_dump(cls, data): 128 """Save tasks from list -> .json""" 129 data_dict = [] 130 131 for task in data: 132 data_dict.append(cls.to_dict(task)) 133 134 if not os.path.exists(Config.DB_PATH): 135 print(f"!> File {Config.DB_PATH} doesn't exist. Check --help menu.") 136 exit(1) 137 138 try: 139 with open(Config.DB_PATH, "w", encoding="utf-8") as f: 140 js.dump(data_dict, f, ensure_ascii=False, indent=4) 141 except IOError as e: 142 print(f"!> Can't write to the file {Config.DB_PATH}: {e}") 143 exit(1) 144 145 @classmethod 146 def print_active(cls): 147 """Print only ACTIVE to stdout""" 148 cls.update_expiration_statuses() 149 tasks = cls.db_load() 150 if not cls.check_for_emptiness(tasks): 151 tp.TaskPrinter.print_active(tasks) 152 153 @classmethod 154 def print_id(cls): 155 """Print only NOT DELETED with ID column""" 156 cls.update_expiration_statuses() 157 tasks = cls.db_load() 158 if not cls.check_for_emptiness(tasks): 159 tp.TaskPrinter.print_id(tasks) 160 161 @classmethod 162 def print_id_all(cls): 163 """Print ALL TASKS with ID column""" 164 cls.update_expiration_statuses() 165 tasks = cls.db_load() 166 if not cls.check_for_emptiness(tasks): 167 tp.TaskPrinter.print_id_all(tasks) 168 169 @classmethod 170 def print_tasks(cls): 171 """Print only NOT DELETED from .json""" 172 cls.update_expiration_statuses() 173 tasks = cls.db_load() 174 if not cls.check_for_emptiness(tasks): 175 tp.TaskPrinter.print_tasks(tasks) 176 177 @classmethod 178 def print_tasks_all(cls): 179 """Prints ALL TASKS from .json""" 180 cls.update_expiration_statuses() 181 tasks = cls.db_load() 182 if not cls.check_for_emptiness(tasks): 183 tp.TaskPrinter.print_tasks_all(tasks) 184 185 @classmethod 186 def create_db(cls): 187 """Creates DB file (if doesn't exist)""" 188 with open(Config.DB_PATH, "w"): 189 task = [] 190 task.append(Task()) 191 cls.db_dump(task) 192 193 if os.path.exists(Config.DB_PATH): 194 print("=> DB succesfuly created") 195 else: 196 print("!> Can't create DB") 197 198 @staticmethod 199 def check_for_emptiness(tasks) -> bool: 200 """Is .json empty?""" 201 if not tasks: 202 print("!> You don't have any tasks") 203 return True 204 return False