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']
27 to_save_relations = [('todo_conditions', 'todo', 'conditions'),
28 ('todo_enables', 'todo', 'enables'),
29 ('todo_disables', 'todo', 'disables'),
30 ('todo_children', 'parent', 'children'),
31 ('todo_children', 'child', 'parents')]
33 # pylint: disable=too-many-arguments
34 def __init__(self, id_: int | None, process: Process,
35 is_done: bool, date: str, comment: str = '',
36 effort: None | float = None) -> None:
38 if process.id_ is None:
39 raise NotFoundException('Process of Todo without ID (not saved?)')
40 self.process = process
41 self._is_done = is_done
43 self.comment = comment
45 self.children: list[Todo] = []
46 self.parents: list[Todo] = []
47 self.conditions: list[Condition] = []
48 self.enables: list[Condition] = []
49 self.disables: list[Condition] = []
51 self.conditions = self.process.conditions[:]
52 self.enables = self.process.enables[:]
53 self.disables = self.process.disables[:]
56 def from_table_row(cls, db_conn: DatabaseConnection,
57 row: Row | list[Any]) -> Todo:
58 """Make from DB row, with dependencies."""
60 raise NotFoundException('calling Todo of '
62 row_as_list = list(row)
63 row_as_list[1] = Process.by_id(db_conn, row[1])
64 todo = super().from_table_row(db_conn, row_as_list)
65 assert isinstance(todo.id_, int)
66 for t_id in db_conn.column_where('todo_children', 'child',
68 # pylint: disable=no-member
69 todo.children += [cls.by_id(db_conn, t_id)]
70 for t_id in db_conn.column_where('todo_children', 'parent',
72 # pylint: disable=no-member
73 todo.parents += [cls.by_id(db_conn, t_id)]
74 for name in ('conditions', 'enables', 'disables'):
75 table = f'todo_{name}'
76 assert isinstance(todo.id_, int)
77 for cond_id in db_conn.column_where(table, 'condition',
79 target = getattr(todo, name)
80 target += [Condition.by_id(db_conn, cond_id)]
84 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
85 """Collect all Todos for Day of date."""
87 for id_ in db_conn.column_where('todos', 'id', 'day', date):
88 todos += [cls.by_id(db_conn, id_)]
92 def is_doable(self) -> bool:
93 """Decide whether .is_done settable based on children, Conditions."""
94 for child in self.children:
97 for condition in self.conditions:
98 if not condition.is_active:
103 def process_id(self) -> int | str | None:
104 """Needed for super().save to save Processes as attributes."""
105 return self.process.id_
108 def unsatisfied_dependencies(self) -> list[int]:
109 """Return Process IDs of .process.explicit_steps not in .children."""
110 unsatisfied = [s.step_process_id for s in self.process.explicit_steps
111 if s.parent_step_id is None]
112 for child_process_id in [c.process.id_ for c in self.children]:
113 if child_process_id in unsatisfied:
114 unsatisfied.remove(child_process_id)
118 def is_done(self) -> bool:
119 """Wrapper around self._is_done so we can control its setter."""
123 def is_done(self, value: bool) -> None:
124 if value != self.is_done and not self.is_doable:
125 raise BadFormatException('cannot change doneness of undoable Todo')
126 if self._is_done != value:
127 self._is_done = value
129 for condition in self.enables:
130 condition.is_active = True
131 for condition in self.disables:
132 condition.is_active = False
135 def title(self) -> VersionedAttribute:
136 """Shortcut to .process.title."""
137 return self.process.title
139 def adopt_from(self, todos: list[Todo]) -> bool:
140 """As far as possible, fill unsatisfied dependencies from todos."""
142 for process_id in self.unsatisfied_dependencies:
143 for todo in [t for t in todos if t.process.id_ == process_id
144 and t not in self.children]:
150 def make_missing_children(self, db_conn: DatabaseConnection) -> None:
151 """Fill unsatisfied dependencies with new Todos."""
152 for process_id in self.unsatisfied_dependencies:
153 process = Process.by_id(db_conn, process_id)
154 todo = self.__class__(None, process, False, self.date)
158 def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
159 """Return tree of depended-on Todos."""
161 def make_node(todo: Todo) -> TodoNode:
163 seen = todo.id_ in seen_todos
164 assert isinstance(todo.id_, int)
165 seen_todos.add(todo.id_)
166 for child in todo.children:
167 children += [make_node(child)]
168 return TodoNode(todo, seen, children)
170 return make_node(self)
172 def add_child(self, child: Todo) -> None:
173 """Add child to self.children, avoid recursion, update parenthoods."""
175 def walk_steps(node: Todo) -> None:
176 if node.id_ == self.id_:
177 raise BadFormatException('bad child choice causes recursion')
178 for child in node.children:
182 raise HandledException('Can only add children to saved Todos.')
183 if child.id_ is None:
184 raise HandledException('Can only add saved children to Todos.')
185 if child in self.children:
186 raise BadFormatException('cannot adopt same child twice')
188 self.children += [child]
189 child.parents += [self]
191 def remove_child(self, child: Todo) -> None:
192 """Remove child from self.children, update counter relations."""
193 if child not in self.children:
194 raise HandledException('Cannot remove un-parented child.')
195 self.children.remove(child)
196 child.parents.remove(self)
198 def remove(self, db_conn: DatabaseConnection) -> None:
199 """Remove from DB, including relations."""
200 children_to_remove = self.children[:]
201 parents_to_remove = self.parents[:]
202 for child in children_to_remove:
203 self.remove_child(child)
204 for parent in parents_to_remove:
205 parent.remove_child(self)
206 super().remove(db_conn)