home · contact · privacy
Re-factor Day.todos code.
[plomtask] / plomtask / todos.py
1 """Actionables."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Any
5 from sqlite3 import Row
6 from plomtask.db import DatabaseConnection, BaseModel
7 from plomtask.processes import Process, ProcessStepsNode
8 from plomtask.versioned_attributes import VersionedAttribute
9 from plomtask.conditions import Condition, ConditionsRelations
10 from plomtask.exceptions import (NotFoundException, BadFormatException,
11                                  HandledException)
12 from plomtask.dating import valid_date
13
14
15 @dataclass
16 class TodoNode:
17     """Collects what's useful to know for Todo/Condition tree display."""
18     todo: Todo
19     seen: bool
20     children: list[TodoNode]
21
22
23 class Todo(BaseModel[int], ConditionsRelations):
24     """Individual actionable."""
25     # pylint: disable=too-many-instance-attributes
26     # pylint: disable=too-many-public-methods
27     table_name = 'todos'
28     to_save = ['process_id', 'is_done', 'date', 'comment', 'effort',
29                'calendarize']
30     to_save_relations = [('todo_conditions', 'todo', 'conditions', 0),
31                          ('todo_blockers', 'todo', 'blockers', 0),
32                          ('todo_enables', 'todo', 'enables', 0),
33                          ('todo_disables', 'todo', 'disables', 0),
34                          ('todo_children', 'parent', 'children', 0),
35                          ('todo_children', 'child', 'parents', 1)]
36     to_search = ['comment']
37
38     # pylint: disable=too-many-arguments
39     def __init__(self, id_: int | None,
40                  process: Process,
41                  is_done: bool,
42                  date: str, comment: str = '',
43                  effort: None | float = None,
44                  calendarize: bool = False) -> None:
45         BaseModel.__init__(self, id_)
46         ConditionsRelations.__init__(self)
47         if process.id_ is None:
48             raise NotFoundException('Process of Todo without ID (not saved?)')
49         self.process = process
50         self._is_done = is_done
51         self.date = valid_date(date)
52         self.comment = comment
53         self.effort = effort
54         self.children: list[Todo] = []
55         self.parents: list[Todo] = []
56         self.calendarize = calendarize
57         if not self.id_:
58             self.calendarize = self.process.calendarize
59             self.conditions = self.process.conditions[:]
60             self.blockers = self.process.blockers[:]
61             self.enables = self.process.enables[:]
62             self.disables = self.process.disables[:]
63
64     @classmethod
65     def by_date_range(cls, db_conn: DatabaseConnection,
66                       date_range: tuple[str, str] = ('', '')) -> list[Todo]:
67         """Collect Todos of Days within date_range."""
68         todos, _, _ = cls.by_date_range_with_limits(db_conn, date_range)
69         return todos
70
71     @classmethod
72     def create_with_children(cls, db_conn: DatabaseConnection,
73                              process_id: int, date: str) -> Todo:
74         """Create Todo of process for date, ensure children."""
75
76         def key_order_func(n: ProcessStepsNode) -> int:
77             assert isinstance(n.process.id_, int)
78             return n.process.id_
79
80         def walk_steps(parent: Todo, step_node: ProcessStepsNode) -> Todo:
81             adoptables = [t for t in cls.by_date(db_conn, date)
82                           if (t not in parent.children)
83                           and (t != parent)
84                           and step_node.process == t.process]
85             satisfier = None
86             for adoptable in adoptables:
87                 satisfier = adoptable
88                 break
89             if not satisfier:
90                 satisfier = cls(None, step_node.process, False, date)
91                 satisfier.save(db_conn)
92             sub_step_nodes = list(step_node.steps.values())
93             sub_step_nodes.sort(key=key_order_func)
94             for sub_node in sub_step_nodes:
95                 if sub_node.is_suppressed:
96                     continue
97                 n_slots = len([n for n in sub_step_nodes
98                                if n.process == sub_node.process])
99                 filled_slots = len([t for t in satisfier.children
100                                     if t.process == sub_node.process])
101                 # if we did not newly create satisfier, it may already fill
102                 # some step dependencies, so only fill what remains open
103                 if n_slots - filled_slots > 0:
104                     satisfier.add_child(walk_steps(satisfier, sub_node))
105             satisfier.save(db_conn)
106             return satisfier
107
108         process = Process.by_id(db_conn, process_id)
109         todo = cls(None, process, False, date)
110         todo.save(db_conn)
111         steps_tree = process.get_steps(db_conn)
112         for step_node in steps_tree.values():
113             if step_node.is_suppressed:
114                 continue
115             todo.add_child(walk_steps(todo, step_node))
116         todo.save(db_conn)
117         return todo
118
119     @classmethod
120     def from_table_row(cls, db_conn: DatabaseConnection,
121                        row: Row | list[Any]) -> Todo:
122         """Make from DB row, with dependencies."""
123         if row[1] == 0:
124             raise NotFoundException('calling Todo of '
125                                     'unsaved Process')
126         row_as_list = list(row)
127         row_as_list[1] = Process.by_id(db_conn, row[1])
128         todo = super().from_table_row(db_conn, row_as_list)
129         assert isinstance(todo.id_, int)
130         for t_id in db_conn.column_where('todo_children', 'child',
131                                          'parent', todo.id_):
132             # pylint: disable=no-member
133             todo.children += [cls.by_id(db_conn, t_id)]
134         for t_id in db_conn.column_where('todo_children', 'parent',
135                                          'child', todo.id_):
136             # pylint: disable=no-member
137             todo.parents += [cls.by_id(db_conn, t_id)]
138         for name in ('conditions', 'blockers', 'enables', 'disables'):
139             table = f'todo_{name}'
140             assert isinstance(todo.id_, int)
141             for cond_id in db_conn.column_where(table, 'condition',
142                                                 'todo', todo.id_):
143                 target = getattr(todo, name)
144                 target += [Condition.by_id(db_conn, cond_id)]
145         return todo
146
147     @classmethod
148     def by_process_id(cls, db_conn: DatabaseConnection,
149                       process_id: int | None) -> list[Todo]:
150         """Collect all Todos of Process of process_id."""
151         return [t for t in cls.all(db_conn) if t.process.id_ == process_id]
152
153     @classmethod
154     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
155         """Collect all Todos for Day of date."""
156         return cls.by_date_range(db_conn, (date, date))
157
158     @property
159     def is_doable(self) -> bool:
160         """Decide whether .is_done settable based on children, Conditions."""
161         for child in self.children:
162             if not child.is_done:
163                 return False
164         for condition in self.conditions:
165             if not condition.is_active:
166                 return False
167         for condition in self.blockers:
168             if condition.is_active:
169                 return False
170         return True
171
172     @property
173     def is_deletable(self) -> bool:
174         """Decide whether self be deletable (not if preserve-worthy values)."""
175         if self.comment:
176             return False
177         if self.effort and self.effort >= 0:
178             return False
179         return True
180
181     @property
182     def performed_effort(self) -> float:
183         """Return performed effort, i.e. self.effort or default if done.."""
184         if self.effort is not None:
185             return self.effort
186         if self.is_done:
187             return self.effort_then
188         return 0
189
190     @property
191     def process_id(self) -> int | str | None:
192         """Needed for super().save to save Processes as attributes."""
193         return self.process.id_
194
195     @property
196     def is_done(self) -> bool:
197         """Wrapper around self._is_done so we can control its setter."""
198         return self._is_done
199
200     @is_done.setter
201     def is_done(self, value: bool) -> None:
202         if value != self.is_done and not self.is_doable:
203             raise BadFormatException('cannot change doneness of undoable Todo')
204         if self._is_done != value:
205             self._is_done = value
206             if value is True:
207                 for condition in self.enables:
208                     condition.is_active = True
209                 for condition in self.disables:
210                     condition.is_active = False
211
212     @property
213     def title(self) -> VersionedAttribute:
214         """Shortcut to .process.title."""
215         return self.process.title
216
217     @property
218     def title_then(self) -> str:
219         """Shortcut to .process.title.at(self.date)"""
220         title_then = self.process.title.at(self.date)
221         assert isinstance(title_then, str)
222         return title_then
223
224     @property
225     def effort_then(self) -> float:
226         """Shortcut to .process.effort.at(self.date)"""
227         effort_then = self.process.effort.at(self.date)
228         assert isinstance(effort_then, float)
229         return effort_then
230
231     @property
232     def has_doneness_in_path(self) -> bool:
233         """Check whether self is done or has any children that are."""
234         if self.is_done:
235             return True
236         for child in self.children:
237             if child.is_done:
238                 return True
239             if child.has_doneness_in_path:
240                 return True
241         return False
242
243     def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
244         """Return tree of depended-on Todos."""
245
246         def make_node(todo: Todo) -> TodoNode:
247             children = []
248             seen = todo.id_ in seen_todos
249             assert isinstance(todo.id_, int)
250             seen_todos.add(todo.id_)
251             for child in todo.children:
252                 children += [make_node(child)]
253             return TodoNode(todo, seen, children)
254
255         return make_node(self)
256
257     @property
258     def tree_effort(self) -> float:
259         """Return sum of performed efforts of self and all descendants."""
260
261         def walk_tree(node: Todo) -> float:
262             local_effort = 0.0
263             for child in node.children:
264                 local_effort += walk_tree(child)
265             return node.performed_effort + local_effort
266
267         return walk_tree(self)
268
269     def add_child(self, child: Todo) -> None:
270         """Add child to self.children, avoid recursion, update parenthoods."""
271
272         def walk_steps(node: Todo) -> None:
273             if node.id_ == self.id_:
274                 raise BadFormatException('bad child choice causes recursion')
275             for child in node.children:
276                 walk_steps(child)
277
278         if self.id_ is None:
279             raise HandledException('Can only add children to saved Todos.')
280         if child.id_ is None:
281             raise HandledException('Can only add saved children to Todos.')
282         if child in self.children:
283             raise BadFormatException('cannot adopt same child twice')
284         walk_steps(child)
285         self.children += [child]
286         child.parents += [self]
287
288     def remove_child(self, child: Todo) -> None:
289         """Remove child from self.children, update counter relations."""
290         if child not in self.children:
291             raise HandledException('Cannot remove un-parented child.')
292         self.children.remove(child)
293         child.parents.remove(self)
294
295     def save(self, db_conn: DatabaseConnection) -> None:
296         """On save calls, also check if auto-deletion by effort < 0."""
297         if self.effort and self.effort < 0 and self.is_deletable:
298             self.remove(db_conn)
299             return
300         super().save(db_conn)
301
302     def remove(self, db_conn: DatabaseConnection) -> None:
303         """Remove from DB, including relations."""
304         if not self.is_deletable:
305             raise HandledException('Cannot remove non-deletable Todo.')
306         children_to_remove = self.children[:]
307         parents_to_remove = self.parents[:]
308         for child in children_to_remove:
309             self.remove_child(child)
310         for parent in parents_to_remove:
311             parent.remove_child(self)
312         super().remove(db_conn)