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