home · contact · privacy
a45260092fdc6c75a94846eb0893b775eb9316dd
[plomtask] / plomtask / conditions.py
1 """Non-doable elements of ProcessStep/Todo chains."""
2 from __future__ import annotations
3 from typing import Any
4 from sqlite3 import Row
5 from plomtask.db import DatabaseConnection, BaseModel
6 from plomtask.misc import VersionedAttribute
7
8
9 class Condition(BaseModel[int]):
10     """Non-Process dependency for ProcessSteps and Todos."""
11     table_name = 'conditions'
12     to_save = ['is_active']
13
14     def __init__(self, id_: int | None, is_active: bool = False) -> None:
15         super().__init__(id_)
16         self.is_active = is_active
17         self.title = VersionedAttribute(self, 'condition_titles', 'UNNAMED')
18         self.description = VersionedAttribute(self, 'condition_descriptions',
19                                               '')
20
21     @classmethod
22     def from_table_row(cls, db_conn: DatabaseConnection,
23                        row: Row | list[Any]) -> Condition:
24         """Build condition from row, including VersionedAttributes."""
25         condition = super().from_table_row(db_conn, row)
26         for name in ('title', 'description'):
27             table_name = f'condition_{name}s'
28             for row_ in db_conn.row_where(table_name, 'parent', row[0]):
29                 getattr(condition, name).history_from_row(row_)
30         return condition
31
32     def save(self, db_conn: DatabaseConnection) -> None:
33         """Save self and its VersionedAttributes to DB and cache."""
34         self.save_core(db_conn)
35         self.title.save(db_conn)
36         self.description.save(db_conn)
37
38
39 class ConditionsRelations:
40     """Methods for handling relations to Conditions, for Todo and Process."""
41
42     def set_conditions(self, db_conn: DatabaseConnection, ids: list[int],
43                        target: str = 'conditions') -> None:
44         """Set self.[target] to Conditions identified by ids."""
45         target_list = getattr(self, target)
46         while len(target_list) > 0:
47             target_list.pop()
48         for id_ in ids:
49             target_list += [Condition.by_id(db_conn, id_)]
50
51     def set_enables(self, db_conn: DatabaseConnection,
52                     ids: list[int]) -> None:
53         """Set self.enables to Conditions identified by ids."""
54         self.set_conditions(db_conn, ids, 'enables')
55
56     def set_disables(self, db_conn: DatabaseConnection,
57                      ids: list[int]) -> None:
58         """Set self.disables to Conditions identified by ids."""
59         self.set_conditions(db_conn, ids, 'disables')