home · contact · privacy
Refactor from_table_row methods of core DB models.
[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):
28     """Individual days defined by their dates."""
29     table_name = 'days'
30     to_save = ['comment']
31     id_type = str
32
33     def __init__(self, date: str, comment: str = '') -> None:
34         self.id_: str = valid_date(date)
35         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
36         self.comment = comment
37
38     def __eq__(self, other: object) -> bool:
39         return isinstance(other, self.__class__) and self.date == other.date
40
41     def __lt__(self, other: Day) -> bool:
42         return self.date < other.date
43
44     @classmethod
45     def all(cls, db_conn: DatabaseConnection,
46             date_range: tuple[str, str] = ('', ''),
47             fill_gaps: bool = False) -> list[Day]:
48         """Return list of Days in database within date_range."""
49         min_date = '2024-01-01'
50         max_date = '2030-12-31'
51         start_date = valid_date(date_range[0] if date_range[0] else min_date)
52         end_date = valid_date(date_range[1] if date_range[1] else max_date)
53         days = []
54         sql = 'SELECT date FROM days WHERE date >= ? AND date <= ?'
55         for row in db_conn.exec(sql, (start_date, end_date)):
56             days += [cls.by_date(db_conn, row[0])]
57         days.sort()
58         if fill_gaps and len(days) > 1:
59             gapless_days = []
60             for i, day in enumerate(days):
61                 gapless_days += [day]
62                 if i < len(days) - 1:
63                     while day.next_date != days[i+1].date:
64                         day = Day(day.next_date)
65                         gapless_days += [day]
66             days = gapless_days
67         return days
68
69     @classmethod
70     def by_date(cls, db_conn: DatabaseConnection,
71                 date: str, create: bool = False) -> Day:
72         """Retrieve Day by date if in DB (prefer cache), else return None."""
73         if date in db_conn.cached_days.keys():
74             day = db_conn.cached_days[date]
75             assert isinstance(day, Day)
76             return day
77         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
78             day = cls.from_table_row(db_conn, row)
79             assert isinstance(day, Day)
80             return day
81         if not create:
82             raise NotFoundException(f'Day not found for date: {date}')
83         day = cls(date)
84         db_conn.cached_days[date] = day
85         assert isinstance(day, Day)
86         return day
87
88     @property
89     def date(self) -> str:
90         """Return self.id_ under the assumption it's a date string."""
91         return self.id_
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     def save(self, db_conn: DatabaseConnection) -> None:
111         """Add (or re-write) self to DB and cache."""
112         self.save_core(db_conn, update_with_lastrowid=False)