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