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