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