1 """Collecting Day and date-related items."""
2 from __future__ import annotations
3 from datetime import datetime, timedelta
4 from plomtask.exceptions import BadFormatException
5 from plomtask.db import DatabaseConnection, BaseModel
7 DATE_FORMAT = '%Y-%m-%d'
8 MIN_RANGE_DATE = '2024-01-01'
9 MAX_RANGE_DATE = '2030-12-31'
12 def valid_date(date_str: str) -> str:
13 """Validate date against DATE_FORMAT or 'today', return in DATE_FORMAT."""
14 if date_str == 'today':
15 date_str = todays_date()
17 dt = datetime.strptime(date_str, DATE_FORMAT)
18 except (ValueError, TypeError) as e:
19 msg = f'Given date of wrong format: {date_str}'
20 raise BadFormatException(msg) from e
21 return dt.strftime(DATE_FORMAT)
24 def todays_date() -> str:
25 """Return current date in DATE_FORMAT."""
26 return datetime.now().strftime(DATE_FORMAT)
29 class Day(BaseModel[str]):
30 """Individual days defined by their dates."""
34 def __init__(self, date: str, comment: str = '') -> None:
35 id_ = valid_date(date)
37 self.datetime = datetime.strptime(self.date, DATE_FORMAT)
38 self.comment = comment
40 def __lt__(self, other: Day) -> bool:
41 return self.date < other.date
44 def all(cls, db_conn: DatabaseConnection,
45 date_range: tuple[str, str] = ('', ''),
46 fill_gaps: bool = False) -> list[Day]:
47 """Return list of Days in database within (open) date_range interval.
49 If no range values provided, defaults them to MIN_RANGE_DATE and
50 MAX_RANGE_DATE. Also knows to properly interpret 'today' as value.
52 On fill_gaps=True, will instantiate (without saving) Days of all dates
53 within the date range that don't exist yet.
55 min_date = '2024-01-01'
56 max_date = '2030-12-31'
57 start_date = valid_date(date_range[0] if date_range[0] else min_date)
58 end_date = valid_date(date_range[1] if date_range[1] else max_date)
60 sql = 'SELECT id FROM days WHERE id >= ? AND id <= ?'
61 for row in db_conn.exec(sql, (start_date, end_date)):
62 days += [cls.by_id(db_conn, row[0])]
64 if fill_gaps and len(days) > 1:
66 for i, day in enumerate(days):
69 while day.next_date != days[i+1].date:
70 day = Day(day.next_date)
76 def date(self) -> str:
77 """Return self.id_ under the assumption it's a date string."""
78 assert isinstance(self.id_, str)
82 def first_of_month(self) -> bool:
83 """Return what month self.date is part of."""
84 assert isinstance(self.id_, str)
85 return self.id_[-2:] == '01'
88 def month_name(self) -> str:
89 """Return what month self.date is part of."""
90 return self.datetime.strftime('%B')
93 def weekday(self) -> str:
94 """Return what weekday matches self.date."""
95 return self.datetime.strftime('%A')
98 def prev_date(self) -> str:
99 """Return date preceding date of this Day."""
100 prev_datetime = self.datetime - timedelta(days=1)
101 return prev_datetime.strftime(DATE_FORMAT)
104 def next_date(self) -> str:
105 """Return date succeeding date of this Day."""
106 next_datetime = self.datetime + timedelta(days=1)
107 return next_datetime.strftime(DATE_FORMAT)