home · contact · privacy
Minor refactorings.
[plomtask] / plomtask / days.py
index 8db9f15b7362ede61c70265e4d5eb8a4c2c0c626..89c957eef7ee49746e079d91ac3db3fa8d178760 100644 (file)
@@ -1,24 +1,71 @@
-#!/usr/bin/env python3
 """Collecting Day and date-related items."""
 from datetime import datetime
+from sqlite3 import Row
+from plomtask.misc import HandledException
+from plomtask.db import DatabaseConnection
 
 DATE_FORMAT = '%Y-%m-%d'
 
 
+def date_valid(date: str):
+    """Validate date against DATE_FORMAT, return Datetime or None."""
+    try:
+        result = datetime.strptime(date, DATE_FORMAT)
+    except (ValueError, TypeError):
+        return None
+    return result
+
+
 class Day:
     """Individual days defined by their dates."""
 
-    def __init__(self, date: str):
+    def __init__(self, date: str, comment: str = ''):
         self.date = date
-        self.datetime = datetime.strptime(date, DATE_FORMAT)
-
-    @property
-    def weekday(self):
-        """Return what weekday matches self.date."""
-        return self.datetime.strftime('%A')
+        self.datetime = date_valid(self.date)
+        if not self.datetime:
+            raise HandledException(f'Given date of wrong format: {self.date}')
+        self.comment = comment
 
     def __eq__(self, other: object):
         return isinstance(other, self.__class__) and self.date == other.date
 
     def __lt__(self, other):
         return self.date < other.date
+
+    @classmethod
+    def from_table_row(cls, row: Row):
+        """Make new Day from database row."""
+        return cls(row[0], row[1])
+
+    @classmethod
+    def all(cls, db_conn: DatabaseConnection,
+            date_range: tuple[str, str] = ('', '')):
+        """Return list of Days in database within date_range."""
+        start_date = date_range[0] if date_range[0] else '2024-01-01'
+        end_date = date_range[1] if date_range[1] else '2030-12-31'
+        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()
+        return days
+
+    @classmethod
+    def by_date(cls, db_conn: DatabaseConnection,
+                date: str, create: bool = False):
+        """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 create:
+            return cls(date)
+        return None
+
+    @property
+    def weekday(self):
+        """Return what weekday matches self.date."""
+        return self.datetime.strftime('%A')
+
+    def save(self, db_conn: DatabaseConnection):
+        """Add (or re-write) self to database."""
+        db_conn.exec('REPLACE INTO days VALUES (?, ?)',
+                     (self.date, self.comment))