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,
12 from plomtask.dating import valid_date
17 """Collects what's useful to know for Todo/Condition tree display."""
20 children: list[TodoNode]
23 class Todo(BaseModel[int], ConditionsRelations):
24 """Individual actionable."""
25 # pylint: disable=too-many-instance-attributes
27 to_save = ['process_id', 'is_done', 'date', 'comment', 'effort',
29 to_save_relations = [('todo_conditions', 'todo', 'conditions'),
30 ('todo_blockers', 'todo', 'blockers'),
31 ('todo_enables', 'todo', 'enables'),
32 ('todo_disables', 'todo', 'disables'),
33 ('todo_children', 'parent', 'children'),
34 ('todo_children', 'child', 'parents')]
35 to_search = ['comment']
37 # pylint: disable=too-many-arguments
38 def __init__(self, id_: int | None,
41 date: str, comment: str = '',
42 effort: None | float = None,
43 calendarize: bool = False) -> None:
44 BaseModel.__init__(self, id_)
45 ConditionsRelations.__init__(self)
46 if process.id_ is None:
47 raise NotFoundException('Process of Todo without ID (not saved?)')
48 self.process = process
49 self._is_done = is_done
50 self.date = valid_date(date)
51 self.comment = comment
53 self.children: list[Todo] = []
54 self.parents: list[Todo] = []
55 self.calendarize = calendarize
57 self.calendarize = self.process.calendarize
58 self.conditions = self.process.conditions[:]
59 self.blockers = self.process.blockers[:]
60 self.enables = self.process.enables[:]
61 self.disables = self.process.disables[:]
64 def by_date_range(cls, db_conn: DatabaseConnection,
65 date_range: tuple[str, str] = ('', '')) -> list[Todo]:
66 """Collect Todos of Days within date_range."""
67 todos, _, _ = cls.by_date_range_with_limits(db_conn, date_range)
71 def create_with_children(cls, db_conn: DatabaseConnection, date: str,
72 process_ids: list[int]) -> list[Todo]:
73 """Create Todos of process_ids for date, ensure children."""
75 for process_id in process_ids:
76 process = Process.by_id(db_conn, process_id)
77 todo = Todo(None, process, False, date)
80 nothing_to_adopt = False
81 while not nothing_to_adopt:
82 nothing_to_adopt = True
83 existing_todos = Todo.by_date(db_conn, date)
84 for todo in new_todos:
85 if todo.adopt_from(existing_todos):
86 nothing_to_adopt = False
87 todo.make_missing_children(db_conn)
92 def from_table_row(cls, db_conn: DatabaseConnection,
93 row: Row | list[Any]) -> Todo:
94 """Make from DB row, with dependencies."""
96 raise NotFoundException('calling Todo of '
98 row_as_list = list(row)
99 row_as_list[1] = Process.by_id(db_conn, row[1])
100 todo = super().from_table_row(db_conn, row_as_list)
101 assert isinstance(todo.id_, int)
102 for t_id in db_conn.column_where('todo_children', 'child',
104 # pylint: disable=no-member
105 todo.children += [cls.by_id(db_conn, t_id)]
106 for t_id in db_conn.column_where('todo_children', 'parent',
108 # pylint: disable=no-member
109 todo.parents += [cls.by_id(db_conn, t_id)]
110 for name in ('conditions', 'blockers', 'enables', 'disables'):
111 table = f'todo_{name}'
112 assert isinstance(todo.id_, int)
113 for cond_id in db_conn.column_where(table, 'condition',
115 target = getattr(todo, name)
116 target += [Condition.by_id(db_conn, cond_id)]
120 def by_process_id(cls, db_conn: DatabaseConnection,
121 process_id: int | None) -> list[Todo]:
122 """Collect all Todos of Process of process_id."""
123 return [t for t in cls.all(db_conn) if t.process.id_ == process_id]
126 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
127 """Collect all Todos for Day of date."""
128 return cls.by_date_range(db_conn, (date, date))
131 def is_doable(self) -> bool:
132 """Decide whether .is_done settable based on children, Conditions."""
133 for child in self.children:
134 if not child.is_done:
136 for condition in self.conditions:
137 if not condition.is_active:
139 for condition in self.blockers:
140 if condition.is_active:
145 def is_deletable(self) -> bool:
146 """Decide whether self be deletable (not if preserve-worthy values)."""
149 if self.effort and self.effort >= 0:
154 def process_id(self) -> int | str | None:
155 """Needed for super().save to save Processes as attributes."""
156 return self.process.id_
159 def unsatisfied_dependencies(self) -> list[int]:
160 """Return Process IDs of .process.explicit_steps not in .children."""
161 unsatisfied = [s.step_process_id for s in self.process.explicit_steps
162 if s.parent_step_id is None]
163 for child_process_id in [c.process.id_ for c in self.children]:
164 if child_process_id in unsatisfied:
165 unsatisfied.remove(child_process_id)
169 def is_done(self) -> bool:
170 """Wrapper around self._is_done so we can control its setter."""
174 def is_done(self, value: bool) -> None:
175 if value != self.is_done and not self.is_doable:
176 raise BadFormatException('cannot change doneness of undoable Todo')
177 if self._is_done != value:
178 self._is_done = value
180 for condition in self.enables:
181 condition.is_active = True
182 for condition in self.disables:
183 condition.is_active = False
186 def title(self) -> VersionedAttribute:
187 """Shortcut to .process.title."""
188 return self.process.title
191 def title_then(self) -> str:
192 """Shortcut to .process.title.at(self.date)"""
193 title_then = self.process.title.at(self.date)
194 assert isinstance(title_then, str)
198 def effort_then(self) -> float:
199 """Shortcut to .process.effort.at(self.date)"""
200 effort_then = self.process.effort.at(self.date)
201 assert isinstance(effort_then, float)
204 def adopt_from(self, todos: list[Todo]) -> bool:
205 """As far as possible, fill unsatisfied dependencies from todos."""
207 for process_id in self.unsatisfied_dependencies:
208 for todo in [t for t in todos if t.process.id_ == process_id
209 and t not in self.children]:
215 def make_missing_children(self, db_conn: DatabaseConnection) -> None:
216 """Fill unsatisfied dependencies with new Todos."""
217 new_todos = self.__class__.create_with_children(
218 db_conn, self.date, self.unsatisfied_dependencies)
219 for todo in new_todos:
222 def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
223 """Return tree of depended-on Todos."""
225 def make_node(todo: Todo) -> TodoNode:
227 seen = todo.id_ in seen_todos
228 assert isinstance(todo.id_, int)
229 seen_todos.add(todo.id_)
230 for child in todo.children:
231 children += [make_node(child)]
232 return TodoNode(todo, seen, children)
234 return make_node(self)
236 def add_child(self, child: Todo) -> None:
237 """Add child to self.children, avoid recursion, update parenthoods."""
239 def walk_steps(node: Todo) -> None:
240 if node.id_ == self.id_:
241 raise BadFormatException('bad child choice causes recursion')
242 for child in node.children:
246 raise HandledException('Can only add children to saved Todos.')
247 if child.id_ is None:
248 raise HandledException('Can only add saved children to Todos.')
249 if child in self.children:
250 raise BadFormatException('cannot adopt same child twice')
252 self.children += [child]
253 child.parents += [self]
255 def remove_child(self, child: Todo) -> None:
256 """Remove child from self.children, update counter relations."""
257 if child not in self.children:
258 raise HandledException('Cannot remove un-parented child.')
259 self.children.remove(child)
260 child.parents.remove(self)
262 def save(self, db_conn: DatabaseConnection) -> None:
263 """On save calls, also check if auto-deletion by effort < 0."""
264 if self.effort and self.effort < 0 and self.is_deletable:
267 super().save(db_conn)
269 def remove(self, db_conn: DatabaseConnection) -> None:
270 """Remove from DB, including relations."""
271 if not self.is_deletable:
272 raise HandledException('Cannot remove non-deletable Todo.')
273 children_to_remove = self.children[:]
274 parents_to_remove = self.parents[:]
275 for child in children_to_remove:
276 self.remove_child(child)
277 for parent in parents_to_remove:
278 parent.remove_child(self)
279 super().remove(db_conn)