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