home · contact · privacy
258d38dbbf1d7f920f36ca06c9f8292506d16807
[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, NotFoundException
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         self.id_: str = valid_date(date)
34         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
35         self.comment = comment
36
37     def __eq__(self, other: object) -> bool:
38         return isinstance(other, self.__class__) and self.date == other.date
39
40     def __lt__(self, other: Day) -> bool:
41         return self.date < other.date
42
43     @classmethod
44     def all(cls, db_conn: DatabaseConnection,
45             date_range: tuple[str, str] = ('', ''),
46             fill_gaps: bool = False) -> list[Day]:
47         """Return list of Days in database within date_range."""
48         min_date = '2024-01-01'
49         max_date = '2030-12-31'
50         start_date = valid_date(date_range[0] if date_range[0] else min_date)
51         end_date = valid_date(date_range[1] if date_range[1] else max_date)
52         days = []
53         sql = 'SELECT id FROM days WHERE id >= ? AND id <= ?'
54         for row in db_conn.exec(sql, (start_date, end_date)):
55             days += [cls.by_id(db_conn, row[0])]
56         days.sort()
57         if fill_gaps and len(days) > 1:
58             gapless_days = []
59             for i, day in enumerate(days):
60                 gapless_days += [day]
61                 if i < len(days) - 1:
62                     while day.next_date != days[i+1].date:
63                         day = Day(day.next_date)
64                         gapless_days += [day]
65             days = gapless_days
66         return days
67
68     @classmethod
69     def by_id(cls, db_conn: DatabaseConnection,
70               date: str, create: bool = False) -> Day:
71         """Retrieve Day by date if in DB (prefer cache), else return None."""
72         day, _ = super()._by_id(db_conn, date)
73         if day:
74             return day
75         if not create:
76             raise NotFoundException(f'Day not found for date: {date}')
77         day = cls(date)
78         day.cache()
79         return day
80
81     @property
82     def date(self) -> str:
83         """Return self.id_ under the assumption it's a date string."""
84         return self.id_
85
86     @property
87     def weekday(self) -> str:
88         """Return what weekday matches self.date."""
89         return self.datetime.strftime('%A')
90
91     @property
92     def prev_date(self) -> str:
93         """Return date preceding date of this Day."""
94         prev_datetime = self.datetime - timedelta(days=1)
95         return prev_datetime.strftime(DATE_FORMAT)
96
97     @property
98     def next_date(self) -> str:
99         """Return date succeeding date of this Day."""
100         next_datetime = self.datetime + timedelta(days=1)
101         return next_datetime.strftime(DATE_FORMAT)
102
103     def save(self, db_conn: DatabaseConnection) -> None:
104         """Add (or re-write) self to DB and cache."""
105         self.save_core(db_conn, update_with_lastrowid=False)