2 from __future__ import annotations
3 from sqlite3 import Row
4 from plomtask.db import DatabaseConnection, BaseModel
5 from plomtask.days import Day
6 from plomtask.processes import Process
7 from plomtask.conditions import Condition
8 from plomtask.exceptions import (NotFoundException, BadFormatException,
12 class Todo(BaseModel):
13 """Individual actionable."""
15 # pylint: disable=too-many-instance-attributes
19 to_save = ['process_id', 'is_done', 'date']
21 def __init__(self, id_: int | None, process: Process,
22 is_done: bool, day: Day) -> None:
24 self.process = process
25 self._is_done = is_done
27 self.children: list[Todo] = []
28 self.parents: list[Todo] = []
29 self.conditions: list[Condition] = []
30 self.fulfills: list[Condition] = []
31 self.undoes: list[Condition] = []
33 self.conditions = process.conditions[:]
34 self.fulfills = process.fulfills[:]
35 self.undoes = process.undoes[:]
38 def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
39 """Make Todo from database row, write to DB cache."""
40 todo = cls(id_=row[0],
41 process=Process.by_id(db_conn, row[1]),
43 day=Day.by_date(db_conn, row[3]))
44 assert isinstance(todo.id_, int)
45 db_conn.cached_todos[todo.id_] = todo
49 def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
50 """Get Todo of .id_=id_ and children (from DB cache if possible)."""
51 if id_ in db_conn.cached_todos.keys():
52 todo = db_conn.cached_todos[id_]
55 for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
57 todo = cls.from_table_row(db_conn, row)
60 raise NotFoundException(f'Todo of ID not found: {id_}')
61 for row in db_conn.exec('SELECT child FROM todo_children '
62 'WHERE parent = ?', (id_,)):
63 todo.children += [cls.by_id(db_conn, row[0])]
64 for row in db_conn.exec('SELECT parent FROM todo_children '
65 'WHERE child = ?', (id_,)):
66 todo.parents += [cls.by_id(db_conn, row[0])]
67 for row in db_conn.exec('SELECT condition FROM todo_conditions '
68 'WHERE todo = ?', (id_,)):
69 todo.conditions += [Condition.by_id(db_conn, row[0])]
70 for row in db_conn.exec('SELECT condition FROM todo_fulfills '
71 'WHERE todo = ?', (id_,)):
72 todo.fulfills += [Condition.by_id(db_conn, row[0])]
73 for row in db_conn.exec('SELECT condition FROM todo_undoes '
74 'WHERE todo = ?', (id_,)):
75 todo.undoes += [Condition.by_id(db_conn, row[0])]
76 assert isinstance(todo, Todo)
80 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
81 """Collect all Todos for Day of date."""
83 for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
84 todos += [cls.by_id(db_conn, row[0])]
88 def enablers_for_at(cls, db_conn: DatabaseConnection, condition: Condition,
89 date: str) -> list[Todo]:
90 """Collect all Todos of day that enable condition."""
92 for row in db_conn.exec('SELECT todo FROM todo_fulfills '
93 'WHERE condition = ?', (condition.id_,)):
94 todo = cls.by_id(db_conn, row[0])
95 if todo.day.date == date:
100 def disablers_for_at(cls, db_conn: DatabaseConnection,
101 condition: Condition, date: str) -> list[Todo]:
102 """Collect all Todos of day that disable condition."""
104 for row in db_conn.exec('SELECT todo FROM todo_undoes '
105 'WHERE condition = ?', (condition.id_,)):
106 todo = cls.by_id(db_conn, row[0])
107 if todo.day.date == date:
112 def is_doable(self) -> bool:
113 """Decide whether .is_done settable based on children, Conditions."""
114 for child in self.children:
115 if not child.is_done:
117 for condition in self.conditions:
118 if not condition.is_active:
123 def process_id(self) -> int | str | None:
124 """Return ID of tasked Process."""
125 return self.process.id_
128 def date(self) -> str:
129 """Return date of used Day."""
133 def is_done(self) -> bool:
134 """Wrapper around self._is_done so we can control its setter."""
138 def is_done(self, value: bool) -> None:
139 if value != self.is_done and not self.is_doable:
140 raise BadFormatException('cannot change doneness of undoable Todo')
141 if self._is_done != value:
142 self._is_done = value
144 for condition in self.fulfills:
145 condition.is_active = True
146 for condition in self.undoes:
147 condition.is_active = False
149 def set_undoes(self, db_conn: DatabaseConnection, ids: list[int]) -> None:
150 """Set self.undoes to Conditions identified by ids."""
151 self.set_conditions(db_conn, ids, 'undoes')
153 def set_fulfills(self, db_conn: DatabaseConnection,
154 ids: list[int]) -> None:
155 """Set self.fulfills to Conditions identified by ids."""
156 self.set_conditions(db_conn, ids, 'fulfills')
158 def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
159 target: str = 'conditions') -> None:
160 """Set self.[target] to Conditions identified by ids."""
161 target_list = getattr(self, target)
162 while len(target_list) > 0:
165 target_list += [Condition.by_id(db_conn, id_)]
167 def add_child(self, child: Todo) -> None:
168 """Add child to self.children, guard against recursion"""
169 def walk_steps(node: Todo) -> None:
170 if node.id_ == self.id_:
171 raise BadFormatException('bad child choice causes recursion')
172 for child in node.children:
175 raise HandledException('Can only add children to saved Todos.')
176 if child.id_ is None:
177 raise HandledException('Can only add saved children to Todos.')
178 if child in self.children:
179 raise BadFormatException('cannot adopt same child twice')
181 self.children += [child]
182 child.parents += [self]
184 def save(self, db_conn: DatabaseConnection) -> None:
185 """Write self and children to DB and its cache."""
186 if self.process.id_ is None:
187 raise NotFoundException('Process of Todo without ID (not saved?)')
188 self.save_core(db_conn)
189 assert isinstance(self.id_, int)
190 db_conn.cached_todos[self.id_] = self
191 db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
193 for child in self.children:
194 db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
195 (self.id_, child.id_))
196 db_conn.exec('DELETE FROM todo_fulfills WHERE todo = ?', (self.id_,))
197 for condition in self.fulfills:
198 if condition.id_ is None:
199 raise NotFoundException('Fulfilled Condition of Todo '
200 'without ID (not saved?)')
201 db_conn.exec('INSERT INTO todo_fulfills VALUES (?, ?)',
202 (self.id_, condition.id_))
203 db_conn.exec('DELETE FROM todo_undoes WHERE todo = ?', (self.id_,))
204 for condition in self.undoes:
205 if condition.id_ is None:
206 raise NotFoundException('Undone Condition of Todo '
207 'without ID (not saved?)')
208 db_conn.exec('INSERT INTO todo_undoes VALUES (?, ?)',
209 (self.id_, condition.id_))
210 db_conn.exec('DELETE FROM todo_conditions WHERE todo = ?', (self.id_,))
211 for condition in self.conditions:
212 if condition.id_ is None:
213 raise NotFoundException('Condition of Todo '
214 'without ID (not saved?)')
215 db_conn.exec('INSERT INTO todo_conditions VALUES (?, ?)',
216 (self.id_, condition.id_))