home · contact · privacy
Base core models on BaseModel providing sensible defaults.
[plomtask] / plomtask / days.py
1 """Collecting Day and date-related items."""
2 from __future__ import annotations
3 from datetime import datetime, timedelta
4 from sqlite3 import Row
5 from plomtask.exceptions import BadFormatException, NotFoundException
6 from plomtask.db import DatabaseConnection, BaseModel
7
8 DATE_FORMAT = '%Y-%m-%d'
9
10
11 def valid_date(date_str: str) -> str:
12     """Validate date against DATE_FORMAT or 'today', return in DATE_FORMAT."""
13     if date_str == 'today':
14         date_str = todays_date()
15     try:
16         dt = datetime.strptime(date_str, DATE_FORMAT)
17     except (ValueError, TypeError) as e:
18         msg = f'Given date of wrong format: {date_str}'
19         raise BadFormatException(msg) from e
20     return dt.strftime(DATE_FORMAT)
21
22
23 def todays_date() -> str:
24     """Return current date in DATE_FORMAT."""
25     return datetime.now().strftime(DATE_FORMAT)
26
27
28 class Day(BaseModel):
29     """Individual days defined by their dates."""
30     table_name = 'days'
31     to_save = ['comment']
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 from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Day:
46         """Make Day from database row, write to cache."""
47         day = cls(row[0], row[1])
48         db_conn.cached_days[day.date] = day
49         return day
50
51     @classmethod
52     def all(cls, db_conn: DatabaseConnection,
53             date_range: tuple[str, str] = ('', ''),
54             fill_gaps: bool = False) -> list[Day]:
55         """Return list of Days in database within date_range."""
56         min_date = '2024-01-01'
57         max_date = '2030-12-31'
58         start_date = valid_date(date_range[0] if date_range[0] else min_date)
59         end_date = valid_date(date_range[1] if date_range[1] else max_date)
60         days = []
61         sql = 'SELECT date FROM days WHERE date >= ? AND date <= ?'
62         for row in db_conn.exec(sql, (start_date, end_date)):
63             days += [cls.by_date(db_conn, row[0])]
64         days.sort()
65         if fill_gaps and 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     @classmethod
77     def by_date(cls, db_conn: DatabaseConnection,
78                 date: str, create: bool = False) -> Day:
79         """Retrieve Day by date if in DB (prefer cache), else return None."""
80         if date in db_conn.cached_days.keys():
81             day = db_conn.cached_days[date]
82             assert isinstance(day, Day)
83             return day
84         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
85             return cls.from_table_row(db_conn, row)
86         if not create:
87             raise NotFoundException(f'Day not found for date: {date}')
88         day = cls(date)
89         db_conn.cached_days[date] = day
90         assert isinstance(day, Day)
91         return day
92
93     @property
94     def date(self) -> str:
95         """Return self.id_ under the assumption it's a date string."""
96         return self.id_
97
98     @property
99     def weekday(self) -> str:
100         """Return what weekday matches self.date."""
101         return self.datetime.strftime('%A')
102
103     @property
104     def prev_date(self) -> str:
105         """Return date preceding date of this Day."""
106         prev_datetime = self.datetime - timedelta(days=1)
107         return prev_datetime.strftime(DATE_FORMAT)
108
109     @property
110     def next_date(self) -> str:
111         """Return date succeeding date of this Day."""
112         next_datetime = self.datetime + timedelta(days=1)
113         return next_datetime.strftime(DATE_FORMAT)
114
115     def save(self, db_conn: DatabaseConnection) -> None:
116         """Add (or re-write) self to DB and cache."""
117         self.save_core(db_conn, update_with_lastrowid=False)