home · contact · privacy
Overhaul caching.
[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.db import DatabaseConnection, BaseModel
7 from plomtask.todos import Todo
8 from plomtask.dating import (DATE_FORMAT, valid_date)
9
10
11 class Day(BaseModel[str]):
12     """Individual days defined by their dates."""
13     table_name = 'days'
14     to_save = ['comment']
15
16     def __init__(self, date: str, comment: str = '') -> None:
17         id_ = valid_date(date)
18         super().__init__(id_)
19         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
20         self.comment = comment
21         self.todos: list[Todo] = []
22
23     def __lt__(self, other: Day) -> bool:
24         return self.date < other.date
25
26     @classmethod
27     def from_table_row(cls, db_conn: DatabaseConnection, row: Row | list[Any]
28                        ) -> Day:
29         """Make from DB row, with linked Todos."""
30         day = super().from_table_row(db_conn, row)
31         assert isinstance(day.id_, str)
32         day.todos = Todo.by_date(db_conn, day.id_)
33         return day
34
35     @classmethod
36     def by_id(cls,
37               db_conn: DatabaseConnection, id_: str | None,
38               create: bool = False,
39               ) -> Day:
40         """Extend BaseModel.by_id checking for new/lost .todos."""
41         day = super().by_id(db_conn, id_, create)
42         assert day.id_ is not None
43         if day.id_ in Todo.days_to_update:
44             Todo.days_to_update.remove(day.id_)
45             day.todos = Todo.by_date(db_conn, day.id_)
46         return day
47
48     @classmethod
49     def by_date_range_filled(cls, db_conn: DatabaseConnection,
50                              start: str, end: str) -> list[Day]:
51         """Return days existing and non-existing between dates start/end."""
52         ret = cls.by_date_range_with_limits(db_conn, (start, end), 'id')
53         days, start_date, end_date = ret
54         return cls.with_filled_gaps(days, start_date, end_date)
55
56     @classmethod
57     def with_filled_gaps(cls, days: list[Day], start_date: str, end_date: str
58                          ) -> list[Day]:
59         """In days, fill with (un-saved) Days gaps between start/end_date."""
60         if start_date > end_date:
61             return days
62         days.sort()
63         if start_date not in [d.date for d in days]:
64             days[:] = [Day(start_date)] + days
65         if end_date not in [d.date for d in days]:
66             days += [Day(end_date)]
67         if len(days) > 1:
68             gapless_days = []
69             for i, day in enumerate(days):
70                 gapless_days += [day]
71                 if i < len(days) - 1:
72                     while day.next_date != days[i+1].date:
73                         day = Day(day.next_date)
74                         gapless_days += [day]
75             days[:] = gapless_days
76         return days
77
78     @property
79     def date(self) -> str:
80         """Return self.id_ under the assumption it's a date string."""
81         assert isinstance(self.id_, str)
82         return self.id_
83
84     @property
85     def first_of_month(self) -> bool:
86         """Return what month self.date is part of."""
87         assert isinstance(self.id_, str)
88         return self.id_[-2:] == '01'
89
90     @property
91     def month_name(self) -> str:
92         """Return what month self.date is part of."""
93         return self.datetime.strftime('%B')
94
95     @property
96     def weekday(self) -> str:
97         """Return what weekday matches self.date."""
98         return self.datetime.strftime('%A')
99
100     @property
101     def prev_date(self) -> str:
102         """Return date preceding date of this Day."""
103         prev_datetime = self.datetime - timedelta(days=1)
104         return prev_datetime.strftime(DATE_FORMAT)
105
106     @property
107     def next_date(self) -> str:
108         """Return date succeeding date of this Day."""
109         next_datetime = self.datetime + timedelta(days=1)
110         return next_datetime.strftime(DATE_FORMAT)
111
112     @property
113     def calendarized_todos(self) -> list[Todo]:
114         """Return only those of self.todos that have .calendarize set."""
115         return [t for t in self.todos if t.calendarize]
116
117     @property
118     def total_effort(self) -> float:
119         """"Sum all .performed_effort of self.todos."""
120         total_effort = 0.0
121         for todo in self.todos:
122             total_effort += todo.performed_effort
123         return total_effort