home · contact · privacy
Put mypy into strict mode, adapt code to still pass.
[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.misc import HandledException
6 from plomtask.db import DatabaseConnection
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 HandledException(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:
29     """Individual days defined by their dates."""
30
31     def __init__(self, date: str, comment: str = '') -> None:
32         self.date = valid_date(date)
33         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
34         self.comment = comment
35
36     def __eq__(self, other: object) -> bool:
37         return isinstance(other, self.__class__) and self.date == other.date
38
39     def __lt__(self, other: Day) -> bool:
40         return self.date < other.date
41
42     @classmethod
43     def from_table_row(cls, row: Row) -> Day:
44         """Make Day from database row."""
45         return cls(row[0], row[1])
46
47     @classmethod
48     def all(cls, db_conn: DatabaseConnection,
49             date_range: tuple[str, str] = ('', ''),
50             fill_gaps: bool = False) -> list[Day]:
51         """Return list of Days in database within date_range."""
52         min_date = '2024-01-01'
53         max_date = '2030-12-31'
54         start_date = valid_date(date_range[0] if date_range[0] else min_date)
55         end_date = valid_date(date_range[1] if date_range[1] else max_date)
56         days = []
57         sql = 'SELECT * FROM days WHERE date >= ? AND date <= ?'
58         for row in db_conn.exec(sql, (start_date, end_date)):
59             days += [cls.from_table_row(row)]
60         days.sort()
61         if fill_gaps and len(days) > 1:
62             gapless_days = []
63             for i, day in enumerate(days):
64                 gapless_days += [day]
65                 if i < len(days) - 1:
66                     while day.next_date != days[i+1].date:
67                         day = Day(day.next_date)
68                         gapless_days += [day]
69             days = gapless_days
70         return days
71
72     @classmethod
73     def by_date(cls, db_conn: DatabaseConnection,
74                 date: str, create: bool = False) -> Day:
75         """Retrieve Day by date if in DB, else return None."""
76         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
77             return cls.from_table_row(row)
78         if not create:
79             raise HandledException(f'Day not found for date: {date}')
80         return cls(date)
81
82     @property
83     def weekday(self) -> str:
84         """Return what weekday matches self.date."""
85         return self.datetime.strftime('%A')
86
87     @property
88     def prev_date(self) -> str:
89         """Return date preceding date of this Day."""
90         prev_datetime = self.datetime - timedelta(days=1)
91         return prev_datetime.strftime(DATE_FORMAT)
92
93     @property
94     def next_date(self) -> str:
95         """Return date succeeding date of this Day."""
96         next_datetime = self.datetime + timedelta(days=1)
97         return next_datetime.strftime(DATE_FORMAT)
98
99     def save(self, db_conn: DatabaseConnection) -> None:
100         """Add (or re-write) self to database."""
101         db_conn.exec('REPLACE INTO days VALUES (?, ?)',
102                      (self.date, self.comment))