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