home · contact · privacy
Add most basic Todo family relations.
[plomtask] / plomtask / todos.py
1 """Actionables."""
2 from __future__ import annotations
3 from sqlite3 import Row
4 from plomtask.db import DatabaseConnection
5 from plomtask.days import Day
6 from plomtask.processes import Process
7 from plomtask.exceptions import (NotFoundException, BadFormatException,
8                                  HandledException)
9
10
11 class Todo:
12     """Individual actionable."""
13
14     def __init__(self, id_: int | None, process: Process,
15                  is_done: bool, day: Day) -> None:
16         self.id_ = id_
17         self.process = process
18         self.is_done = is_done
19         self.day = day
20         self.children: list[Todo] = []
21
22     @classmethod
23     def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
24         """Make Todo from database row, write to DB cache."""
25         todo = cls(id_=row[0],
26                    process=Process.by_id(db_conn, row[1]),
27                    is_done=row[2],
28                    day=Day.by_date(db_conn, row[3]))
29         assert todo.id_ is not None
30         db_conn.cached_todos[todo.id_] = todo
31         return todo
32
33     @classmethod
34     def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
35         """Get Todo of .id_=id_ and children (from DB cache if possible)."""
36         if id_ in db_conn.cached_todos.keys():
37             todo = db_conn.cached_todos[id_]
38         else:
39             todo = None
40             for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
41                                     (id_,)):
42                 todo = cls.from_table_row(db_conn, row)
43                 break
44             if todo is None:
45                 raise NotFoundException(f'Todo of ID not found: {id_}')
46             for row in db_conn.exec('SELECT child FROM todo_children '
47                                     'WHERE parent = ?', (id_,)):
48                 todo.children += [cls.by_id(db_conn, row[0])]
49         assert isinstance(todo, Todo)
50         return todo
51
52     @classmethod
53     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
54         """Collect all Todos for Day of date."""
55         todos = []
56         for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
57             todos += [cls.by_id(db_conn, row[0])]
58         return todos
59
60     def add_child(self, child: Todo) -> None:
61         """Add child to self.children, guard against recursion"""
62         def walk_steps(node: Todo) -> None:
63             if node.id_ == self.id_:
64                 raise BadFormatException('bad child choice causes recursion')
65             for child in node.children:
66                 walk_steps(child)
67         if self.id_ is None:
68             raise HandledException('Can only add children to saved Todos.')
69         if child.id_ is None:
70             raise HandledException('Can only add saved children to Todos.')
71         if child in self.children:
72             raise BadFormatException('cannot adopt same child twice')
73         walk_steps(child)
74         self.children += [child]
75
76     def save(self, db_conn: DatabaseConnection) -> None:
77         """Write self and children to DB and its cache."""
78         if self.process.id_ is None:
79             raise NotFoundException('Process of Todo without ID (not saved?)')
80         cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
81                               (self.id_, self.process.id_,
82                                self.is_done, self.day.date))
83         self.id_ = cursor.lastrowid
84         assert self.id_ is not None
85         db_conn.cached_todos[self.id_] = self
86         db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
87                      (self.id_,))
88         for child in self.children:
89             db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
90                          (self.id_, child.id_))