home · contact · privacy
Nest Todo creation by adopting and making children as needed.
[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
8 from plomtask.versioned_attributes import VersionedAttribute
9 from plomtask.conditions import Condition, ConditionsRelations
10 from plomtask.exceptions import (NotFoundException, BadFormatException,
11                                  HandledException)
12
13
14 @dataclass
15 class TodoNode:
16     """Collects what's useful to know for Todo/Condition tree display."""
17     todo: Todo
18     seen: bool
19     children: list[TodoNode]
20
21
22 class Todo(BaseModel[int], ConditionsRelations):
23     """Individual actionable."""
24     # pylint: disable=too-many-instance-attributes
25     table_name = 'todos'
26     to_save = ['process_id', 'is_done', 'date', 'comment', 'effort',
27                'calendarize']
28     to_save_relations = [('todo_conditions', 'todo', 'conditions'),
29                          ('todo_blockers', 'todo', 'blockers'),
30                          ('todo_enables', 'todo', 'enables'),
31                          ('todo_disables', 'todo', 'disables'),
32                          ('todo_children', 'parent', 'children'),
33                          ('todo_children', 'child', 'parents')]
34
35     # pylint: disable=too-many-arguments
36     def __init__(self, id_: int | None,
37                  process: Process,
38                  is_done: bool,
39                  date: str, comment: str = '',
40                  effort: None | float = None,
41                  calendarize: bool = False) -> None:
42         BaseModel.__init__(self, id_)
43         ConditionsRelations.__init__(self)
44         if process.id_ is None:
45             raise NotFoundException('Process of Todo without ID (not saved?)')
46         self.process = process
47         self._is_done = is_done
48         self.date = date
49         self.comment = comment
50         self.effort = effort
51         self.children: list[Todo] = []
52         self.parents: list[Todo] = []
53         self.calendarize = calendarize
54         if not self.id_:
55             self.calendarize = self.process.calendarize
56             self.conditions = self.process.conditions[:]
57             self.blockers = self.process.blockers[:]
58             self.enables = self.process.enables[:]
59             self.disables = self.process.disables[:]
60
61     @classmethod
62     def create_with_children(cls, db_conn: DatabaseConnection, date: str,
63                              process_ids: list[int]) -> list[Todo]:
64         """Create Todos of process_ids for date, ensure children."""
65         new_todos = []
66         for process_id in process_ids:
67             process = Process.by_id(db_conn, process_id)
68             todo = Todo(None, process, False, date)
69             todo.save(db_conn)
70             new_todos += [todo]
71         nothing_to_adopt = False
72         while not nothing_to_adopt:
73             nothing_to_adopt = True
74             existing_todos = Todo.by_date(db_conn, date)
75             for todo in new_todos:
76                 if todo.adopt_from(existing_todos):
77                     nothing_to_adopt = False
78                 todo.make_missing_children(db_conn)
79                 todo.save(db_conn)
80         return new_todos
81
82     @classmethod
83     def from_table_row(cls, db_conn: DatabaseConnection,
84                        row: Row | list[Any]) -> Todo:
85         """Make from DB row, with dependencies."""
86         if row[1] == 0:
87             raise NotFoundException('calling Todo of '
88                                     'unsaved Process')
89         row_as_list = list(row)
90         row_as_list[1] = Process.by_id(db_conn, row[1])
91         todo = super().from_table_row(db_conn, row_as_list)
92         assert isinstance(todo.id_, int)
93         for t_id in db_conn.column_where('todo_children', 'child',
94                                          'parent', todo.id_):
95             # pylint: disable=no-member
96             todo.children += [cls.by_id(db_conn, t_id)]
97         for t_id in db_conn.column_where('todo_children', 'parent',
98                                          'child', todo.id_):
99             # pylint: disable=no-member
100             todo.parents += [cls.by_id(db_conn, t_id)]
101         for name in ('conditions', 'blockers', 'enables', 'disables'):
102             table = f'todo_{name}'
103             assert isinstance(todo.id_, int)
104             for cond_id in db_conn.column_where(table, 'condition',
105                                                 'todo', todo.id_):
106                 target = getattr(todo, name)
107                 target += [Condition.by_id(db_conn, cond_id)]
108         return todo
109
110     @classmethod
111     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
112         """Collect all Todos for Day of date."""
113         todos = []
114         for id_ in db_conn.column_where('todos', 'id', 'day', date):
115             todos += [cls.by_id(db_conn, id_)]
116         return todos
117
118     @property
119     def is_doable(self) -> bool:
120         """Decide whether .is_done settable based on children, Conditions."""
121         for child in self.children:
122             if not child.is_done:
123                 return False
124         for condition in self.conditions:
125             if not condition.is_active:
126                 return False
127         for condition in self.blockers:
128             if condition.is_active:
129                 return False
130         return True
131
132     @property
133     def is_deletable(self) -> bool:
134         """Decide whether self be deletable (not if preserve-worthy values)."""
135         if self.comment:
136             return False
137         if self.effort and self.effort >= 0:
138             return False
139         return True
140
141     @property
142     def process_id(self) -> int | str | None:
143         """Needed for super().save to save Processes as attributes."""
144         return self.process.id_
145
146     @property
147     def unsatisfied_dependencies(self) -> list[int]:
148         """Return Process IDs of .process.explicit_steps not in .children."""
149         unsatisfied = [s.step_process_id for s in self.process.explicit_steps
150                        if s.parent_step_id is None]
151         for child_process_id in [c.process.id_ for c in self.children]:
152             if child_process_id in unsatisfied:
153                 unsatisfied.remove(child_process_id)
154         return unsatisfied
155
156     @property
157     def is_done(self) -> bool:
158         """Wrapper around self._is_done so we can control its setter."""
159         return self._is_done
160
161     @is_done.setter
162     def is_done(self, value: bool) -> None:
163         if value != self.is_done and not self.is_doable:
164             raise BadFormatException('cannot change doneness of undoable Todo')
165         if self._is_done != value:
166             self._is_done = value
167             if value is True:
168                 for condition in self.enables:
169                     condition.is_active = True
170                 for condition in self.disables:
171                     condition.is_active = False
172
173     @property
174     def title(self) -> VersionedAttribute:
175         """Shortcut to .process.title."""
176         return self.process.title
177
178     def adopt_from(self, todos: list[Todo]) -> bool:
179         """As far as possible, fill unsatisfied dependencies from todos."""
180         adopted = False
181         for process_id in self.unsatisfied_dependencies:
182             for todo in [t for t in todos if t.process.id_ == process_id
183                          and t not in self.children]:
184                 self.add_child(todo)
185                 adopted = True
186                 break
187         return adopted
188
189     def make_missing_children(self, db_conn: DatabaseConnection) -> None:
190         """Fill unsatisfied dependencies with new Todos."""
191         new_todos = self.__class__.create_with_children(
192                 db_conn, self.date, self.unsatisfied_dependencies)
193         for todo in new_todos:
194             self.add_child(todo)
195
196     def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
197         """Return tree of depended-on Todos."""
198
199         def make_node(todo: Todo) -> TodoNode:
200             children = []
201             seen = todo.id_ in seen_todos
202             assert isinstance(todo.id_, int)
203             seen_todos.add(todo.id_)
204             for child in todo.children:
205                 children += [make_node(child)]
206             return TodoNode(todo, seen, children)
207
208         return make_node(self)
209
210     def add_child(self, child: Todo) -> None:
211         """Add child to self.children, avoid recursion, update parenthoods."""
212
213         def walk_steps(node: Todo) -> None:
214             if node.id_ == self.id_:
215                 raise BadFormatException('bad child choice causes recursion')
216             for child in node.children:
217                 walk_steps(child)
218
219         if self.id_ is None:
220             raise HandledException('Can only add children to saved Todos.')
221         if child.id_ is None:
222             raise HandledException('Can only add saved children to Todos.')
223         if child in self.children:
224             raise BadFormatException('cannot adopt same child twice')
225         walk_steps(child)
226         self.children += [child]
227         child.parents += [self]
228
229     def remove_child(self, child: Todo) -> None:
230         """Remove child from self.children, update counter relations."""
231         if child not in self.children:
232             raise HandledException('Cannot remove un-parented child.')
233         self.children.remove(child)
234         child.parents.remove(self)
235
236     def save(self, db_conn: DatabaseConnection) -> None:
237         """On save calls, also check if auto-deletion by effort < 0."""
238         if self.effort and self.effort < 0 and self.is_deletable:
239             self.remove(db_conn)
240             return
241         super().save(db_conn)
242
243     def remove(self, db_conn: DatabaseConnection) -> None:
244         """Remove from DB, including relations."""
245         if not self.is_deletable:
246             raise HandledException('Cannot remove non-deletable Todo.')
247         children_to_remove = self.children[:]
248         parents_to_remove = self.parents[:]
249         for child in children_to_remove:
250             self.remove_child(child)
251         for parent in parents_to_remove:
252             parent.remove_child(self)
253         super().remove(db_conn)