X-Git-Url: https://plomlompom.com/repos/feed.xml?a=blobdiff_plain;f=plomtask%2Fdays.py;h=afdea33760b41df3149c857b306c6e2b447b7df8;hb=87398980c438de55ff17098790a59e123624493b;hp=8db9f15b7362ede61c70265e4d5eb8a4c2c0c626;hpb=4546631ed7cc59f3e66a1902b28930f955b2b03f;p=plomtask diff --git a/plomtask/days.py b/plomtask/days.py index 8db9f15..afdea33 100644 --- a/plomtask/days.py +++ b/plomtask/days.py @@ -1,24 +1,102 @@ -#!/usr/bin/env python3 """Collecting Day and date-related items.""" -from datetime import datetime +from __future__ import annotations +from datetime import datetime, timedelta +from sqlite3 import Row +from plomtask.exceptions import BadFormatException, NotFoundException +from plomtask.db import DatabaseConnection DATE_FORMAT = '%Y-%m-%d' +def valid_date(date_str: str) -> str: + """Validate date against DATE_FORMAT or 'today', return in DATE_FORMAT.""" + if date_str == 'today': + date_str = todays_date() + try: + dt = datetime.strptime(date_str, DATE_FORMAT) + except (ValueError, TypeError) as e: + msg = f'Given date of wrong format: {date_str}' + raise BadFormatException(msg) from e + return dt.strftime(DATE_FORMAT) + + +def todays_date() -> str: + """Return current date in DATE_FORMAT.""" + return datetime.now().strftime(DATE_FORMAT) + + class Day: """Individual days defined by their dates.""" - def __init__(self, date: str): - self.date = date - self.datetime = datetime.strptime(date, DATE_FORMAT) + def __init__(self, date: str, comment: str = '') -> None: + self.date = valid_date(date) + self.datetime = datetime.strptime(self.date, DATE_FORMAT) + self.comment = comment + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) and self.date == other.date + + def __lt__(self, other: Day) -> bool: + return self.date < other.date + + @classmethod + def from_table_row(cls, row: Row) -> Day: + """Make Day from database row.""" + return cls(row[0], row[1]) + + @classmethod + def all(cls, db_conn: DatabaseConnection, + date_range: tuple[str, str] = ('', ''), + fill_gaps: bool = False) -> list[Day]: + """Return list of Days in database within date_range.""" + min_date = '2024-01-01' + max_date = '2030-12-31' + start_date = valid_date(date_range[0] if date_range[0] else min_date) + end_date = valid_date(date_range[1] if date_range[1] else max_date) + days = [] + sql = 'SELECT * FROM days WHERE date >= ? AND date <= ?' + for row in db_conn.exec(sql, (start_date, end_date)): + days += [cls.from_table_row(row)] + days.sort() + if fill_gaps and len(days) > 1: + gapless_days = [] + for i, day in enumerate(days): + gapless_days += [day] + if i < len(days) - 1: + while day.next_date != days[i+1].date: + day = Day(day.next_date) + gapless_days += [day] + days = gapless_days + return days + + @classmethod + def by_date(cls, db_conn: DatabaseConnection, + date: str, create: bool = False) -> Day: + """Retrieve Day by date if in DB, else return None.""" + for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)): + return cls.from_table_row(row) + if not create: + raise NotFoundException(f'Day not found for date: {date}') + return cls(date) @property - def weekday(self): + def weekday(self) -> str: """Return what weekday matches self.date.""" return self.datetime.strftime('%A') - def __eq__(self, other: object): - return isinstance(other, self.__class__) and self.date == other.date + @property + def prev_date(self) -> str: + """Return date preceding date of this Day.""" + prev_datetime = self.datetime - timedelta(days=1) + return prev_datetime.strftime(DATE_FORMAT) - def __lt__(self, other): - return self.date < other.date + @property + def next_date(self) -> str: + """Return date succeeding date of this Day.""" + next_datetime = self.datetime + timedelta(days=1) + return next_datetime.strftime(DATE_FORMAT) + + def save(self, db_conn: DatabaseConnection) -> None: + """Add (or re-write) self to database.""" + db_conn.exec('REPLACE INTO days VALUES (?, ?)', + (self.date, self.comment))