2 from __future__ import annotations
3 from typing import Any, Set
4 from sqlite3 import Row
5 from plomtask.db import DatabaseConnection, BaseModel
6 from plomtask.processes import Process, ProcessStepsNode
7 from plomtask.versioned_attributes import VersionedAttribute
8 from plomtask.conditions import Condition, ConditionsRelations
9 from plomtask.exceptions import (NotFoundException, BadFormatException,
11 from plomtask.dating import valid_date
15 """Collects what's useful to know for Todo/Condition tree display."""
16 # pylint: disable=too-few-public-methods
19 children: list[TodoNode]
24 children: list[TodoNode]) -> None:
27 self.children = children
30 def as_dict(self) -> dict[str, object]:
31 """Return self as (json.dumps-coompatible) dict."""
32 return {'todo': self.todo.id_,
34 'children': [c.as_dict for c in self.children]}
37 class Todo(BaseModel[int], ConditionsRelations):
38 """Individual actionable."""
39 # pylint: disable=too-many-instance-attributes
40 # pylint: disable=too-many-public-methods
42 to_save = ['process_id', 'is_done', 'date', 'comment', 'effort',
44 to_save_relations = [('todo_conditions', 'todo', 'conditions', 0),
45 ('todo_blockers', 'todo', 'blockers', 0),
46 ('todo_enables', 'todo', 'enables', 0),
47 ('todo_disables', 'todo', 'disables', 0),
48 ('todo_children', 'parent', 'children', 0),
49 ('todo_children', 'child', 'parents', 1)]
50 to_search = ['comment']
51 days_to_update: Set[str] = set()
55 # pylint: disable=too-many-arguments
56 def __init__(self, id_: int | None,
59 date: str, comment: str = '',
60 effort: None | float = None,
61 calendarize: bool = False) -> None:
62 BaseModel.__init__(self, id_)
63 ConditionsRelations.__init__(self)
64 if process.id_ is None:
65 raise NotFoundException('Process of Todo without ID (not saved?)')
66 self.process = process
67 self._is_done = is_done
68 self.date = valid_date(date)
69 self.comment = comment
73 self.calendarize = calendarize
75 self.calendarize = self.process.calendarize
76 self.conditions = self.process.conditions[:]
77 self.blockers = self.process.blockers[:]
78 self.enables = self.process.enables[:]
79 self.disables = self.process.disables[:]
82 def by_date_range(cls, db_conn: DatabaseConnection,
83 date_range: tuple[str, str] = ('', '')) -> list[Todo]:
84 """Collect Todos of Days within date_range."""
85 todos, _, _ = cls.by_date_range_with_limits(db_conn, date_range)
89 def create_with_children(cls, db_conn: DatabaseConnection,
90 process_id: int, date: str) -> Todo:
91 """Create Todo of process for date, ensure children."""
93 def key_order_func(n: ProcessStepsNode) -> int:
94 assert isinstance(n.process.id_, int)
97 def walk_steps(parent: Todo, step_node: ProcessStepsNode) -> Todo:
98 adoptables = [t for t in cls.by_date(db_conn, date)
99 if (t not in parent.children)
101 and step_node.process == t.process]
103 for adoptable in adoptables:
104 satisfier = adoptable
107 satisfier = cls(None, step_node.process, False, date)
108 satisfier.save(db_conn)
109 sub_step_nodes = list(step_node.steps.values())
110 sub_step_nodes.sort(key=key_order_func)
111 for sub_node in sub_step_nodes:
112 if sub_node.is_suppressed:
114 n_slots = len([n for n in sub_step_nodes
115 if n.process == sub_node.process])
116 filled_slots = len([t for t in satisfier.children
117 if t.process == sub_node.process])
118 # if we did not newly create satisfier, it may already fill
119 # some step dependencies, so only fill what remains open
120 if n_slots - filled_slots > 0:
121 satisfier.add_child(walk_steps(satisfier, sub_node))
122 satisfier.save(db_conn)
125 process = Process.by_id(db_conn, process_id)
126 todo = cls(None, process, False, date)
128 steps_tree = process.get_steps(db_conn)
129 for step_node in steps_tree.values():
130 if step_node.is_suppressed:
132 todo.add_child(walk_steps(todo, step_node))
137 def from_table_row(cls, db_conn: DatabaseConnection,
138 row: Row | list[Any]) -> Todo:
139 """Make from DB row, with dependencies."""
141 raise NotFoundException('calling Todo of '
143 row_as_list = list(row)
144 row_as_list[1] = Process.by_id(db_conn, row[1])
145 todo = super().from_table_row(db_conn, row_as_list)
146 assert isinstance(todo.id_, int)
147 for t_id in db_conn.column_where('todo_children', 'child',
149 todo.children += [cls.by_id(db_conn, t_id)]
150 for t_id in db_conn.column_where('todo_children', 'parent',
152 todo.parents += [cls.by_id(db_conn, t_id)]
153 for name in ('conditions', 'blockers', 'enables', 'disables'):
154 table = f'todo_{name}'
155 assert isinstance(todo.id_, int)
156 for cond_id in db_conn.column_where(table, 'condition',
158 target = getattr(todo, name)
159 target += [Condition.by_id(db_conn, cond_id)]
163 def by_process_id(cls, db_conn: DatabaseConnection,
164 process_id: int | None) -> list[Todo]:
165 """Collect all Todos of Process of process_id."""
166 return [t for t in cls.all(db_conn) if t.process.id_ == process_id]
169 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
170 """Collect all Todos for Day of date."""
171 return cls.by_date_range(db_conn, (date, date))
174 def is_doable(self) -> bool:
175 """Decide whether .is_done settable based on children, Conditions."""
176 for child in self.children:
177 if not child.is_done:
179 for condition in self.conditions:
180 if not condition.is_active:
182 for condition in self.blockers:
183 if condition.is_active:
188 def is_deletable(self) -> bool:
189 """Decide whether self be deletable (not if preserve-worthy values)."""
192 if self.effort and self.effort >= 0:
197 def performed_effort(self) -> float:
198 """Return performed effort, i.e. self.effort or default if done.."""
199 if self.effort is not None:
202 return self.effort_then
206 def process_id(self) -> int | str | None:
207 """Needed for super().save to save Processes as attributes."""
208 return self.process.id_
211 def is_done(self) -> bool:
212 """Wrapper around self._is_done so we can control its setter."""
216 def is_done(self, value: bool) -> None:
217 if value != self.is_done and not self.is_doable:
218 raise BadFormatException('cannot change doneness of undoable Todo')
219 if self._is_done != value:
220 self._is_done = value
222 for condition in self.enables:
223 condition.is_active = True
224 for condition in self.disables:
225 condition.is_active = False
228 def title(self) -> VersionedAttribute:
229 """Shortcut to .process.title."""
230 return self.process.title
233 def title_then(self) -> str:
234 """Shortcut to .process.title.at(self.date)"""
235 title_then = self.process.title.at(self.date)
236 assert isinstance(title_then, str)
240 def effort_then(self) -> float:
241 """Shortcut to .process.effort.at(self.date)"""
242 effort_then = self.process.effort.at(self.date)
243 assert isinstance(effort_then, float)
247 def has_doneness_in_path(self) -> bool:
248 """Check whether self is done or has any children that are."""
251 for child in self.children:
254 if child.has_doneness_in_path:
258 def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
259 """Return tree of depended-on Todos."""
261 def make_node(todo: Todo) -> TodoNode:
263 seen = todo.id_ in seen_todos
264 assert isinstance(todo.id_, int)
265 seen_todos.add(todo.id_)
266 for child in todo.children:
267 children += [make_node(child)]
268 return TodoNode(todo, seen, children)
270 return make_node(self)
273 def tree_effort(self) -> float:
274 """Return sum of performed efforts of self and all descendants."""
276 def walk_tree(node: Todo) -> float:
278 for child in node.children:
279 local_effort += walk_tree(child)
280 return node.performed_effort + local_effort
282 return walk_tree(self)
284 def add_child(self, child: Todo) -> None:
285 """Add child to self.children, avoid recursion, update parenthoods."""
287 def walk_steps(node: Todo) -> None:
288 if node.id_ == self.id_:
289 raise BadFormatException('bad child choice causes recursion')
290 for child in node.children:
294 raise HandledException('Can only add children to saved Todos.')
295 if child.id_ is None:
296 raise HandledException('Can only add saved children to Todos.')
297 if child in self.children:
298 raise BadFormatException('cannot adopt same child twice')
300 self.children += [child]
301 child.parents += [self]
303 def remove_child(self, child: Todo) -> None:
304 """Remove child from self.children, update counter relations."""
305 if child not in self.children:
306 raise HandledException('Cannot remove un-parented child.')
307 self.children.remove(child)
308 child.parents.remove(self)
310 def save(self, db_conn: DatabaseConnection) -> None:
311 """On save calls, also check if auto-deletion by effort < 0."""
312 if self.effort and self.effort < 0 and self.is_deletable:
316 self.__class__.days_to_update.add(self.date)
317 super().save(db_conn)
318 for condition in self.enables + self.disables + self.conditions:
319 condition.save(db_conn)
321 def remove(self, db_conn: DatabaseConnection) -> None:
322 """Remove from DB, including relations."""
323 if not self.is_deletable:
324 raise HandledException('Cannot remove non-deletable Todo.')
325 self.__class__.days_to_update.add(self.date)
326 children_to_remove = self.children[:]
327 parents_to_remove = self.parents[:]
328 for child in children_to_remove:
329 self.remove_child(child)
330 for parent in parents_to_remove:
331 parent.remove_child(self)
332 super().remove(db_conn)