home · contact · privacy
Initialize Days with links to their Todos as early as possible.
[plomtask] / plomtask / days.py
1 """Collecting Day and date-related items."""
2 from __future__ import annotations
3 from typing import Any
4 from sqlite3 import Row
5 from datetime import datetime, timedelta
6 from plomtask.exceptions import HandledException
7 from plomtask.db import DatabaseConnection, BaseModel
8 from plomtask.todos import Todo
9 from plomtask.dating import (DATE_FORMAT, valid_date)
10
11
12 class Day(BaseModel[str]):
13     """Individual days defined by their dates."""
14     table_name = 'days'
15     to_save = ['comment']
16
17     def __init__(self,
18                  date: str,
19                  comment: str = '',
20                  init_empty_todo_list: bool = False
21                  ) -> None:
22         id_ = valid_date(date)
23         super().__init__(id_)
24         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
25         self.comment = comment
26         self.todos: list[Todo] | None = [] if init_empty_todo_list else None
27
28     def __lt__(self, other: Day) -> bool:
29         return self.date < other.date
30
31     @classmethod
32     def from_table_row(cls, db_conn: DatabaseConnection, row: Row | list[Any]
33                        ) -> Day:
34         """Make from DB row, with linked Todos."""
35         day = super().from_table_row(db_conn, row)
36         assert isinstance(day.id_, str)
37         day.todos = Todo.by_date(db_conn, day.id_)
38         return day
39
40     @classmethod
41     def by_date_range_filled(cls, db_conn: DatabaseConnection,
42                              start: str, end: str) -> list[Day]:
43         """Return days existing and non-existing between dates start/end."""
44         ret = cls.by_date_range_with_limits(db_conn, (start, end), 'id')
45         days, start_date, end_date = ret
46         return cls.with_filled_gaps(days, start_date, end_date)
47
48     @classmethod
49     def with_filled_gaps(cls, days: list[Day], start_date: str, end_date: str
50                          ) -> list[Day]:
51         """In days, fill with (un-saved) Days gaps between start/end_date."""
52         if start_date > end_date:
53             return days
54         days.sort()
55         if start_date not in [d.date for d in days]:
56             days[:] = [Day(start_date, init_empty_todo_list=True)] + days
57         if end_date not in [d.date for d in days]:
58             days += [Day(end_date, init_empty_todo_list=True)]
59         if len(days) > 1:
60             gapless_days = []
61             for i, day in enumerate(days):
62                 gapless_days += [day]
63                 if i < len(days) - 1:
64                     while day.next_date != days[i+1].date:
65                         day = Day(day.next_date, init_empty_todo_list=True)
66                         gapless_days += [day]
67             days[:] = gapless_days
68         return days
69
70     @property
71     def date(self) -> str:
72         """Return self.id_ under the assumption it's a date string."""
73         assert isinstance(self.id_, str)
74         return self.id_
75
76     @property
77     def first_of_month(self) -> bool:
78         """Return what month self.date is part of."""
79         assert isinstance(self.id_, str)
80         return self.id_[-2:] == '01'
81
82     @property
83     def month_name(self) -> str:
84         """Return what month self.date is part of."""
85         return self.datetime.strftime('%B')
86
87     @property
88     def weekday(self) -> str:
89         """Return what weekday matches self.date."""
90         return self.datetime.strftime('%A')
91
92     @property
93     def prev_date(self) -> str:
94         """Return date preceding date of this Day."""
95         prev_datetime = self.datetime - timedelta(days=1)
96         return prev_datetime.strftime(DATE_FORMAT)
97
98     @property
99     def next_date(self) -> str:
100         """Return date succeeding date of this Day."""
101         next_datetime = self.datetime + timedelta(days=1)
102         return next_datetime.strftime(DATE_FORMAT)
103
104     @property
105     def calendarized_todos(self) -> list[Todo]:
106         """Return only those of self.todos that have .calendarize set."""
107         if self.todos is None:
108             msg = 'Trying to return from un-initialized Day.todos.'
109             raise HandledException(msg)
110         # pylint: disable=not-an-iterable
111         # (after the above is-None test, self.todos _should_ be iterable!)
112         return [t for t in self.todos if t.calendarize]