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