2 from __future__ import annotations
3 from plomtask.db import DatabaseConnection, BaseModel
4 from plomtask.processes import Process
5 from plomtask.conditions import Condition
6 from plomtask.exceptions import (NotFoundException, BadFormatException,
10 class Todo(BaseModel):
11 """Individual actionable."""
13 # pylint: disable=too-many-instance-attributes
16 to_save = ['process_id', 'is_done', 'date']
18 def __init__(self, id_: int | None, process: Process,
19 is_done: bool, date: str) -> None:
21 self.process = process
22 self._is_done = is_done
24 self.children: list[Todo] = []
25 self.parents: list[Todo] = []
26 self.conditions: list[Condition] = []
27 self.fulfills: list[Condition] = []
28 self.undoes: list[Condition] = []
30 self.conditions = process.conditions[:]
31 self.fulfills = process.fulfills[:]
32 self.undoes = process.undoes[:]
35 def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
36 """Get Todo of .id_=id_ and children (from DB cache if possible)."""
37 if id_ in db_conn.cached_todos.keys():
38 todo = db_conn.cached_todos[id_]
41 for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
45 raise NotFoundException('calling Todo of '
47 row[1] = Process.by_id(db_conn, row[1])
48 todo = cls.from_table_row(db_conn, row)
51 raise NotFoundException(f'Todo of ID not found: {id_}')
52 for row in db_conn.exec('SELECT child FROM todo_children '
53 'WHERE parent = ?', (id_,)):
54 todo.children += [cls.by_id(db_conn, row[0])]
55 for row in db_conn.exec('SELECT parent FROM todo_children '
56 'WHERE child = ?', (id_,)):
57 todo.parents += [cls.by_id(db_conn, row[0])]
58 for row in db_conn.exec('SELECT condition FROM todo_conditions '
59 'WHERE todo = ?', (id_,)):
60 todo.conditions += [Condition.by_id(db_conn, row[0])]
61 for row in db_conn.exec('SELECT condition FROM todo_fulfills '
62 'WHERE todo = ?', (id_,)):
63 todo.fulfills += [Condition.by_id(db_conn, row[0])]
64 for row in db_conn.exec('SELECT condition FROM todo_undoes '
65 'WHERE todo = ?', (id_,)):
66 todo.undoes += [Condition.by_id(db_conn, row[0])]
67 assert isinstance(todo, Todo)
71 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
72 """Collect all Todos for Day of date."""
74 for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
75 todos += [cls.by_id(db_conn, row[0])]
79 def enablers_for_at(cls, db_conn: DatabaseConnection, condition: Condition,
80 date: str) -> list[Todo]:
81 """Collect all Todos of day that enable condition."""
83 for row in db_conn.exec('SELECT todo FROM todo_fulfills '
84 'WHERE condition = ?', (condition.id_,)):
85 todo = cls.by_id(db_conn, row[0])
91 def disablers_for_at(cls, db_conn: DatabaseConnection,
92 condition: Condition, date: str) -> list[Todo]:
93 """Collect all Todos of day that disable condition."""
95 for row in db_conn.exec('SELECT todo FROM todo_undoes '
96 'WHERE condition = ?', (condition.id_,)):
97 todo = cls.by_id(db_conn, row[0])
103 def is_doable(self) -> bool:
104 """Decide whether .is_done settable based on children, Conditions."""
105 for child in self.children:
106 if not child.is_done:
108 for condition in self.conditions:
109 if not condition.is_active:
114 def process_id(self) -> int | str | None:
115 """Return ID of tasked Process."""
116 return self.process.id_
119 def is_done(self) -> bool:
120 """Wrapper around self._is_done so we can control its setter."""
124 def is_done(self, value: bool) -> None:
125 if value != self.is_done and not self.is_doable:
126 raise BadFormatException('cannot change doneness of undoable Todo')
127 if self._is_done != value:
128 self._is_done = value
130 for condition in self.fulfills:
131 condition.is_active = True
132 for condition in self.undoes:
133 condition.is_active = False
135 def set_undoes(self, db_conn: DatabaseConnection, ids: list[int]) -> None:
136 """Set self.undoes to Conditions identified by ids."""
137 self.set_conditions(db_conn, ids, 'undoes')
139 def set_fulfills(self, db_conn: DatabaseConnection,
140 ids: list[int]) -> None:
141 """Set self.fulfills to Conditions identified by ids."""
142 self.set_conditions(db_conn, ids, 'fulfills')
144 def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
145 target: str = 'conditions') -> None:
146 """Set self.[target] to Conditions identified by ids."""
147 target_list = getattr(self, target)
148 while len(target_list) > 0:
151 target_list += [Condition.by_id(db_conn, id_)]
153 def add_child(self, child: Todo) -> None:
154 """Add child to self.children, guard against recursion"""
155 def walk_steps(node: Todo) -> None:
156 if node.id_ == self.id_:
157 raise BadFormatException('bad child choice causes recursion')
158 for child in node.children:
161 raise HandledException('Can only add children to saved Todos.')
162 if child.id_ is None:
163 raise HandledException('Can only add saved children to Todos.')
164 if child in self.children:
165 raise BadFormatException('cannot adopt same child twice')
167 self.children += [child]
168 child.parents += [self]
170 def save(self, db_conn: DatabaseConnection) -> None:
171 """Write self and children to DB and its cache."""
172 if self.process.id_ is None:
173 raise NotFoundException('Process of Todo without ID (not saved?)')
174 self.save_core(db_conn)
175 assert isinstance(self.id_, int)
176 db_conn.cached_todos[self.id_] = self
177 db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
179 for child in self.children:
180 db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
181 (self.id_, child.id_))
182 db_conn.exec('DELETE FROM todo_fulfills WHERE todo = ?', (self.id_,))
183 for condition in self.fulfills:
184 if condition.id_ is None:
185 raise NotFoundException('Fulfilled Condition of Todo '
186 'without ID (not saved?)')
187 db_conn.exec('INSERT INTO todo_fulfills VALUES (?, ?)',
188 (self.id_, condition.id_))
189 db_conn.exec('DELETE FROM todo_undoes WHERE todo = ?', (self.id_,))
190 for condition in self.undoes:
191 if condition.id_ is None:
192 raise NotFoundException('Undone Condition of Todo '
193 'without ID (not saved?)')
194 db_conn.exec('INSERT INTO todo_undoes VALUES (?, ?)',
195 (self.id_, condition.id_))
196 db_conn.exec('DELETE FROM todo_conditions WHERE todo = ?', (self.id_,))
197 for condition in self.conditions:
198 if condition.id_ is None:
199 raise NotFoundException('Condition of Todo '
200 'without ID (not saved?)')
201 db_conn.exec('INSERT INTO todo_conditions VALUES (?, ?)',
202 (self.id_, condition.id_))