home · contact · privacy
Improve __eq__ of BaseModel to compare all saved attributes; plus minor refactorings.
[plomtask] / plomtask / days.py
1 """Collecting Day and date-related items."""
2 from __future__ import annotations
3 from datetime import datetime, timedelta
4 from plomtask.exceptions import BadFormatException
5 from plomtask.db import DatabaseConnection, BaseModel
6
7 DATE_FORMAT = '%Y-%m-%d'
8
9
10 def valid_date(date_str: str) -> str:
11     """Validate date against DATE_FORMAT or 'today', return in DATE_FORMAT."""
12     if date_str == 'today':
13         date_str = todays_date()
14     try:
15         dt = datetime.strptime(date_str, DATE_FORMAT)
16     except (ValueError, TypeError) as e:
17         msg = f'Given date of wrong format: {date_str}'
18         raise BadFormatException(msg) from e
19     return dt.strftime(DATE_FORMAT)
20
21
22 def todays_date() -> str:
23     """Return current date in DATE_FORMAT."""
24     return datetime.now().strftime(DATE_FORMAT)
25
26
27 class Day(BaseModel[str]):
28     """Individual days defined by their dates."""
29     table_name = 'days'
30     to_save = ['comment']
31
32     def __init__(self, date: str, comment: str = '') -> None:
33         id_ = valid_date(date)
34         super().__init__(id_)
35         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
36         self.comment = comment
37
38     def __lt__(self, other: Day) -> bool:
39         return self.date < other.date
40
41     @classmethod
42     def all(cls, db_conn: DatabaseConnection,
43             date_range: tuple[str, str] = ('', ''),
44             fill_gaps: bool = False) -> list[Day]:
45         """Return list of Days in database within date_range."""
46         min_date = '2024-01-01'
47         max_date = '2030-12-31'
48         start_date = valid_date(date_range[0] if date_range[0] else min_date)
49         end_date = valid_date(date_range[1] if date_range[1] else max_date)
50         days = []
51         sql = 'SELECT id FROM days WHERE id >= ? AND id <= ?'
52         for row in db_conn.exec(sql, (start_date, end_date)):
53             days += [cls.by_id(db_conn, row[0])]
54         days.sort()
55         if fill_gaps and len(days) > 1:
56             gapless_days = []
57             for i, day in enumerate(days):
58                 gapless_days += [day]
59                 if i < len(days) - 1:
60                     while day.next_date != days[i+1].date:
61                         day = Day(day.next_date)
62                         gapless_days += [day]
63             days = gapless_days
64         return days
65
66     @property
67     def date(self) -> str:
68         """Return self.id_ under the assumption it's a date string."""
69         assert isinstance(self.id_, str)
70         return self.id_
71
72     @property
73     def weekday(self) -> str:
74         """Return what weekday matches self.date."""
75         return self.datetime.strftime('%A')
76
77     @property
78     def prev_date(self) -> str:
79         """Return date preceding date of this Day."""
80         prev_datetime = self.datetime - timedelta(days=1)
81         return prev_datetime.strftime(DATE_FORMAT)
82
83     @property
84     def next_date(self) -> str:
85         """Return date succeeding date of this Day."""
86         next_datetime = self.datetime + timedelta(days=1)
87         return next_datetime.strftime(DATE_FORMAT)
88
89     def save(self, db_conn: DatabaseConnection) -> None:
90         """Add (or re-write) self to DB and cache."""
91         self.save_core(db_conn)