home · contact · privacy
ba466b52c792f81029a94f4bc9fcc21718dd500b
[plomtask] / plomtask / days.py
1 """Collecting Day and date-related items."""
2 from datetime import datetime
3 from sqlite3 import Row
4 from plomtask.misc import HandledException
5 from plomtask.db import DatabaseConnection
6
7 DATE_FORMAT = '%Y-%m-%d'
8
9
10 def date_valid(date: str):
11     """Validate date against DATE_FORMAT, return Datetime or None."""
12     try:
13         result = datetime.strptime(date, DATE_FORMAT)
14     except (ValueError, TypeError):
15         return None
16     return result
17
18
19 class Day:
20     """Individual days defined by their dates."""
21
22     def __init__(self, date: str, comment: str = ''):
23         self.date = date
24         self.datetime = date_valid(self.date)
25         if not self.datetime:
26             raise HandledException(f'Given date of wrong format: {self.date}')
27         self.comment = comment
28
29     def __eq__(self, other: object):
30         return isinstance(other, self.__class__) and self.date == other.date
31
32     def __lt__(self, other):
33         return self.date < other.date
34
35     @classmethod
36     def from_table_row(cls, row: Row):
37         """Make new Day from database row."""
38         return cls(row[0], row[1])
39
40     @classmethod
41     def all(cls, db_conn: DatabaseConnection,
42             date_range: tuple[str, str] = ('', '')):
43         """Return list of Days in database within date_range."""
44         start_date = date_range[0] if date_range[0] else '2024-01-01'
45         end_date = date_range[1] if date_range[1] else '2030-12-31'
46         days = []
47         sql = 'SELECT * FROM days WHERE date >= ? AND date <= ?'
48         for row in db_conn.exec(sql, (start_date, end_date)):
49             days += [cls.from_table_row(row)]
50         days.sort()
51         return days
52
53     @classmethod
54     def by_date(cls, db_conn: DatabaseConnection, date: str):
55         """Retrieve Day by date if in DB, else return None."""
56         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
57             return cls.from_table_row(row)
58         return None
59
60     @property
61     def weekday(self):
62         """Return what weekday matches self.date."""
63         return self.datetime.strftime('%A')
64
65     def save(self, db_conn: DatabaseConnection):
66         """Add (or re-write) self to database."""
67         db_conn.exec('REPLACE INTO days VALUES (?, ?)',
68                      (self.date, self.comment))