home · contact · privacy
d007d0f0ff14303e7668146323f0b2384a35cf55
[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     to_search = ['title.newest', 'description.newest']
37     can_create_by_id = True
38
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
49
50     @property
51     def as_dict(self) -> dict[str, object]:
52         """Return self as (json.dumps-coompatible) dict."""
53         d = super().as_dict
54         d['explicit_steps'] = [s.as_dict for s in self.explicit_steps]
55         d['suppressed_steps'] = [s.as_dict for s in self.suppressed_steps]
56         return d
57
58     @classmethod
59     def from_table_row(cls, db_conn: DatabaseConnection,
60                        row: Row | list[Any]) -> Process:
61         """Make from DB row, with dependencies."""
62         process = super().from_table_row(db_conn, row)
63         assert process.id_ is not None
64         for name in ('conditions', 'blockers', 'enables', 'disables'):
65             table = f'process_{name}'
66             assert isinstance(process.id_, int)
67             for c_id in db_conn.column_where(table, 'condition',
68                                              'process', process.id_):
69                 target = getattr(process, name)
70                 target += [Condition.by_id(db_conn, c_id)]
71         for row_ in db_conn.row_where('process_steps', 'owner', process.id_):
72             step = ProcessStep.from_table_row(db_conn, row_)
73             process.explicit_steps += [step]
74         for row_ in db_conn.row_where('process_step_suppressions', 'process',
75                                       process.id_):
76             step = ProcessStep.by_id(db_conn, row_[1])
77             process.suppressed_steps += [step]
78         process.n_owners = len(process.used_as_step_by(db_conn))
79         return process
80
81     def used_as_step_by(self, db_conn: DatabaseConnection) -> list[Process]:
82         """Return Processes using self for a ProcessStep."""
83         if not self.id_:
84             return []
85         owner_ids = set()
86         for id_ in db_conn.column_where('process_steps', 'owner',
87                                         'step_process', self.id_):
88             owner_ids.add(id_)
89         return [self.__class__.by_id(db_conn, id_) for id_ in owner_ids]
90
91     def get_steps(self, db_conn: DatabaseConnection, external_owner:
92                   Process | None = None) -> dict[int, ProcessStepsNode]:
93         """Return tree of depended-on explicit and implicit ProcessSteps."""
94
95         def make_node(step: ProcessStep, suppressed: bool) -> ProcessStepsNode:
96             is_explicit = False
97             if external_owner is not None:
98                 is_explicit = step.owner_id == external_owner.id_
99             process = self.__class__.by_id(db_conn, step.step_process_id)
100             step_steps = {}
101             if not suppressed:
102                 step_steps = process.get_steps(db_conn, external_owner)
103             return ProcessStepsNode(process, step.parent_step_id,
104                                     is_explicit, step_steps, False, suppressed)
105
106         def walk_steps(node_id: int, node: ProcessStepsNode) -> None:
107             node.seen = node_id in seen_step_ids
108             seen_step_ids.add(node_id)
109             if node.is_suppressed:
110                 return
111             explicit_children = [s for s in self.explicit_steps
112                                  if s.parent_step_id == node_id]
113             for child in explicit_children:
114                 assert isinstance(child.id_, int)
115                 node.steps[child.id_] = make_node(child, False)
116             for id_, step in node.steps.items():
117                 walk_steps(id_, step)
118
119         steps: dict[int, ProcessStepsNode] = {}
120         seen_step_ids: Set[int] = set()
121         if external_owner is None:
122             external_owner = self
123         for step in [s for s in self.explicit_steps
124                      if s.parent_step_id is None]:
125             assert isinstance(step.id_, int)
126             new_node = make_node(step, step in external_owner.suppressed_steps)
127             steps[step.id_] = new_node
128         for step_id, step_node in steps.items():
129             walk_steps(step_id, step_node)
130         return steps
131
132     def set_step_suppressions(self, db_conn: DatabaseConnection,
133                               step_ids: list[int]) -> None:
134         """Set self.suppressed_steps from step_ids."""
135         assert isinstance(self.id_, int)
136         db_conn.delete_where('process_step_suppressions', 'process', self.id_)
137         self.suppressed_steps = [ProcessStep.by_id(db_conn, s)
138                                  for s in step_ids]
139
140     def set_steps(self, db_conn: DatabaseConnection,
141                   steps: list[ProcessStep]) -> None:
142         """Set self.explicit_steps in bulk.
143
144         Checks against recursion, and turns into top-level steps any of
145         unknown or non-owned parent.
146         """
147         def walk_steps(node: ProcessStep) -> None:
148             if node.step_process_id == self.id_:
149                 raise BadFormatException('bad step selection causes recursion')
150             step_process = self.by_id(db_conn, node.step_process_id)
151             for step in step_process.explicit_steps:
152                 walk_steps(step)
153
154         assert isinstance(self.id_, int)
155         for step in [s for s in self.explicit_steps if s not in steps]:
156             step.remove(db_conn)
157         for step in [s for s in steps if s not in self.explicit_steps]:
158             if step.parent_step_id is not None:
159                 try:
160                     parent_step = ProcessStep.by_id(db_conn,
161                                                     step.parent_step_id)
162                     if parent_step.owner_id != self.id_:
163                         step.parent_step_id = None
164                 except NotFoundException:
165                     step.parent_step_id = None
166             walk_steps(step)
167             step.save(db_conn)
168
169     def set_owners(self, db_conn: DatabaseConnection,
170                    owner_ids: list[int]) -> None:
171         """Re-set owners to those identified in owner_ids."""
172         owners_old = self.used_as_step_by(db_conn)
173         losers = [o for o in owners_old if o.id_ not in owner_ids]
174         owners_old_ids = [o.id_ for o in owners_old]
175         winners = [Process.by_id(db_conn, id_) for id_ in owner_ids
176                    if id_ not in owners_old_ids]
177         steps_to_remove = []
178         for loser in losers:
179             steps_to_remove += [s for s in loser.explicit_steps
180                                 if s.step_process_id == self.id_]
181         for step in steps_to_remove:
182             step.remove(db_conn)
183         for winner in winners:
184             assert isinstance(winner.id_, int)
185             assert isinstance(self.id_, int)
186             new_step = ProcessStep(None, winner.id_, self.id_, None)
187             new_explicit_steps = winner.explicit_steps + [new_step]
188             winner.set_steps(db_conn, new_explicit_steps)
189
190     def save(self, db_conn: DatabaseConnection) -> None:
191         """Add (or re-write) self and connected items to DB."""
192         super().save(db_conn)
193         assert isinstance(self.id_, int)
194         db_conn.delete_where('process_steps', 'owner', self.id_)
195         for step in self.explicit_steps:
196             step.save(db_conn)
197
198     def remove(self, db_conn: DatabaseConnection) -> None:
199         """Remove from DB, with dependencies.
200
201         Guard against removal of Processes in use.
202         """
203         assert isinstance(self.id_, int)
204         for _ in db_conn.row_where('process_steps', 'step_process', self.id_):
205             raise HandledException('cannot remove Process in use')
206         for _ in db_conn.row_where('todos', 'process', self.id_):
207             raise HandledException('cannot remove Process in use')
208         for step in self.explicit_steps:
209             step.remove(db_conn)
210         super().remove(db_conn)
211
212
213 class ProcessStep(BaseModel[int]):
214     """Sub-unit of Processes."""
215     table_name = 'process_steps'
216     to_save = ['owner_id', 'step_process_id', 'parent_step_id']
217
218     def __init__(self, id_: int | None, owner_id: int, step_process_id: int,
219                  parent_step_id: int | None) -> None:
220         super().__init__(id_)
221         self.owner_id = owner_id
222         self.step_process_id = step_process_id
223         self.parent_step_id = parent_step_id
224
225     def save(self, db_conn: DatabaseConnection) -> None:
226         """Update into DB/cache, and owner's .explicit_steps."""
227         super().save(db_conn)
228         owner = Process.by_id(db_conn, self.owner_id)
229         if self not in owner.explicit_steps:
230             for s in [s for s in owner.explicit_steps if s.id_ == self.id_]:
231                 s.remove(db_conn)
232             owner.explicit_steps += [self]
233         owner.explicit_steps.sort(key=hash)
234
235     def remove(self, db_conn: DatabaseConnection) -> None:
236         """Remove from DB, and owner's .explicit_steps."""
237         owner = Process.by_id(db_conn, self.owner_id)
238         owner.explicit_steps.remove(self)
239         super().remove(db_conn)