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