home · contact · privacy
Re-factor Day.todos code.
[plomtask] / plomtask / days.py
index 2531a011f1875a4819337adcd7e59c7a08355af4..155ed03aabdbddacdf481267c04aa9d5a0fc29c0 100644 (file)
@@ -23,7 +23,7 @@ class Day(BaseModel[str]):
         super().__init__(id_)
         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
         self.comment = comment
-        self.todos: list[Todo] | None = [] if init_empty_todo_list else None
+        self._todos: list[Todo] | None = [] if init_empty_todo_list else None
 
     def __lt__(self, other: Day) -> bool:
         return self.date < other.date
@@ -32,9 +32,25 @@ class Day(BaseModel[str]):
     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_)
+        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
@@ -102,11 +118,22 @@ class Day(BaseModel[str]):
         return next_datetime.strftime(DATE_FORMAT)
 
     @property
-    def calendarized_todos(self) -> list[Todo]:
-        """Return only those of self.todos that have .calendarize set."""
-        if self.todos is None:
+    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)
-        # pylint: disable=not-an-iterable
-        # (after the above is-None test, self.todos _should_ be iterable!)
+        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