home · contact · privacy
Refactor database management code a little bit.
[plomtask] / plomtask / days.py
index d7083b4310bf76c168f6f33d29cf55c8ada7a29f..155ed03aabdbddacdf481267c04aa9d5a0fc29c0 100644 (file)
@@ -1,6 +1,9 @@
 """Collecting Day and date-related items."""
 from __future__ import annotations
+from typing import Any
+from sqlite3 import Row
 from datetime import datetime, timedelta
+from plomtask.exceptions import HandledException
 from plomtask.db import DatabaseConnection, BaseModel
 from plomtask.todos import Todo
 from plomtask.dating import (DATE_FORMAT, valid_date)
@@ -11,42 +14,73 @@ class Day(BaseModel[str]):
     table_name = 'days'
     to_save = ['comment']
 
-    def __init__(self, date: str, comment: str = '') -> None:
+    def __init__(self,
+                 date: str,
+                 comment: str = '',
+                 init_empty_todo_list: bool = False
+                 ) -> None:
         id_ = valid_date(date)
         super().__init__(id_)
         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
         self.comment = comment
-        self.calendarized_todos: list[Todo] = []
+        self._todos: list[Todo] | None = [] if init_empty_todo_list else None
 
     def __lt__(self, other: Day) -> bool:
         return self.date < other.date
 
     @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 (open) date_range interval.
-
-        On fill_gaps=True, will instantiate (without saving) Days of all dates
-        within the date range that don't exist yet.
-        """
-        ret = cls.by_date_range_with_limits(db_conn, date_range, 'id')
+    def from_table_row(cls, db_conn: DatabaseConnection, row: Row | list[Any]
+                       ) -> Day:
+        """Make from DB row, with linked Todos."""
+        # pylint: disable=protected-access
+        # (since on ._todo we're only meddling within cls)
+        day = super().from_table_row(db_conn, row)
+        assert isinstance(day.id_, str)
+        day._todos = Todo.by_date(db_conn, day.id_)
+        return day
+
+    @classmethod
+    def by_id(cls,
+              db_conn: DatabaseConnection, id_: str | None,
+              create: bool = False,
+              init_empty_todo_list: bool = False
+              ) -> Day:
+        """Extend BaseModel.by_id with init_empty_todo_list flag."""
+        # pylint: disable=protected-access
+        # (since on ._todo we're only meddling within cls)
+        day = super().by_id(db_conn, id_, create)
+        if init_empty_todo_list and day._todos is None:
+            day._todos = []
+        return day
+
+    @classmethod
+    def by_date_range_filled(cls, db_conn: DatabaseConnection,
+                             start: str, end: str) -> list[Day]:
+        """Return days existing and non-existing between dates start/end."""
+        ret = cls.by_date_range_with_limits(db_conn, (start, end), 'id')
         days, start_date, end_date = ret
+        return cls.with_filled_gaps(days, start_date, end_date)
+
+    @classmethod
+    def with_filled_gaps(cls, days: list[Day], start_date: str, end_date: str
+                         ) -> list[Day]:
+        """In days, fill with (un-saved) Days gaps between start/end_date."""
+        if start_date > end_date:
+            return days
         days.sort()
-        if fill_gaps:
-            if start_date not in [d.date for d in days]:
-                days = [Day(start_date)] + days
-            if end_date not in [d.date for d in days]:
-                days += [Day(end_date)]
-            if 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
+        if start_date not in [d.date for d in days]:
+            days[:] = [Day(start_date, init_empty_todo_list=True)] + days
+        if end_date not in [d.date for d in days]:
+            days += [Day(end_date, init_empty_todo_list=True)]
+        if 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, init_empty_todo_list=True)
+                        gapless_days += [day]
+            days[:] = gapless_days
         return days
 
     @property
@@ -83,7 +117,23 @@ class Day(BaseModel[str]):
         next_datetime = self.datetime + timedelta(days=1)
         return next_datetime.strftime(DATE_FORMAT)
 
-    def collect_calendarized_todos(self, db_conn: DatabaseConnection) -> None:
-        """Fill self.calendarized_todos."""
-        self.calendarized_todos = [t for t in Todo.by_date(db_conn, self.date)
-                                   if t.calendarize]
+    @property
+    def todos(self) -> list[Todo]:
+        """Return self.todos if initialized, else raise Exception."""
+        if self._todos is None:
+            msg = 'Trying to return from un-initialized Day.todos.'
+            raise HandledException(msg)
+        return list(self._todos)
+
+    @property
+    def calendarized_todos(self) -> list[Todo]:
+        """Return only those of self.todos that have .calendarize set."""
+        return [t for t in self.todos if t.calendarize]
+
+    @property
+    def total_effort(self) -> float:
+        """"Sum all .performed_effort of self.todos."""
+        total_effort = 0.0
+        for todo in self.todos:
+            total_effort += todo.performed_effort
+        return total_effort