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, BaseModel
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."""
33 def __init__(self, date: str, comment: str = '') -> None:
34 self.id_: str = valid_date(date)
35 self.datetime = datetime.strptime(self.date, DATE_FORMAT)
36 self.comment = comment
38 def __eq__(self, other: object) -> bool:
39 return isinstance(other, self.__class__) and self.date == other.date
41 def __lt__(self, other: Day) -> bool:
42 return self.date < other.date
45 def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Day:
46 """Make Day from database row, write to cache."""
47 day = cls(row[0], row[1])
48 db_conn.cached_days[day.date] = day
52 def all(cls, db_conn: DatabaseConnection,
53 date_range: tuple[str, str] = ('', ''),
54 fill_gaps: bool = False) -> list[Day]:
55 """Return list of Days in database within date_range."""
56 min_date = '2024-01-01'
57 max_date = '2030-12-31'
58 start_date = valid_date(date_range[0] if date_range[0] else min_date)
59 end_date = valid_date(date_range[1] if date_range[1] else max_date)
61 sql = 'SELECT date FROM days WHERE date >= ? AND date <= ?'
62 for row in db_conn.exec(sql, (start_date, end_date)):
63 days += [cls.by_date(db_conn, row[0])]
65 if fill_gaps and len(days) > 1:
67 for i, day in enumerate(days):
70 while day.next_date != days[i+1].date:
71 day = Day(day.next_date)
77 def by_date(cls, db_conn: DatabaseConnection,
78 date: str, create: bool = False) -> Day:
79 """Retrieve Day by date if in DB (prefer cache), else return None."""
80 if date in db_conn.cached_days.keys():
81 day = db_conn.cached_days[date]
82 assert isinstance(day, Day)
84 for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
85 return cls.from_table_row(db_conn, row)
87 raise NotFoundException(f'Day not found for date: {date}')
89 db_conn.cached_days[date] = day
90 assert isinstance(day, Day)
94 def date(self) -> str:
95 """Return self.id_ under the assumption it's a date string."""
99 def weekday(self) -> str:
100 """Return what weekday matches self.date."""
101 return self.datetime.strftime('%A')
104 def prev_date(self) -> str:
105 """Return date preceding date of this Day."""
106 prev_datetime = self.datetime - timedelta(days=1)
107 return prev_datetime.strftime(DATE_FORMAT)
110 def next_date(self) -> str:
111 """Return date succeeding date of this Day."""
112 next_datetime = self.datetime + timedelta(days=1)
113 return next_datetime.strftime(DATE_FORMAT)
115 def save(self, db_conn: DatabaseConnection) -> None:
116 """Add (or re-write) self to DB and cache."""
117 self.save_core(db_conn, update_with_lastrowid=False)