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