home · contact · privacy
Add Todo.effort.
[plomtask] / plomtask / todos.py
1 """Actionables."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Any
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,
11                                  HandledException)
12
13
14 @dataclass
15 class TodoNode:
16     """Collects what's useful to know for Todo/Condition tree display."""
17     todo: Todo
18     seen: bool
19     children: list[TodoNode]
20
21
22 class Todo(BaseModel[int], ConditionsRelations):
23     """Individual actionable."""
24     # pylint: disable=too-many-instance-attributes
25     table_name = 'todos'
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')]
32
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:
37         super().__init__(id_)
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
42         self.date = date
43         self.comment = comment
44         self.effort = effort
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] = []
50         if not self.id_:
51             self.conditions = self.process.conditions[:]
52             self.enables = self.process.enables[:]
53             self.disables = self.process.disables[:]
54
55     @classmethod
56     def from_table_row(cls, db_conn: DatabaseConnection,
57                        row: Row | list[Any]) -> Todo:
58         """Make from DB row, with dependencies."""
59         if row[1] == 0:
60             raise NotFoundException('calling Todo of '
61                                     'unsaved Process')
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',
67                                          'parent', todo.id_):
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',
71                                          'child', todo.id_):
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',
78                                                 'todo', todo.id_):
79                 target = getattr(todo, name)
80                 target += [Condition.by_id(db_conn, cond_id)]
81         return todo
82
83     @classmethod
84     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
85         """Collect all Todos for Day of date."""
86         todos = []
87         for id_ in db_conn.column_where('todos', 'id', 'day', date):
88             todos += [cls.by_id(db_conn, id_)]
89         return todos
90
91     @property
92     def is_doable(self) -> bool:
93         """Decide whether .is_done settable based on children, Conditions."""
94         for child in self.children:
95             if not child.is_done:
96                 return False
97         for condition in self.conditions:
98             if not condition.is_active:
99                 return False
100         return True
101
102     @property
103     def process_id(self) -> int | str | None:
104         """Needed for super().save to save Processes as attributes."""
105         return self.process.id_
106
107     @property
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)
115         return unsatisfied
116
117     @property
118     def is_done(self) -> bool:
119         """Wrapper around self._is_done so we can control its setter."""
120         return self._is_done
121
122     @is_done.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
128             if value is True:
129                 for condition in self.enables:
130                     condition.is_active = True
131                 for condition in self.disables:
132                     condition.is_active = False
133
134     @property
135     def title(self) -> VersionedAttribute:
136         """Shortcut to .process.title."""
137         return self.process.title
138
139     def adopt_from(self, todos: list[Todo]) -> bool:
140         """As far as possible, fill unsatisfied dependencies from todos."""
141         adopted = False
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]:
145                 self.add_child(todo)
146                 adopted = True
147                 break
148         return adopted
149
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)
155             todo.save(db_conn)
156             self.add_child(todo)
157
158     def get_step_tree(self, seen_todos: set[int]) -> TodoNode:
159         """Return tree of depended-on Todos."""
160
161         def make_node(todo: Todo) -> TodoNode:
162             children = []
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)
169
170         return make_node(self)
171
172     def add_child(self, child: Todo) -> None:
173         """Add child to self.children, avoid recursion, update parenthoods."""
174
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:
179                 walk_steps(child)
180
181         if self.id_ is None:
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')
187         walk_steps(child)
188         self.children += [child]
189         child.parents += [self]
190
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)
197
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)