2 from __future__ import annotations
3 from dataclasses import dataclass
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,
16 """Collects what's useful to know for Todo/Condition tree display."""
19 children: list[TodoNode]
22 class Todo(BaseModel[int], ConditionsRelations):
23 """Individual actionable."""
24 # pylint: disable=too-many-instance-attributes
26 to_save = ['process_id', 'is_done', 'date', 'comment', 'effort',
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')]
35 # pylint: disable=too-many-arguments
36 def __init__(self, id_: int | None,
39 date: str, comment: str = '',
40 effort: None | float = None,
41 calendarize: bool = False) -> None:
42 BaseModel.__init__(self, id_)
43 ConditionsRelations.__init__(self)
44 if process.id_ is None:
45 raise NotFoundException('Process of Todo without ID (not saved?)')
46 self.process = process
47 self._is_done = is_done
49 self.comment = comment
51 self.children: list[Todo] = []
52 self.parents: list[Todo] = []
53 self.calendarize = calendarize
55 self.calendarize = self.process.calendarize
56 self.conditions = self.process.conditions[:]
57 self.blockers = self.process.blockers[:]
58 self.enables = self.process.enables[:]
59 self.disables = self.process.disables[:]
62 def from_table_row(cls, db_conn: DatabaseConnection,
63 row: Row | list[Any]) -> Todo:
64 """Make from DB row, with dependencies."""
66 raise NotFoundException('calling Todo of '
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',
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',
78 # pylint: disable=no-member
79 todo.parents += [cls.by_id(db_conn, t_id)]
80 for name in ('conditions', 'blockers', 'enables', 'disables'):
81 table = f'todo_{name}'
82 assert isinstance(todo.id_, int)
83 for cond_id in db_conn.column_where(table, 'condition',
85 target = getattr(todo, name)
86 target += [Condition.by_id(db_conn, cond_id)]
90 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
91 """Collect all Todos for Day of date."""
93 for id_ in db_conn.column_where('todos', 'id', 'day', date):
94 todos += [cls.by_id(db_conn, id_)]
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:
103 for condition in self.conditions:
104 if not condition.is_active:
106 for condition in self.blockers:
107 if condition.is_active:
112 def is_deletable(self) -> bool:
113 """Decide whether self be deletable (not if preserve-worthy values)."""
116 if self.effort and self.effort >= 0:
121 def process_id(self) -> int | str | None:
122 """Needed for super().save to save Processes as attributes."""
123 return self.process.id_
126 def unsatisfied_dependencies(self) -> list[int]:
127 """Return Process IDs of .process.explicit_steps not in .children."""
128 unsatisfied = [s.step_process_id for s in self.process.explicit_steps
129 if s.parent_step_id is None]
130 for child_process_id in [c.process.id_ for c in self.children]:
131 if child_process_id in unsatisfied:
132 unsatisfied.remove(child_process_id)
136 def is_done(self) -> bool:
137 """Wrapper around self._is_done so we can control its setter."""
141 def is_done(self, value: bool) -> None:
142 if value != self.is_done and not self.is_doable:
143 raise BadFormatException('cannot change doneness of undoable Todo')
144 if self._is_done != value:
145 self._is_done = value
147 for condition in self.enables:
148 condition.is_active = True
149 for condition in self.disables:
150 condition.is_active = False
153 def title(self) -> VersionedAttribute:
154 """Shortcut to .process.title."""
155 return self.process.title
157 def adopt_from(self, todos: list[Todo]) -> bool:
158 """As far as possible, fill unsatisfied dependencies from todos."""
160 for process_id in self.unsatisfied_dependencies:
161 for todo in [t for t in todos if t.process.id_ == process_id
162 and t not in self.children]:
168 def make_missing_children(self, db_conn: DatabaseConnection) -> None:
169 """Fill unsatisfied dependencies with new Todos."""
170 for process_id in self.unsatisfied_dependencies:
171 process = Process.by_id(db_conn, process_id)
172 todo = self.__class__(None, process, False, self.date)
176 def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
177 """Return tree of depended-on Todos."""
179 def make_node(todo: Todo) -> TodoNode:
181 seen = todo.id_ in seen_todos
182 assert isinstance(todo.id_, int)
183 seen_todos.add(todo.id_)
184 for child in todo.children:
185 children += [make_node(child)]
186 return TodoNode(todo, seen, children)
188 return make_node(self)
190 def add_child(self, child: Todo) -> None:
191 """Add child to self.children, avoid recursion, update parenthoods."""
193 def walk_steps(node: Todo) -> None:
194 if node.id_ == self.id_:
195 raise BadFormatException('bad child choice causes recursion')
196 for child in node.children:
200 raise HandledException('Can only add children to saved Todos.')
201 if child.id_ is None:
202 raise HandledException('Can only add saved children to Todos.')
203 if child in self.children:
204 raise BadFormatException('cannot adopt same child twice')
206 self.children += [child]
207 child.parents += [self]
209 def remove_child(self, child: Todo) -> None:
210 """Remove child from self.children, update counter relations."""
211 if child not in self.children:
212 raise HandledException('Cannot remove un-parented child.')
213 self.children.remove(child)
214 child.parents.remove(self)
216 def save(self, db_conn: DatabaseConnection) -> None:
217 """On save calls, also check if auto-deletion by effort < 0."""
218 if self.effort and self.effort < 0 and self.is_deletable:
221 super().save(db_conn)
223 def remove(self, db_conn: DatabaseConnection) -> None:
224 """Remove from DB, including relations."""
225 if not self.is_deletable:
226 raise HandledException('Cannot remove non-deletable Todo.')
227 children_to_remove = self.children[:]
228 parents_to_remove = self.parents[:]
229 for child in children_to_remove:
230 self.remove_child(child)
231 for parent in parents_to_remove:
232 parent.remove_child(self)
233 super().remove(db_conn)