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