home · contact · privacy
Add GET /todo and Todo retrieval by ID.
[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
8
9
10 class Todo:
11     """Individual actionable."""
12
13     def __init__(self, id_: int | None, process: Process,
14                  is_done: bool, day: Day) -> None:
15         self.id_ = id_
16         self.process = process
17         self.is_done = is_done
18         self.day = day
19
20     def __eq__(self, other: object) -> bool:
21         return isinstance(other, self.__class__) and self.id_ == other.id_
22
23     @classmethod
24     def from_table_row(cls, row: Row, db_conn: DatabaseConnection) -> Todo:
25         """Make Todo from database row."""
26         return cls(id_=row[0],
27                    process=Process.by_id(db_conn, row[1]),
28                    is_done=row[2],
29                    day=Day.by_date(db_conn, row[3]))
30
31     @classmethod
32     def by_id(cls, db_conn: DatabaseConnection, id_: int) -> Todo:
33         """Get Todo of .id_=id_."""
34         for row in db_conn.exec('SELECT * FROM todos WHERE id = ?', (id_,)):
35             return cls.from_table_row(row, db_conn)
36         raise NotFoundException(f'Todo of ID not found: {id_}')
37
38     @classmethod
39     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
40         """Collect all Todos for Day of date."""
41         todos = []
42         for row in db_conn.exec('SELECT * FROM todos WHERE day = ?', (date,)):
43             todos += [cls.from_table_row(row, db_conn)]
44         return todos
45
46     def save(self, db_conn: DatabaseConnection) -> None:
47         """Write self to DB."""
48         if self.process.id_ is None:
49             raise NotFoundException('Process of Todo without ID (not saved?)')
50         cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
51                               (self.id_, self.process.id_,
52                                self.is_done, self.day.date))
53         self.id_ = cursor.lastrowid