home · contact · privacy
Refactor models' .by_id().
[plomtask] / plomtask / todos.py
1 """Actionables."""
2 from __future__ import annotations
3 from typing import Any
4 from sqlite3 import Row
5 from plomtask.db import DatabaseConnection, BaseModel
6 from plomtask.processes import Process
7 from plomtask.conditions import Condition
8 from plomtask.exceptions import (NotFoundException, BadFormatException,
9                                  HandledException)
10
11
12 class Todo(BaseModel):
13     """Individual actionable."""
14
15     # pylint: disable=too-many-instance-attributes
16
17     table_name = 'todos'
18     to_save = ['process_id', 'is_done', 'date']
19
20     def __init__(self, id_: int | None, process: Process,
21                  is_done: bool, date: str) -> None:
22         self.set_int_id(id_)
23         self.process = process
24         self._is_done = is_done
25         self.date = date
26         self.children: list[Todo] = []
27         self.parents: list[Todo] = []
28         self.conditions: list[Condition] = []
29         self.fulfills: list[Condition] = []
30         self.undoes: list[Condition] = []
31         if not self.id_:
32             self.conditions = process.conditions[:]
33             self.fulfills = process.fulfills[:]
34             self.undoes = process.undoes[:]
35
36     @classmethod
37     def from_table_row(cls, db_conn: DatabaseConnection,
38                        row: Row | list[Any]) -> Todo:
39         """Make from DB row, write to DB cache."""
40         if row[1] == 0:
41             raise NotFoundException('calling Todo of '
42                                     'unsaved Process')
43         row_as_list = list(row)
44         row_as_list[1] = Process.by_id(db_conn, row[1])
45         todo = super().from_table_row(db_conn, row_as_list)
46         assert isinstance(todo, Todo)
47         return todo
48
49     @classmethod
50     def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
51         """Get Todo of .id_=id_ and children (from DB cache if possible)."""
52         if id_:
53             todo, from_cache = super()._by_id(db_conn, id_)
54         else:
55             todo, from_cache = None, False
56         if todo is None:
57             raise NotFoundException(f'Todo of ID not found: {id_}')
58         if not from_cache:
59             for row in db_conn.exec('SELECT child FROM todo_children '
60                                     'WHERE parent = ?', (id_,)):
61                 todo.children += [cls.by_id(db_conn, row[0])]
62             for row in db_conn.exec('SELECT parent FROM todo_children '
63                                     'WHERE child = ?', (id_,)):
64                 todo.parents += [cls.by_id(db_conn, row[0])]
65             for row in db_conn.exec('SELECT condition FROM todo_conditions '
66                                     'WHERE todo = ?', (id_,)):
67                 todo.conditions += [Condition.by_id(db_conn, row[0])]
68             for row in db_conn.exec('SELECT condition FROM todo_fulfills '
69                                     'WHERE todo = ?', (id_,)):
70                 todo.fulfills += [Condition.by_id(db_conn, row[0])]
71             for row in db_conn.exec('SELECT condition FROM todo_undoes '
72                                     'WHERE todo = ?', (id_,)):
73                 todo.undoes += [Condition.by_id(db_conn, row[0])]
74         assert isinstance(todo, Todo)
75         return todo
76
77     @classmethod
78     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
79         """Collect all Todos for Day of date."""
80         todos = []
81         for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
82             todos += [cls.by_id(db_conn, row[0])]
83         return todos
84
85     @classmethod
86     def enablers_for_at(cls, db_conn: DatabaseConnection, condition: Condition,
87                         date: str) -> list[Todo]:
88         """Collect all Todos of day that enable condition."""
89         enablers = []
90         for row in db_conn.exec('SELECT todo FROM todo_fulfills '
91                                 'WHERE condition = ?', (condition.id_,)):
92             todo = cls.by_id(db_conn, row[0])
93             if todo.date == date:
94                 enablers += [todo]
95         return enablers
96
97     @classmethod
98     def disablers_for_at(cls, db_conn: DatabaseConnection,
99                          condition: Condition, date: str) -> list[Todo]:
100         """Collect all Todos of day that disable condition."""
101         disablers = []
102         for row in db_conn.exec('SELECT todo FROM todo_undoes '
103                                 'WHERE condition = ?', (condition.id_,)):
104             todo = cls.by_id(db_conn, row[0])
105             if todo.date == date:
106                 disablers += [todo]
107         return disablers
108
109     @property
110     def is_doable(self) -> bool:
111         """Decide whether .is_done settable based on children, Conditions."""
112         for child in self.children:
113             if not child.is_done:
114                 return False
115         for condition in self.conditions:
116             if not condition.is_active:
117                 return False
118         return True
119
120     @property
121     def process_id(self) -> int | str | None:
122         """Return ID of tasked Process."""
123         return self.process.id_
124
125     @property
126     def is_done(self) -> bool:
127         """Wrapper around self._is_done so we can control its setter."""
128         return self._is_done
129
130     @is_done.setter
131     def is_done(self, value: bool) -> None:
132         if value != self.is_done and not self.is_doable:
133             raise BadFormatException('cannot change doneness of undoable Todo')
134         if self._is_done != value:
135             self._is_done = value
136             if value is True:
137                 for condition in self.fulfills:
138                     condition.is_active = True
139                 for condition in self.undoes:
140                     condition.is_active = False
141
142     def set_undoes(self, db_conn: DatabaseConnection, ids: list[int]) -> None:
143         """Set self.undoes to Conditions identified by ids."""
144         self.set_conditions(db_conn, ids, 'undoes')
145
146     def set_fulfills(self, db_conn: DatabaseConnection,
147                      ids: list[int]) -> None:
148         """Set self.fulfills to Conditions identified by ids."""
149         self.set_conditions(db_conn, ids, 'fulfills')
150
151     def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
152                        target: str = 'conditions') -> None:
153         """Set self.[target] to Conditions identified by ids."""
154         target_list = getattr(self, target)
155         while len(target_list) > 0:
156             target_list.pop()
157         for id_ in ids:
158             target_list += [Condition.by_id(db_conn, id_)]
159
160     def add_child(self, child: Todo) -> None:
161         """Add child to self.children, guard against recursion"""
162         def walk_steps(node: Todo) -> None:
163             if node.id_ == self.id_:
164                 raise BadFormatException('bad child choice causes recursion')
165             for child in node.children:
166                 walk_steps(child)
167         if self.id_ is None:
168             raise HandledException('Can only add children to saved Todos.')
169         if child.id_ is None:
170             raise HandledException('Can only add saved children to Todos.')
171         if child in self.children:
172             raise BadFormatException('cannot adopt same child twice')
173         walk_steps(child)
174         self.children += [child]
175         child.parents += [self]
176
177     def save(self, db_conn: DatabaseConnection) -> None:
178         """Write self and children to DB and its cache."""
179         if self.process.id_ is None:
180             raise NotFoundException('Process of Todo without ID (not saved?)')
181         self.save_core(db_conn)
182         assert isinstance(self.id_, int)
183         db_conn.cached_todos[self.id_] = self
184         db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
185                      (self.id_,))
186         for child in self.children:
187             db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
188                          (self.id_, child.id_))
189         db_conn.exec('DELETE FROM todo_fulfills WHERE todo = ?', (self.id_,))
190         for condition in self.fulfills:
191             if condition.id_ is None:
192                 raise NotFoundException('Fulfilled Condition of Todo '
193                                         'without ID (not saved?)')
194             db_conn.exec('INSERT INTO todo_fulfills VALUES (?, ?)',
195                          (self.id_, condition.id_))
196         db_conn.exec('DELETE FROM todo_undoes WHERE todo = ?', (self.id_,))
197         for condition in self.undoes:
198             if condition.id_ is None:
199                 raise NotFoundException('Undone Condition of Todo '
200                                         'without ID (not saved?)')
201             db_conn.exec('INSERT INTO todo_undoes VALUES (?, ?)',
202                          (self.id_, condition.id_))
203         db_conn.exec('DELETE FROM todo_conditions WHERE todo = ?', (self.id_,))
204         for condition in self.conditions:
205             if condition.id_ is None:
206                 raise NotFoundException('Condition of Todo '
207                                         'without ID (not saved?)')
208             db_conn.exec('INSERT INTO todo_conditions VALUES (?, ?)',
209                          (self.id_, condition.id_))