home · contact · privacy
Add text-based search/filter for Conditions and Processes.
[plomtask] / plomtask / conditions.py
index 4b012491d6151ed74995849378fa8dc1c04f20f8..d2559272cd876c5b071b59437998e3356409cd07 100644 (file)
@@ -3,17 +3,19 @@ from __future__ import annotations
 from typing import Any
 from sqlite3 import Row
 from plomtask.db import DatabaseConnection, BaseModel
-from plomtask.misc import VersionedAttribute
-from plomtask.exceptions import NotFoundException
+from plomtask.versioned_attributes import VersionedAttribute
+from plomtask.exceptions import HandledException
 
 
 class Condition(BaseModel[int]):
-    """Non Process-dependency for ProcessSteps and Todos."""
+    """Non-Process dependency for ProcessSteps and Todos."""
     table_name = 'conditions'
     to_save = ['is_active']
+    to_save_versioned = ['title', 'description']
+    to_search = ['title.newest', 'description.newest']
 
     def __init__(self, id_: int | None, is_active: bool = False) -> None:
-        self.set_int_id(id_)
+        super().__init__(id_)
         self.is_active = is_active
         self.title = VersionedAttribute(self, 'condition_titles', 'UNNAMED')
         self.description = VersionedAttribute(self, 'condition_descriptions',
@@ -24,53 +26,37 @@ class Condition(BaseModel[int]):
                        row: Row | list[Any]) -> Condition:
         """Build condition from row, including VersionedAttributes."""
         condition = super().from_table_row(db_conn, row)
-        assert isinstance(condition, Condition)
         for name in ('title', 'description'):
             table_name = f'condition_{name}s'
             for row_ in db_conn.row_where(table_name, 'parent', row[0]):
                 getattr(condition, name).history_from_row(row_)
         return condition
 
-    @classmethod
-    def all(cls, db_conn: DatabaseConnection) -> list[Condition]:
-        """Collect all Conditions and their VersionedAttributes."""
-        conditions = {}
-        for id_, condition in cls.cache_.items():
-            conditions[id_] = condition
-        already_recorded = conditions.keys()
-        for id_ in db_conn.column_all('conditions', 'id'):
-            if id_ not in already_recorded:
-                condition = cls.by_id(db_conn, id_)
-                assert isinstance(condition.id_, int)
-                conditions[condition.id_] = condition
-        return list(conditions.values())
-
-    @classmethod
-    def by_id(cls, db_conn: DatabaseConnection, id_: int | None,
-              create: bool = False) -> Condition:
-        """Collect (or create) Condition and its VersionedAttributes."""
-        condition = None
-        if id_:
-            condition, _ = super()._by_id(db_conn, id_)
-        if not condition:
-            if not create:
-                raise NotFoundException(f'Condition not found of id: {id_}')
-            condition = cls(id_, False)
-            condition.save(db_conn)
-        assert isinstance(condition, Condition)
-        return condition
+    def remove(self, db_conn: DatabaseConnection) -> None:
+        """Remove from DB, with VersionedAttributes.
 
-    def save(self, db_conn: DatabaseConnection) -> None:
-        """Save self and its VersionedAttributes to DB and cache."""
-        self.save_core(db_conn)
-        self.title.save(db_conn)
-        self.description.save(db_conn)
-        assert isinstance(self.id_, int)
+        Checks for Todos and Processes that depend on Condition, prohibits
+        deletion if found.
+        """
+        if self.id_ is None:
+            raise HandledException('cannot remove unsaved item')
+        for item in ('process', 'todo'):
+            for attr in ('conditions', 'blockers', 'enables', 'disables'):
+                table_name = f'{item}_{attr}'
+                for _ in db_conn.row_where(table_name, 'condition', self.id_):
+                    raise HandledException('cannot remove Condition in use')
+        super().remove(db_conn)
 
 
 class ConditionsRelations:
     """Methods for handling relations to Conditions, for Todo and Process."""
 
+    def __init__(self) -> None:
+        self.conditions: list[Condition] = []
+        self.blockers: list[Condition] = []
+        self.enables: list[Condition] = []
+        self.disables: list[Condition] = []
+
     def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
                        target: str = 'conditions') -> None:
         """Set self.[target] to Conditions identified by ids."""
@@ -80,6 +66,11 @@ class ConditionsRelations:
         for id_ in ids:
             target_list += [Condition.by_id(db_conn, id_)]
 
+    def set_blockers(self, db_conn: DatabaseConnection,
+                     ids: list[int]) -> None:
+        """Set self.enables to Conditions identified by ids."""
+        self.set_conditions(db_conn, ids, 'blockers')
+
     def set_enables(self, db_conn: DatabaseConnection,
                     ids: list[int]) -> None:
         """Set self.enables to Conditions identified by ids."""