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()
54 sorters = {'doneness': lambda t: t.is_done,
55 'title': lambda t: t.title_then,
56 'comment': lambda t: t.comment,
57 'date': lambda t: t.date}
59 # pylint: disable=too-many-arguments
60 def __init__(self, id_: int | None,
63 date: str, comment: str = '',
64 effort: None | float = None,
65 calendarize: bool = False) -> None:
66 BaseModel.__init__(self, id_)
67 ConditionsRelations.__init__(self)
68 if process.id_ is None:
69 raise NotFoundException('Process of Todo without ID (not saved?)')
70 self.process = process
71 self._is_done = is_done
72 self.date = valid_date(date)
73 self.comment = comment
77 self.calendarize = calendarize
79 self.calendarize = self.process.calendarize
80 self.conditions = self.process.conditions[:]
81 self.blockers = self.process.blockers[:]
82 self.enables = self.process.enables[:]
83 self.disables = self.process.disables[:]
86 def by_date_range(cls, db_conn: DatabaseConnection,
87 date_range: tuple[str, str] = ('', '')) -> list[Todo]:
88 """Collect Todos of Days within date_range."""
89 todos, _, _ = cls.by_date_range_with_limits(db_conn, date_range)
93 def create_with_children(cls, db_conn: DatabaseConnection,
94 process_id: int, date: str) -> Todo:
95 """Create Todo of process for date, ensure children."""
97 def key_order_func(n: ProcessStepsNode) -> int:
98 assert isinstance(n.process.id_, int)
101 def walk_steps(parent: Todo, step_node: ProcessStepsNode) -> Todo:
102 adoptables = [t for t in cls.by_date(db_conn, date)
103 if (t not in parent.children)
105 and step_node.process == t.process]
107 for adoptable in adoptables:
108 satisfier = adoptable
111 satisfier = cls(None, step_node.process, False, date)
112 satisfier.save(db_conn)
113 sub_step_nodes = list(step_node.steps.values())
114 sub_step_nodes.sort(key=key_order_func)
115 for sub_node in sub_step_nodes:
116 if sub_node.is_suppressed:
118 n_slots = len([n for n in sub_step_nodes
119 if n.process == sub_node.process])
120 filled_slots = len([t for t in satisfier.children
121 if t.process == sub_node.process])
122 # if we did not newly create satisfier, it may already fill
123 # some step dependencies, so only fill what remains open
124 if n_slots - filled_slots > 0:
125 satisfier.add_child(walk_steps(satisfier, sub_node))
126 satisfier.save(db_conn)
129 process = Process.by_id(db_conn, process_id)
130 todo = cls(None, process, False, date)
132 steps_tree = process.get_steps(db_conn)
133 for step_node in steps_tree.values():
134 if step_node.is_suppressed:
136 todo.add_child(walk_steps(todo, step_node))
141 def from_table_row(cls, db_conn: DatabaseConnection,
142 row: Row | list[Any]) -> Todo:
143 """Make from DB row, with dependencies."""
145 raise NotFoundException('calling Todo of '
147 row_as_list = list(row)
148 row_as_list[1] = Process.by_id(db_conn, row[1])
149 todo = super().from_table_row(db_conn, row_as_list)
150 assert isinstance(todo.id_, int)
151 for t_id in db_conn.column_where('todo_children', 'child',
153 todo.children += [cls.by_id(db_conn, t_id)]
154 for t_id in db_conn.column_where('todo_children', 'parent',
156 todo.parents += [cls.by_id(db_conn, t_id)]
157 for name in ('conditions', 'blockers', 'enables', 'disables'):
158 table = f'todo_{name}'
159 assert isinstance(todo.id_, int)
160 for cond_id in db_conn.column_where(table, 'condition',
162 target = getattr(todo, name)
163 target += [Condition.by_id(db_conn, cond_id)]
167 def by_process_id(cls, db_conn: DatabaseConnection,
168 process_id: int | None) -> list[Todo]:
169 """Collect all Todos of Process of process_id."""
170 return [t for t in cls.all(db_conn) if t.process.id_ == process_id]
173 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
174 """Collect all Todos for Day of date."""
175 return cls.by_date_range(db_conn, (date, date))
178 def is_doable(self) -> bool:
179 """Decide whether .is_done settable based on children, Conditions."""
180 for child in self.children:
181 if not child.is_done:
183 for condition in self.conditions:
184 if not condition.is_active:
186 for condition in self.blockers:
187 if condition.is_active:
192 def is_deletable(self) -> bool:
193 """Decide whether self be deletable (not if preserve-worthy values)."""
196 if self.effort and self.effort >= 0:
201 def performed_effort(self) -> float:
202 """Return performed effort, i.e. self.effort or default if done.."""
203 if self.effort is not None:
206 return self.effort_then
210 def process_id(self) -> int | str | None:
211 """Needed for super().save to save Processes as attributes."""
212 return self.process.id_
215 def is_done(self) -> bool:
216 """Wrapper around self._is_done so we can control its setter."""
220 def is_done(self, value: bool) -> None:
221 if value != self.is_done and not self.is_doable:
222 raise BadFormatException('cannot change doneness of undoable Todo')
223 if self._is_done != value:
224 self._is_done = value
226 for condition in self.enables:
227 condition.is_active = True
228 for condition in self.disables:
229 condition.is_active = False
232 def title(self) -> VersionedAttribute:
233 """Shortcut to .process.title."""
234 return self.process.title
237 def title_then(self) -> str:
238 """Shortcut to .process.title.at(self.date)"""
239 title_then = self.process.title.at(self.date)
240 assert isinstance(title_then, str)
244 def effort_then(self) -> float:
245 """Shortcut to .process.effort.at(self.date)"""
246 effort_then = self.process.effort.at(self.date)
247 assert isinstance(effort_then, float)
251 def has_doneness_in_path(self) -> bool:
252 """Check whether self is done or has any children that are."""
255 for child in self.children:
258 if child.has_doneness_in_path:
262 def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
263 """Return tree of depended-on Todos."""
265 def make_node(todo: Todo) -> TodoNode:
267 seen = todo.id_ in seen_todos
268 assert isinstance(todo.id_, int)
269 seen_todos.add(todo.id_)
270 for child in todo.children:
271 children += [make_node(child)]
272 return TodoNode(todo, seen, children)
274 return make_node(self)
277 def tree_effort(self) -> float:
278 """Return sum of performed efforts of self and all descendants."""
280 def walk_tree(node: Todo) -> float:
282 for child in node.children:
283 local_effort += walk_tree(child)
284 return node.performed_effort + local_effort
286 return walk_tree(self)
288 def add_child(self, child: Todo) -> None:
289 """Add child to self.children, avoid recursion, update parenthoods."""
291 def walk_steps(node: Todo) -> None:
292 if node.id_ == self.id_:
293 raise BadFormatException('bad child choice causes recursion')
294 for child in node.children:
298 raise HandledException('Can only add children to saved Todos.')
299 if child.id_ is None:
300 raise HandledException('Can only add saved children to Todos.')
301 if child in self.children:
302 raise BadFormatException('cannot adopt same child twice')
304 self.children += [child]
305 child.parents += [self]
307 def remove_child(self, child: Todo) -> None:
308 """Remove child from self.children, update counter relations."""
309 if child not in self.children:
310 raise HandledException('Cannot remove un-parented child.')
311 self.children.remove(child)
312 child.parents.remove(self)
314 def save(self, db_conn: DatabaseConnection) -> None:
315 """On save calls, also check if auto-deletion by effort < 0."""
316 if self.effort and self.effort < 0 and self.is_deletable:
320 self.__class__.days_to_update.add(self.date)
321 super().save(db_conn)
322 for condition in self.enables + self.disables + self.conditions:
323 condition.save(db_conn)
325 def remove(self, db_conn: DatabaseConnection) -> None:
326 """Remove from DB, including relations."""
327 if not self.is_deletable:
328 raise HandledException('Cannot remove non-deletable Todo.')
329 self.__class__.days_to_update.add(self.date)
330 children_to_remove = self.children[:]
331 parents_to_remove = self.parents[:]
332 for child in children_to_remove:
333 self.remove_child(child)
334 for parent in parents_to_remove:
335 parent.remove_child(self)
336 super().remove(db_conn)