home · contact · privacy
Refactor .as_dict integration of Process.explicit_steps, Day.todos.
[plomtask] / plomtask / processes.py
1 """Collecting Processes and Process-related items."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Set, Any
5 from sqlite3 import Row
6 from plomtask.db import DatabaseConnection, BaseModel
7 from plomtask.versioned_attributes import VersionedAttribute
8 from plomtask.conditions import Condition, ConditionsRelations
9 from plomtask.exceptions import (NotFoundException, BadFormatException,
10                                  HandledException)
11
12
13 @dataclass
14 class ProcessStepsNode:
15     """Collects what's useful to know for ProcessSteps tree display."""
16     process: Process
17     parent_id: int | None
18     is_explicit: bool
19     steps: dict[int, ProcessStepsNode]
20     seen: bool = False
21     is_suppressed: bool = False
22
23
24 class Process(BaseModel[int], ConditionsRelations):
25     """Template for, and metadata for, Todos, and their arrangements."""
26     # pylint: disable=too-many-instance-attributes
27     table_name = 'processes'
28     to_save = ['calendarize']
29     to_save_versioned = ['title', 'description', 'effort']
30     to_save_relations = [('process_conditions', 'process', 'conditions', 0),
31                          ('process_blockers', 'process', 'blockers', 0),
32                          ('process_enables', 'process', 'enables', 0),
33                          ('process_disables', 'process', 'disables', 0),
34                          ('process_step_suppressions', 'process',
35                           'suppressed_steps', 0)]
36     add_to_dict = ['explicit_steps']
37     to_search = ['title.newest', 'description.newest']
38     can_create_by_id = True
39
40     def __init__(self, id_: int | None, calendarize: bool = False) -> None:
41         BaseModel.__init__(self, id_)
42         ConditionsRelations.__init__(self)
43         self.title = VersionedAttribute(self, 'process_titles', 'UNNAMED')
44         self.description = VersionedAttribute(self, 'process_descriptions', '')
45         self.effort = VersionedAttribute(self, 'process_efforts', 1.0)
46         self.explicit_steps: list[ProcessStep] = []
47         self.suppressed_steps: list[ProcessStep] = []
48         self.calendarize = calendarize
49         self.n_owners: int | None = None  # only set by from_table_row
50
51     @classmethod
52     def from_table_row(cls, db_conn: DatabaseConnection,
53                        row: Row | list[Any]) -> Process:
54         """Make from DB row, with dependencies."""
55         process = super().from_table_row(db_conn, row)
56         assert process.id_ is not None
57         for name in ('conditions', 'blockers', 'enables', 'disables'):
58             table = f'process_{name}'
59             assert isinstance(process.id_, int)
60             for c_id in db_conn.column_where(table, 'condition',
61                                              'process', process.id_):
62                 target = getattr(process, name)
63                 target += [Condition.by_id(db_conn, c_id)]
64         for row_ in db_conn.row_where('process_steps', 'owner', process.id_):
65             step = ProcessStep.from_table_row(db_conn, row_)
66             process.explicit_steps += [step]
67         for row_ in db_conn.row_where('process_step_suppressions', 'process',
68                                       process.id_):
69             step = ProcessStep.by_id(db_conn, row_[1])
70             process.suppressed_steps += [step]
71         process.n_owners = len(process.used_as_step_by(db_conn))
72         return process
73
74     def used_as_step_by(self, db_conn: DatabaseConnection) -> list[Process]:
75         """Return Processes using self for a ProcessStep."""
76         if not self.id_:
77             return []
78         owner_ids = set()
79         for id_ in db_conn.column_where('process_steps', 'owner',
80                                         'step_process', self.id_):
81             owner_ids.add(id_)
82         return [self.__class__.by_id(db_conn, id_) for id_ in owner_ids]
83
84     def get_steps(self, db_conn: DatabaseConnection, external_owner:
85                   Process | None = None) -> dict[int, ProcessStepsNode]:
86         """Return tree of depended-on explicit and implicit ProcessSteps."""
87
88         def make_node(step: ProcessStep, suppressed: bool) -> ProcessStepsNode:
89             is_explicit = False
90             if external_owner is not None:
91                 is_explicit = step.owner_id == external_owner.id_
92             process = self.__class__.by_id(db_conn, step.step_process_id)
93             step_steps = {}
94             if not suppressed:
95                 step_steps = process.get_steps(db_conn, external_owner)
96             return ProcessStepsNode(process, step.parent_step_id,
97                                     is_explicit, step_steps, False, suppressed)
98
99         def walk_steps(node_id: int, node: ProcessStepsNode) -> None:
100             node.seen = node_id in seen_step_ids
101             seen_step_ids.add(node_id)
102             if node.is_suppressed:
103                 return
104             explicit_children = [s for s in self.explicit_steps
105                                  if s.parent_step_id == node_id]
106             for child in explicit_children:
107                 assert isinstance(child.id_, int)
108                 node.steps[child.id_] = make_node(child, False)
109             for id_, step in node.steps.items():
110                 walk_steps(id_, step)
111
112         steps: dict[int, ProcessStepsNode] = {}
113         seen_step_ids: Set[int] = set()
114         if external_owner is None:
115             external_owner = self
116         for step in [s for s in self.explicit_steps
117                      if s.parent_step_id is None]:
118             assert isinstance(step.id_, int)
119             new_node = make_node(step, step in external_owner.suppressed_steps)
120             steps[step.id_] = new_node
121         for step_id, step_node in steps.items():
122             walk_steps(step_id, step_node)
123         return steps
124
125     def set_step_suppressions(self, db_conn: DatabaseConnection,
126                               step_ids: list[int]) -> None:
127         """Set self.suppressed_steps from step_ids."""
128         assert isinstance(self.id_, int)
129         db_conn.delete_where('process_step_suppressions', 'process', self.id_)
130         self.suppressed_steps = [ProcessStep.by_id(db_conn, s)
131                                  for s in step_ids]
132
133     def set_steps(self, db_conn: DatabaseConnection,
134                   steps: list[ProcessStep]) -> None:
135         """Set self.explicit_steps in bulk.
136
137         Checks against recursion, and turns into top-level steps any of
138         unknown or non-owned parent.
139         """
140         def walk_steps(node: ProcessStep) -> None:
141             if node.step_process_id == self.id_:
142                 raise BadFormatException('bad step selection causes recursion')
143             step_process = self.by_id(db_conn, node.step_process_id)
144             for step in step_process.explicit_steps:
145                 walk_steps(step)
146
147         assert isinstance(self.id_, int)
148         for step in [s for s in self.explicit_steps if s not in steps]:
149             step.remove(db_conn)
150         for step in [s for s in steps if s not in self.explicit_steps]:
151             if step.parent_step_id is not None:
152                 try:
153                     parent_step = ProcessStep.by_id(db_conn,
154                                                     step.parent_step_id)
155                     if parent_step.owner_id != self.id_:
156                         step.parent_step_id = None
157                 except NotFoundException:
158                     step.parent_step_id = None
159             walk_steps(step)
160             step.save(db_conn)
161
162     def set_owners(self, db_conn: DatabaseConnection,
163                    owner_ids: list[int]) -> None:
164         """Re-set owners to those identified in owner_ids."""
165         owners_old = self.used_as_step_by(db_conn)
166         losers = [o for o in owners_old if o.id_ not in owner_ids]
167         owners_old_ids = [o.id_ for o in owners_old]
168         winners = [Process.by_id(db_conn, id_) for id_ in owner_ids
169                    if id_ not in owners_old_ids]
170         steps_to_remove = []
171         for loser in losers:
172             steps_to_remove += [s for s in loser.explicit_steps
173                                 if s.step_process_id == self.id_]
174         for step in steps_to_remove:
175             step.remove(db_conn)
176         for winner in winners:
177             assert isinstance(winner.id_, int)
178             assert isinstance(self.id_, int)
179             new_step = ProcessStep(None, winner.id_, self.id_, None)
180             new_explicit_steps = winner.explicit_steps + [new_step]
181             winner.set_steps(db_conn, new_explicit_steps)
182
183     def save(self, db_conn: DatabaseConnection) -> None:
184         """Add (or re-write) self and connected items to DB."""
185         super().save(db_conn)
186         assert isinstance(self.id_, int)
187         db_conn.delete_where('process_steps', 'owner', self.id_)
188         for step in self.explicit_steps:
189             step.save(db_conn)
190
191     def remove(self, db_conn: DatabaseConnection) -> None:
192         """Remove from DB, with dependencies.
193
194         Guard against removal of Processes in use.
195         """
196         assert isinstance(self.id_, int)
197         for _ in db_conn.row_where('process_steps', 'step_process', self.id_):
198             raise HandledException('cannot remove Process in use')
199         for _ in db_conn.row_where('todos', 'process', self.id_):
200             raise HandledException('cannot remove Process in use')
201         for step in self.explicit_steps:
202             step.remove(db_conn)
203         super().remove(db_conn)
204
205
206 class ProcessStep(BaseModel[int]):
207     """Sub-unit of Processes."""
208     table_name = 'process_steps'
209     to_save = ['owner_id', 'step_process_id', 'parent_step_id']
210
211     def __init__(self, id_: int | None, owner_id: int, step_process_id: int,
212                  parent_step_id: int | None) -> None:
213         super().__init__(id_)
214         self.owner_id = owner_id
215         self.step_process_id = step_process_id
216         self.parent_step_id = parent_step_id
217
218     def save(self, db_conn: DatabaseConnection) -> None:
219         """Update into DB/cache, and owner's .explicit_steps."""
220         super().save(db_conn)
221         owner = Process.by_id(db_conn, self.owner_id)
222         if self not in owner.explicit_steps:
223             for s in [s for s in owner.explicit_steps if s.id_ == self.id_]:
224                 s.remove(db_conn)
225             owner.explicit_steps += [self]
226         owner.explicit_steps.sort(key=hash)
227
228     def remove(self, db_conn: DatabaseConnection) -> None:
229         """Remove from DB, and owner's .explicit_steps."""
230         owner = Process.by_id(db_conn, self.owner_id)
231         owner.explicit_steps.remove(self)
232         super().remove(db_conn)