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