home · contact · privacy
Add rump HTTP server/handler testing.
[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,
55                 date: str, create: bool = False):
56         """Retrieve Day by date if in DB, else return None."""
57         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
58             return cls.from_table_row(row)
59         if create:
60             return cls(date)
61         return None
62
63     @property
64     def weekday(self):
65         """Return what weekday matches self.date."""
66         return self.datetime.strftime('%A')
67
68     def save(self, db_conn: DatabaseConnection):
69         """Add (or re-write) self to database."""
70         db_conn.exec('REPLACE INTO days VALUES (?, ?)',
71                      (self.date, self.comment))