home · contact · privacy
Refactor from_table_row methods of core DB models.
[plomtask] / plomtask / todos.py
1 """Actionables."""
2 from __future__ import annotations
3 from plomtask.db import DatabaseConnection, BaseModel
4 from plomtask.processes import Process
5 from plomtask.conditions import Condition
6 from plomtask.exceptions import (NotFoundException, BadFormatException,
7                                  HandledException)
8
9
10 class Todo(BaseModel):
11     """Individual actionable."""
12
13     # pylint: disable=too-many-instance-attributes
14
15     table_name = 'todos'
16     to_save = ['process_id', 'is_done', 'date']
17
18     def __init__(self, id_: int | None, process: Process,
19                  is_done: bool, date: str) -> None:
20         self.set_int_id(id_)
21         self.process = process
22         self._is_done = is_done
23         self.date = date
24         self.children: list[Todo] = []
25         self.parents: list[Todo] = []
26         self.conditions: list[Condition] = []
27         self.fulfills: list[Condition] = []
28         self.undoes: list[Condition] = []
29         if not self.id_:
30             self.conditions = process.conditions[:]
31             self.fulfills = process.fulfills[:]
32             self.undoes = process.undoes[:]
33
34     @classmethod
35     def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
36         """Get Todo of .id_=id_ and children (from DB cache if possible)."""
37         if id_ in db_conn.cached_todos.keys():
38             todo = db_conn.cached_todos[id_]
39         else:
40             todo = None
41             for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
42                                     (id_,)):
43                 row = list(row)
44                 if row[1] == 0:
45                     raise NotFoundException('calling Todo of '
46                                             'unsaved Process')
47                 row[1] = Process.by_id(db_conn, row[1])
48                 todo = cls.from_table_row(db_conn, row)
49                 break
50             if todo is None:
51                 raise NotFoundException(f'Todo of ID not found: {id_}')
52             for row in db_conn.exec('SELECT child FROM todo_children '
53                                     'WHERE parent = ?', (id_,)):
54                 todo.children += [cls.by_id(db_conn, row[0])]
55             for row in db_conn.exec('SELECT parent FROM todo_children '
56                                     'WHERE child = ?', (id_,)):
57                 todo.parents += [cls.by_id(db_conn, row[0])]
58             for row in db_conn.exec('SELECT condition FROM todo_conditions '
59                                     'WHERE todo = ?', (id_,)):
60                 todo.conditions += [Condition.by_id(db_conn, row[0])]
61             for row in db_conn.exec('SELECT condition FROM todo_fulfills '
62                                     'WHERE todo = ?', (id_,)):
63                 todo.fulfills += [Condition.by_id(db_conn, row[0])]
64             for row in db_conn.exec('SELECT condition FROM todo_undoes '
65                                     'WHERE todo = ?', (id_,)):
66                 todo.undoes += [Condition.by_id(db_conn, row[0])]
67         assert isinstance(todo, Todo)
68         return todo
69
70     @classmethod
71     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
72         """Collect all Todos for Day of date."""
73         todos = []
74         for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
75             todos += [cls.by_id(db_conn, row[0])]
76         return todos
77
78     @classmethod
79     def enablers_for_at(cls, db_conn: DatabaseConnection, condition: Condition,
80                         date: str) -> list[Todo]:
81         """Collect all Todos of day that enable condition."""
82         enablers = []
83         for row in db_conn.exec('SELECT todo FROM todo_fulfills '
84                                 'WHERE condition = ?', (condition.id_,)):
85             todo = cls.by_id(db_conn, row[0])
86             if todo.date == date:
87                 enablers += [todo]
88         return enablers
89
90     @classmethod
91     def disablers_for_at(cls, db_conn: DatabaseConnection,
92                          condition: Condition, date: str) -> list[Todo]:
93         """Collect all Todos of day that disable condition."""
94         disablers = []
95         for row in db_conn.exec('SELECT todo FROM todo_undoes '
96                                 'WHERE condition = ?', (condition.id_,)):
97             todo = cls.by_id(db_conn, row[0])
98             if todo.date == date:
99                 disablers += [todo]
100         return disablers
101
102     @property
103     def is_doable(self) -> bool:
104         """Decide whether .is_done settable based on children, Conditions."""
105         for child in self.children:
106             if not child.is_done:
107                 return False
108         for condition in self.conditions:
109             if not condition.is_active:
110                 return False
111         return True
112
113     @property
114     def process_id(self) -> int | str | None:
115         """Return ID of tasked Process."""
116         return self.process.id_
117
118     @property
119     def is_done(self) -> bool:
120         """Wrapper around self._is_done so we can control its setter."""
121         return self._is_done
122
123     @is_done.setter
124     def is_done(self, value: bool) -> None:
125         if value != self.is_done and not self.is_doable:
126             raise BadFormatException('cannot change doneness of undoable Todo')
127         if self._is_done != value:
128             self._is_done = value
129             if value is True:
130                 for condition in self.fulfills:
131                     condition.is_active = True
132                 for condition in self.undoes:
133                     condition.is_active = False
134
135     def set_undoes(self, db_conn: DatabaseConnection, ids: list[int]) -> None:
136         """Set self.undoes to Conditions identified by ids."""
137         self.set_conditions(db_conn, ids, 'undoes')
138
139     def set_fulfills(self, db_conn: DatabaseConnection,
140                      ids: list[int]) -> None:
141         """Set self.fulfills to Conditions identified by ids."""
142         self.set_conditions(db_conn, ids, 'fulfills')
143
144     def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
145                        target: str = 'conditions') -> None:
146         """Set self.[target] to Conditions identified by ids."""
147         target_list = getattr(self, target)
148         while len(target_list) > 0:
149             target_list.pop()
150         for id_ in ids:
151             target_list += [Condition.by_id(db_conn, id_)]
152
153     def add_child(self, child: Todo) -> None:
154         """Add child to self.children, guard against recursion"""
155         def walk_steps(node: Todo) -> None:
156             if node.id_ == self.id_:
157                 raise BadFormatException('bad child choice causes recursion')
158             for child in node.children:
159                 walk_steps(child)
160         if self.id_ is None:
161             raise HandledException('Can only add children to saved Todos.')
162         if child.id_ is None:
163             raise HandledException('Can only add saved children to Todos.')
164         if child in self.children:
165             raise BadFormatException('cannot adopt same child twice')
166         walk_steps(child)
167         self.children += [child]
168         child.parents += [self]
169
170     def save(self, db_conn: DatabaseConnection) -> None:
171         """Write self and children to DB and its cache."""
172         if self.process.id_ is None:
173             raise NotFoundException('Process of Todo without ID (not saved?)')
174         self.save_core(db_conn)
175         assert isinstance(self.id_, int)
176         db_conn.cached_todos[self.id_] = self
177         db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
178                      (self.id_,))
179         for child in self.children:
180             db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
181                          (self.id_, child.id_))
182         db_conn.exec('DELETE FROM todo_fulfills WHERE todo = ?', (self.id_,))
183         for condition in self.fulfills:
184             if condition.id_ is None:
185                 raise NotFoundException('Fulfilled Condition of Todo '
186                                         'without ID (not saved?)')
187             db_conn.exec('INSERT INTO todo_fulfills VALUES (?, ?)',
188                          (self.id_, condition.id_))
189         db_conn.exec('DELETE FROM todo_undoes WHERE todo = ?', (self.id_,))
190         for condition in self.undoes:
191             if condition.id_ is None:
192                 raise NotFoundException('Undone Condition of Todo '
193                                         'without ID (not saved?)')
194             db_conn.exec('INSERT INTO todo_undoes VALUES (?, ?)',
195                          (self.id_, condition.id_))
196         db_conn.exec('DELETE FROM todo_conditions WHERE todo = ?', (self.id_,))
197         for condition in self.conditions:
198             if condition.id_ is None:
199                 raise NotFoundException('Condition of Todo '
200                                         'without ID (not saved?)')
201             db_conn.exec('INSERT INTO todo_conditions VALUES (?, ?)',
202                          (self.id_, condition.id_))