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