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