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
8 DATE_FORMAT = '%Y-%m-%d'
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()
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)
23 def todays_date() -> str:
24 """Return current date in DATE_FORMAT."""
25 return datetime.now().strftime(DATE_FORMAT)
29 """Individual days defined by their dates."""
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
36 def __eq__(self, other: object) -> bool:
37 return isinstance(other, self.__class__) and self.date == other.date
39 def __lt__(self, other: Day) -> bool:
40 return self.date < other.date
43 def from_table_row(cls, row: Row) -> Day:
44 """Make Day from database row."""
45 return cls(row[0], row[1])
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)
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)]
61 if fill_gaps and len(days) > 1:
63 for i, day in enumerate(days):
66 while day.next_date != days[i+1].date:
67 day = Day(day.next_date)
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)
79 raise NotFoundException(f'Day not found for date: {date}')
83 def weekday(self) -> str:
84 """Return what weekday matches self.date."""
85 return self.datetime.strftime('%A')
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)
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)
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))