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