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