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']
37 can_create_by_id = True
39 def __init__(self, id_: int | None, calendarize: bool = False) -> None:
40 BaseModel.__init__(self, id_)
41 ConditionsRelations.__init__(self)
42 self.title = VersionedAttribute(self, 'process_titles', 'UNNAMED')
43 self.description = VersionedAttribute(self, 'process_descriptions', '')
44 self.effort = VersionedAttribute(self, 'process_efforts', 1.0)
45 self.explicit_steps: list[ProcessStep] = []
46 self.suppressed_steps: list[ProcessStep] = []
47 self.calendarize = calendarize
48 self.n_owners: int | None = None # only set by from_table_row
51 def as_dict(self) -> dict[str, object]:
52 """Return self as (json.dumps-coompatible) dict."""
54 assert isinstance(d['_library'], dict)
55 d['explicit_steps'] = [s.as_dict_into_reference(d['_library'])
56 for s in self.explicit_steps]
60 def from_table_row(cls, db_conn: DatabaseConnection,
61 row: Row | list[Any]) -> Process:
62 """Make from DB row, with dependencies."""
63 process = super().from_table_row(db_conn, row)
64 assert process.id_ is not None
65 for name in ('conditions', 'blockers', 'enables', 'disables'):
66 table = f'process_{name}'
67 assert isinstance(process.id_, int)
68 for c_id in db_conn.column_where(table, 'condition',
69 'process', process.id_):
70 target = getattr(process, name)
71 target += [Condition.by_id(db_conn, c_id)]
72 for row_ in db_conn.row_where('process_steps', 'owner', process.id_):
73 step = ProcessStep.from_table_row(db_conn, row_)
74 process.explicit_steps += [step]
75 for row_ in db_conn.row_where('process_step_suppressions', 'process',
77 step = ProcessStep.by_id(db_conn, row_[1])
78 process.suppressed_steps += [step]
79 process.n_owners = len(process.used_as_step_by(db_conn))
82 def used_as_step_by(self, db_conn: DatabaseConnection) -> list[Process]:
83 """Return Processes using self for a ProcessStep."""
87 for id_ in db_conn.column_where('process_steps', 'owner',
88 'step_process', self.id_):
90 return [self.__class__.by_id(db_conn, id_) for id_ in owner_ids]
92 def get_steps(self, db_conn: DatabaseConnection, external_owner:
93 Process | None = None) -> dict[int, ProcessStepsNode]:
94 """Return tree of depended-on explicit and implicit ProcessSteps."""
96 def make_node(step: ProcessStep, suppressed: bool) -> ProcessStepsNode:
98 if external_owner is not None:
99 is_explicit = step.owner_id == external_owner.id_
100 process = self.__class__.by_id(db_conn, step.step_process_id)
103 step_steps = process.get_steps(db_conn, external_owner)
104 return ProcessStepsNode(process, step.parent_step_id,
105 is_explicit, step_steps, False, suppressed)
107 def walk_steps(node_id: int, node: ProcessStepsNode) -> None:
108 node.seen = node_id in seen_step_ids
109 seen_step_ids.add(node_id)
110 if node.is_suppressed:
112 explicit_children = [s for s in self.explicit_steps
113 if s.parent_step_id == node_id]
114 for child in explicit_children:
115 assert isinstance(child.id_, int)
116 node.steps[child.id_] = make_node(child, False)
117 for id_, step in node.steps.items():
118 walk_steps(id_, step)
120 steps: dict[int, ProcessStepsNode] = {}
121 seen_step_ids: Set[int] = set()
122 if external_owner is None:
123 external_owner = self
124 for step in [s for s in self.explicit_steps
125 if s.parent_step_id is None]:
126 assert isinstance(step.id_, int)
127 new_node = make_node(step, step in external_owner.suppressed_steps)
128 steps[step.id_] = new_node
129 for step_id, step_node in steps.items():
130 walk_steps(step_id, step_node)
133 def set_step_suppressions(self, db_conn: DatabaseConnection,
134 step_ids: list[int]) -> None:
135 """Set self.suppressed_steps from step_ids."""
136 assert isinstance(self.id_, int)
137 db_conn.delete_where('process_step_suppressions', 'process', self.id_)
138 self.suppressed_steps = [ProcessStep.by_id(db_conn, s)
141 def set_steps(self, db_conn: DatabaseConnection,
142 steps: list[ProcessStep]) -> None:
143 """Set self.explicit_steps in bulk.
145 Checks against recursion, and turns into top-level steps any of
146 unknown or non-owned parent.
148 def walk_steps(node: ProcessStep) -> None:
149 if node.step_process_id == self.id_:
150 raise BadFormatException('bad step selection causes recursion')
151 step_process = self.by_id(db_conn, node.step_process_id)
152 for step in step_process.explicit_steps:
155 assert isinstance(self.id_, int)
156 for step in [s for s in self.explicit_steps if s not in steps]:
158 for step in [s for s in steps if s not in self.explicit_steps]:
159 if step.parent_step_id is not None:
161 parent_step = ProcessStep.by_id(db_conn,
163 if parent_step.owner_id != self.id_:
164 step.parent_step_id = None
165 except NotFoundException:
166 step.parent_step_id = None
170 def set_owners(self, db_conn: DatabaseConnection,
171 owner_ids: list[int]) -> None:
172 """Re-set owners to those identified in owner_ids."""
173 owners_old = self.used_as_step_by(db_conn)
174 losers = [o for o in owners_old if o.id_ not in owner_ids]
175 owners_old_ids = [o.id_ for o in owners_old]
176 winners = [Process.by_id(db_conn, id_) for id_ in owner_ids
177 if id_ not in owners_old_ids]
180 steps_to_remove += [s for s in loser.explicit_steps
181 if s.step_process_id == self.id_]
182 for step in steps_to_remove:
184 for winner in winners:
185 assert isinstance(winner.id_, int)
186 assert isinstance(self.id_, int)
187 new_step = ProcessStep(None, winner.id_, self.id_, None)
188 new_explicit_steps = winner.explicit_steps + [new_step]
189 winner.set_steps(db_conn, new_explicit_steps)
191 def save(self, db_conn: DatabaseConnection) -> None:
192 """Add (or re-write) self and connected items to DB."""
193 super().save(db_conn)
194 assert isinstance(self.id_, int)
195 db_conn.delete_where('process_steps', 'owner', self.id_)
196 for step in self.explicit_steps:
199 def remove(self, db_conn: DatabaseConnection) -> None:
200 """Remove from DB, with dependencies.
202 Guard against removal of Processes in use.
204 assert isinstance(self.id_, int)
205 for _ in db_conn.row_where('process_steps', 'step_process', self.id_):
206 raise HandledException('cannot remove Process in use')
207 for _ in db_conn.row_where('todos', 'process', self.id_):
208 raise HandledException('cannot remove Process in use')
209 for step in self.explicit_steps:
211 super().remove(db_conn)
214 class ProcessStep(BaseModel[int]):
215 """Sub-unit of Processes."""
216 table_name = 'process_steps'
217 to_save = ['owner_id', 'step_process_id', 'parent_step_id']
219 def __init__(self, id_: int | None, owner_id: int, step_process_id: int,
220 parent_step_id: int | None) -> None:
221 super().__init__(id_)
222 self.owner_id = owner_id
223 self.step_process_id = step_process_id
224 self.parent_step_id = parent_step_id
226 def save(self, db_conn: DatabaseConnection) -> None:
227 """Update into DB/cache, and owner's .explicit_steps."""
228 super().save(db_conn)
229 owner = Process.by_id(db_conn, self.owner_id)
230 if self not in owner.explicit_steps:
231 for s in [s for s in owner.explicit_steps if s.id_ == self.id_]:
233 owner.explicit_steps += [self]
234 owner.explicit_steps.sort(key=hash)
236 def remove(self, db_conn: DatabaseConnection) -> None:
237 """Remove from DB, and owner's .explicit_steps."""
238 owner = Process.by_id(db_conn, self.owner_id)
239 owner.explicit_steps.remove(self)
240 super().remove(db_conn)