home · contact · privacy
155ed03aabdbddacdf481267c04aa9d5a0fc29c0
[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         # pylint: disable=protected-access
36         # (since on ._todo we're only meddling within cls)
37         day = super().from_table_row(db_conn, row)
38         assert isinstance(day.id_, str)
39         day._todos = Todo.by_date(db_conn, day.id_)
40         return day
41
42     @classmethod
43     def by_id(cls,
44               db_conn: DatabaseConnection, id_: str | None,
45               create: bool = False,
46               init_empty_todo_list: bool = False
47               ) -> Day:
48         """Extend BaseModel.by_id with init_empty_todo_list flag."""
49         # pylint: disable=protected-access
50         # (since on ._todo we're only meddling within cls)
51         day = super().by_id(db_conn, id_, create)
52         if init_empty_todo_list and day._todos is None:
53             day._todos = []
54         return day
55
56     @classmethod
57     def by_date_range_filled(cls, db_conn: DatabaseConnection,
58                              start: str, end: str) -> list[Day]:
59         """Return days existing and non-existing between dates start/end."""
60         ret = cls.by_date_range_with_limits(db_conn, (start, end), 'id')
61         days, start_date, end_date = ret
62         return cls.with_filled_gaps(days, start_date, end_date)
63
64     @classmethod
65     def with_filled_gaps(cls, days: list[Day], start_date: str, end_date: str
66                          ) -> list[Day]:
67         """In days, fill with (un-saved) Days gaps between start/end_date."""
68         if start_date > end_date:
69             return days
70         days.sort()
71         if start_date not in [d.date for d in days]:
72             days[:] = [Day(start_date, init_empty_todo_list=True)] + days
73         if end_date not in [d.date for d in days]:
74             days += [Day(end_date, init_empty_todo_list=True)]
75         if len(days) > 1:
76             gapless_days = []
77             for i, day in enumerate(days):
78                 gapless_days += [day]
79                 if i < len(days) - 1:
80                     while day.next_date != days[i+1].date:
81                         day = Day(day.next_date, init_empty_todo_list=True)
82                         gapless_days += [day]
83             days[:] = gapless_days
84         return days
85
86     @property
87     def date(self) -> str:
88         """Return self.id_ under the assumption it's a date string."""
89         assert isinstance(self.id_, str)
90         return self.id_
91
92     @property
93     def first_of_month(self) -> bool:
94         """Return what month self.date is part of."""
95         assert isinstance(self.id_, str)
96         return self.id_[-2:] == '01'
97
98     @property
99     def month_name(self) -> str:
100         """Return what month self.date is part of."""
101         return self.datetime.strftime('%B')
102
103     @property
104     def weekday(self) -> str:
105         """Return what weekday matches self.date."""
106         return self.datetime.strftime('%A')
107
108     @property
109     def prev_date(self) -> str:
110         """Return date preceding date of this Day."""
111         prev_datetime = self.datetime - timedelta(days=1)
112         return prev_datetime.strftime(DATE_FORMAT)
113
114     @property
115     def next_date(self) -> str:
116         """Return date succeeding date of this Day."""
117         next_datetime = self.datetime + timedelta(days=1)
118         return next_datetime.strftime(DATE_FORMAT)
119
120     @property
121     def todos(self) -> list[Todo]:
122         """Return self.todos if initialized, else raise Exception."""
123         if self._todos is None:
124             msg = 'Trying to return from un-initialized Day.todos.'
125             raise HandledException(msg)
126         return list(self._todos)
127
128     @property
129     def calendarized_todos(self) -> list[Todo]:
130         """Return only those of self.todos that have .calendarize set."""
131         return [t for t in self.todos if t.calendarize]
132
133     @property
134     def total_effort(self) -> float:
135         """"Sum all .performed_effort of self.todos."""
136         total_effort = 0.0
137         for todo in self.todos:
138             total_effort += todo.performed_effort
139         return total_effort