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,
14 class ProcessStepsNode:
15 """Collects what's useful to know for ProcessSteps tree display."""
19 steps: dict[int, ProcessStepsNode]
21 is_suppressed: bool = False
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 to_search = ['title.newest', 'description.newest']
38 def __init__(self, id_: int | None, calendarize: bool = False) -> None:
39 BaseModel.__init__(self, id_)
40 ConditionsRelations.__init__(self)
41 self.title = VersionedAttribute(self, 'process_titles', 'UNNAMED')
42 self.description = VersionedAttribute(self, 'process_descriptions', '')
43 self.effort = VersionedAttribute(self, 'process_efforts', 1.0)
44 self.explicit_steps: list[ProcessStep] = []
45 self.suppressed_steps: list[ProcessStep] = []
46 self.calendarize = calendarize
47 self.n_owners: int | None = None # only set by from_table_row
50 def from_table_row(cls, db_conn: DatabaseConnection,
51 row: Row | list[Any]) -> Process:
52 """Make from DB row, with dependencies."""
53 process = super().from_table_row(db_conn, row)
54 assert isinstance(process.id_, int)
55 for name in ('title', 'description', 'effort'):
56 table = f'process_{name}s'
57 for row_ in db_conn.row_where(table, 'parent', process.id_):
58 getattr(process, name).history_from_row(row_)
59 for name in ('conditions', 'blockers', 'enables', 'disables'):
60 table = f'process_{name}'
61 assert isinstance(process.id_, int)
62 for c_id in db_conn.column_where(table, 'condition',
63 'process', process.id_):
64 target = getattr(process, name)
65 target += [Condition.by_id(db_conn, c_id)]
66 for row_ in db_conn.row_where('process_steps', 'owner', process.id_):
67 step = ProcessStep.from_table_row(db_conn, row_)
68 process.explicit_steps += [step]
69 for row_ in db_conn.row_where('process_step_suppressions', 'process',
71 step = ProcessStep.by_id(db_conn, row_[1])
72 process.suppressed_steps += [step]
73 process.n_owners = len(process.used_as_step_by(db_conn))
76 def used_as_step_by(self, db_conn: DatabaseConnection) -> list[Process]:
77 """Return Processes using self for a ProcessStep."""
81 for id_ in db_conn.column_where('process_steps', 'owner',
82 'step_process', self.id_):
84 return [self.__class__.by_id(db_conn, id_) for id_ in owner_ids]
86 def get_steps(self, db_conn: DatabaseConnection, external_owner:
87 Process | None = None) -> dict[int, ProcessStepsNode]:
88 """Return tree of depended-on explicit and implicit ProcessSteps."""
90 def make_node(step: ProcessStep, suppressed: bool) -> ProcessStepsNode:
92 if external_owner is not None:
93 is_explicit = step.owner_id == external_owner.id_
94 process = self.__class__.by_id(db_conn, step.step_process_id)
97 step_steps = process.get_steps(db_conn, external_owner)
98 return ProcessStepsNode(process, step.parent_step_id,
99 is_explicit, step_steps, False, suppressed)
101 def walk_steps(node_id: int, node: ProcessStepsNode) -> None:
102 node.seen = node_id in seen_step_ids
103 seen_step_ids.add(node_id)
104 if node.is_suppressed:
106 explicit_children = [s for s in self.explicit_steps
107 if s.parent_step_id == node_id]
108 for child in explicit_children:
109 assert isinstance(child.id_, int)
110 node.steps[child.id_] = make_node(child, False)
111 for id_, step in node.steps.items():
112 walk_steps(id_, step)
114 steps: dict[int, ProcessStepsNode] = {}
115 seen_step_ids: Set[int] = set()
116 if external_owner is None:
117 external_owner = self
118 for step in [s for s in self.explicit_steps
119 if s.parent_step_id is None]:
120 assert isinstance(step.id_, int)
121 new_node = make_node(step, step in external_owner.suppressed_steps)
122 steps[step.id_] = new_node
123 for step_id, step_node in steps.items():
124 walk_steps(step_id, step_node)
127 def set_step_suppressions(self, db_conn: DatabaseConnection,
128 step_ids: list[int]) -> None:
129 """Set self.suppressed_steps from step_ids."""
130 assert isinstance(self.id_, int)
131 db_conn.delete_where('process_step_suppressions', 'process', self.id_)
132 self.suppressed_steps = [ProcessStep.by_id(db_conn, s)
135 def set_steps(self, db_conn: DatabaseConnection,
136 steps: list[ProcessStep]) -> None:
137 """Set self.explicit_steps in bulk.
139 Checks against recursion, and turns into top-level steps any of
140 unknown or non-owned parent.
142 def walk_steps(node: ProcessStep) -> None:
143 if node.step_process_id == self.id_:
144 raise BadFormatException('bad step selection causes recursion')
145 step_process = self.by_id(db_conn, node.step_process_id)
146 for step in step_process.explicit_steps:
149 assert isinstance(self.id_, int)
150 for step in [s for s in self.explicit_steps if s not in steps]:
152 for step in [s for s in steps if s not in self.explicit_steps]:
153 if step.parent_step_id is not None:
155 parent_step = ProcessStep.by_id(db_conn,
157 if parent_step.owner_id != self.id_:
158 step.parent_step_id = None
159 except NotFoundException:
160 step.parent_step_id = None
164 def set_owners(self, db_conn: DatabaseConnection,
165 owner_ids: list[int]) -> None:
166 """Re-set owners to those identified in owner_ids."""
167 owners_old = self.used_as_step_by(db_conn)
168 losers = [o for o in owners_old if o.id_ not in owner_ids]
169 owners_old_ids = [o.id_ for o in owners_old]
170 winners = [Process.by_id(db_conn, id_) for id_ in owner_ids
171 if id_ not in owners_old_ids]
174 steps_to_remove += [s for s in loser.explicit_steps
175 if s.step_process_id == self.id_]
176 for step in steps_to_remove:
178 for winner in winners:
179 assert isinstance(winner.id_, int)
180 assert isinstance(self.id_, int)
181 new_step = ProcessStep(None, winner.id_, self.id_, None)
182 new_explicit_steps = winner.explicit_steps + [new_step]
183 winner.set_steps(db_conn, new_explicit_steps)
185 def save(self, db_conn: DatabaseConnection) -> None:
186 """Add (or re-write) self and connected items to DB."""
187 super().save(db_conn)
188 assert isinstance(self.id_, int)
189 db_conn.delete_where('process_steps', 'owner', self.id_)
190 for step in self.explicit_steps:
193 def remove(self, db_conn: DatabaseConnection) -> None:
194 """Remove from DB, with dependencies.
196 Guard against removal of Processes in use.
198 assert isinstance(self.id_, int)
199 for _ in db_conn.row_where('process_steps', 'step_process', self.id_):
200 raise HandledException('cannot remove Process in use')
201 for _ in db_conn.row_where('todos', 'process', self.id_):
202 raise HandledException('cannot remove Process in use')
203 for step in self.explicit_steps:
205 super().remove(db_conn)
208 class ProcessStep(BaseModel[int]):
209 """Sub-unit of Processes."""
210 table_name = 'process_steps'
211 to_save = ['owner_id', 'step_process_id', 'parent_step_id']
213 def __init__(self, id_: int | None, owner_id: int, step_process_id: int,
214 parent_step_id: int | None) -> None:
215 super().__init__(id_)
216 self.owner_id = owner_id
217 self.step_process_id = step_process_id
218 self.parent_step_id = parent_step_id
220 def save(self, db_conn: DatabaseConnection) -> None:
221 """Remove from DB, and owner's .explicit_steps."""
222 super().save(db_conn)
223 owner = Process.by_id(db_conn, self.owner_id)
224 if self not in owner.explicit_steps:
225 for s in [s for s in owner.explicit_steps if s.id_ == self.id_]:
227 owner.explicit_steps += [self]
228 owner.explicit_steps.sort(key=hash)
230 def remove(self, db_conn: DatabaseConnection) -> None:
231 """Remove from DB, and owner's .explicit_steps."""
232 owner = Process.by_id(db_conn, self.owner_id)
233 owner.explicit_steps.remove(self)
234 super().remove(db_conn)