home · contact · privacy
Privatize more methods and attributes of TaskHandler.
[plomtask] / plomtask / http.py
1 """Web server stuff."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Any, Callable
5 from base64 import b64encode, b64decode
6 from http.server import BaseHTTPRequestHandler
7 from http.server import HTTPServer
8 from urllib.parse import urlparse, parse_qs
9 from os.path import split as path_split
10 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
11 from plomtask.dating import date_in_n_days
12 from plomtask.days import Day
13 from plomtask.exceptions import HandledException, BadFormatException, \
14         NotFoundException
15 from plomtask.db import DatabaseConnection, DatabaseFile
16 from plomtask.processes import Process, ProcessStep, ProcessStepsNode
17 from plomtask.conditions import Condition
18 from plomtask.todos import Todo
19
20 TEMPLATES_DIR = 'templates'
21
22
23 class TaskServer(HTTPServer):
24     """Variant of HTTPServer that knows .jinja as Jinja Environment."""
25
26     def __init__(self, db_file: DatabaseFile,
27                  *args: Any, **kwargs: Any) -> None:
28         super().__init__(*args, **kwargs)
29         self.db = db_file
30         self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
31
32
33 class InputsParser:
34     """Wrapper for validating and retrieving dict-like HTTP inputs."""
35
36     def __init__(self, dict_: dict[str, list[str]],
37                  strictness: bool = True) -> None:
38         self.inputs = dict_
39         self.strict = strictness
40
41     def get_str(self, key: str, default: str = '',
42                 ignore_strict: bool = False) -> str:
43         """Retrieve single/first string value of key, or default."""
44         if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
45             if self.strict and not ignore_strict:
46                 raise BadFormatException(f'no value found for key {key}')
47             return default
48         return self.inputs[key][0]
49
50     def get_first_strings_starting(self, prefix: str) -> dict[str, str]:
51         """Retrieve dict of (first) strings at key starting with prefix."""
52         ret = {}
53         for key in [k for k in self.inputs.keys() if k.startswith(prefix)]:
54             ret[key] = self.inputs[key][0]
55         return ret
56
57     def get_int(self, key: str) -> int:
58         """Retrieve single/first value of key as int, error if empty."""
59         val = self.get_int_or_none(key)
60         if val is None:
61             raise BadFormatException(f'unexpected empty value for: {key}')
62         return val
63
64     def get_int_or_none(self, key: str) -> int | None:
65         """Retrieve single/first value of key as int, return None if empty."""
66         val = self.get_str(key, ignore_strict=True)
67         if val == '':
68             return None
69         try:
70             return int(val)
71         except ValueError as e:
72             msg = f'cannot int form field value for key {key}: {val}'
73             raise BadFormatException(msg) from e
74
75     def get_float(self, key: str) -> float:
76         """Retrieve float value of key from self.postvars."""
77         val = self.get_str(key)
78         try:
79             return float(val)
80         except ValueError as e:
81             msg = f'cannot float form field value for key {key}: {val}'
82             raise BadFormatException(msg) from e
83
84     def get_all_str(self, key: str) -> list[str]:
85         """Retrieve list of string values at key."""
86         if key not in self.inputs.keys():
87             return []
88         return self.inputs[key]
89
90     def get_all_int(self, key: str) -> list[int]:
91         """Retrieve list of int values at key."""
92         all_str = self.get_all_str(key)
93         try:
94             return [int(s) for s in all_str if len(s) > 0]
95         except ValueError as e:
96             msg = f'cannot int a form field value for key {key} in: {all_str}'
97             raise BadFormatException(msg) from e
98
99
100 class TaskHandler(BaseHTTPRequestHandler):
101     """Handles single HTTP request."""
102     # pylint: disable=too-many-public-methods
103     server: TaskServer
104     conn: DatabaseConnection
105     _site: str
106     _form_data: InputsParser
107     _params: InputsParser
108
109     def _send_html(self, html: str, code: int = 200) -> None:
110         """Send HTML as proper HTTP response."""
111         self.send_response(code)
112         self.end_headers()
113         self.wfile.write(bytes(html, 'utf-8'))
114
115     @staticmethod
116     def _request_wrapper(http_method: str, not_found_msg: str
117                          ) -> Callable[..., Callable[[TaskHandler], None]]:
118         def decorator(f: Callable[..., str | None]
119                       ) -> Callable[[TaskHandler], None]:
120             def wrapper(self: TaskHandler) -> None:
121                 # pylint: disable=protected-access
122                 # (because pylint here fails to detect the use of wrapper as a
123                 # method to self with respective access privileges)
124                 try:
125                     self.conn = DatabaseConnection(self.server.db)
126                     parsed_url = urlparse(self.path)
127                     self._site = path_split(parsed_url.path)[1]
128                     params = parse_qs(parsed_url.query, strict_parsing=True)
129                     self._params = InputsParser(params, False)
130                     handler_name = f'do_{http_method}_{self._site}'
131                     if hasattr(self, handler_name):
132                         handler = getattr(self, handler_name)
133                         redir_target = f(self, handler)
134                         if redir_target:
135                             self.send_response(302)
136                             self.send_header('Location', redir_target)
137                             self.end_headers()
138                     else:
139                         msg = f'{not_found_msg}: {self._site}'
140                         raise NotFoundException(msg)
141                 except HandledException as error:
142                     html = self.server.jinja.\
143                             get_template('msg.html').render(msg=error)
144                     self._send_html(html, error.http_code)
145                 finally:
146                     self.conn.close()
147             return wrapper
148         return decorator
149
150     @_request_wrapper('GET', 'Unknown page')
151     def do_GET(self, handler: Callable[[], str | dict[str, object]]
152                ) -> str | None:
153         """Render page with result of handler, or redirect if result is str."""
154         template = f'{self._site}.html'
155         ctx_or_redir = handler()
156         if str == type(ctx_or_redir):
157             return ctx_or_redir
158         assert isinstance(ctx_or_redir, dict)
159         html = self.server.jinja.get_template(template).render(**ctx_or_redir)
160         self._send_html(html)
161         return None
162
163     @_request_wrapper('POST', 'Unknown POST target')
164     def do_POST(self, handler: Callable[[], str]) -> str:
165         """Handle POST with handler, prepare redirection to result."""
166         length = int(self.headers['content-length'])
167         postvars = parse_qs(self.rfile.read(length).decode(),
168                             keep_blank_values=True, strict_parsing=True)
169         self._form_data = InputsParser(postvars)
170         redir_target = handler()
171         self.conn.commit()
172         return redir_target
173
174     # GET handlers
175
176     def do_GET_(self) -> str:
177         """Return redirect target on GET /."""
178         return '/day'
179
180     def _do_GET_calendar(self) -> dict[str, object]:
181         """Show Days from ?start= to ?end=.
182
183         Both .do_GET_calendar and .do_GET_calendar_txt refer to this to do the
184         same, the only difference being the HTML template they are rendered to,
185         which .do_GET selects from their method name.
186         """
187         start = self._params.get_str('start')
188         end = self._params.get_str('end')
189         if not end:
190             end = date_in_n_days(366)
191         ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
192         days, start, end = ret
193         days = Day.with_filled_gaps(days, start, end)
194         for day in days:
195             day.collect_calendarized_todos(self.conn)
196         today = date_in_n_days(0)
197         return {'start': start, 'end': end, 'days': days, 'today': today}
198
199     def do_GET_calendar(self) -> dict[str, object]:
200         """Show Days from ?start= to ?end= – normal view."""
201         return self._do_GET_calendar()
202
203     def do_GET_calendar_txt(self) -> dict[str, object]:
204         """Show Days from ?start= to ?end= – minimalist view."""
205         return self._do_GET_calendar()
206
207     def do_GET_day(self) -> dict[str, object]:
208         """Show single Day of ?date=."""
209         date = self._params.get_str('date', date_in_n_days(0))
210         make_type = self._params.get_str('make_type')
211         todays_todos = Todo.by_date(self.conn, date)
212         total_effort = 0.0
213         for todo in todays_todos:
214             total_effort += todo.performed_effort
215         conditions_present = []
216         enablers_for = {}
217         disablers_for = {}
218         for todo in todays_todos:
219             for condition in todo.conditions + todo.blockers:
220                 if condition not in conditions_present:
221                     conditions_present += [condition]
222                     enablers_for[condition.id_] = [p for p in
223                                                    Process.all(self.conn)
224                                                    if condition in p.enables]
225                     disablers_for[condition.id_] = [p for p in
226                                                     Process.all(self.conn)
227                                                     if condition in p.disables]
228         seen_todos: set[int] = set()
229         top_nodes = [t.get_step_tree(seen_todos)
230                      for t in todays_todos if not t.parents]
231         return {'day': Day.by_id(self.conn, date, create=True),
232                 'total_effort': total_effort,
233                 'top_nodes': top_nodes,
234                 'make_type': make_type,
235                 'enablers_for': enablers_for,
236                 'disablers_for': disablers_for,
237                 'conditions_present': conditions_present,
238                 'processes': Process.all(self.conn)}
239
240     def do_GET_todo(self) -> dict[str, object]:
241         """Show single Todo of ?id=."""
242
243         @dataclass
244         class TodoStepsNode:
245             """Collect what's useful for Todo steps tree display."""
246             id_: int
247             todo: Todo | None
248             process: Process | None
249             children: list[TodoStepsNode]  # pylint: disable=undefined-variable
250             fillable: bool = False
251
252         def walk_process_steps(id_: int,
253                                process_step_nodes: list[ProcessStepsNode],
254                                steps_nodes: list[TodoStepsNode]) -> None:
255             for process_step_node in process_step_nodes:
256                 id_ += 1
257                 node = TodoStepsNode(id_, None, process_step_node.process, [])
258                 steps_nodes += [node]
259                 walk_process_steps(id_, list(process_step_node.steps.values()),
260                                    node.children)
261
262         def walk_todo_steps(id_: int, todos: list[Todo],
263                             steps_nodes: list[TodoStepsNode]) -> None:
264             for todo in todos:
265                 matched = False
266                 for match in [item for item in steps_nodes
267                               if item.process
268                               and item.process == todo.process]:
269                     match.todo = todo
270                     matched = True
271                     for child in match.children:
272                         child.fillable = True
273                     walk_todo_steps(id_, todo.children, match.children)
274                 if not matched:
275                     id_ += 1
276                     node = TodoStepsNode(id_, todo, None, [])
277                     steps_nodes += [node]
278                     walk_todo_steps(id_, todo.children, node.children)
279
280         def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
281                                     ) -> set[int]:
282             ids = set()
283             for node in steps_nodes:
284                 if not node.todo:
285                     assert isinstance(node.process, Process)
286                     assert isinstance(node.process.id_, int)
287                     ids.add(node.process.id_)
288                 ids = ids | collect_adoptables_keys(node.children)
289             return ids
290
291         id_ = self._params.get_int('id')
292         todo = Todo.by_id(self.conn, id_)
293         todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
294         process_tree = todo.process.get_steps(self.conn, None)
295         steps_todo_to_process: list[TodoStepsNode] = []
296         walk_process_steps(0, list(process_tree.values()),
297                            steps_todo_to_process)
298         for steps_node in steps_todo_to_process:
299             steps_node.fillable = True
300         walk_todo_steps(len(steps_todo_to_process), todo_steps,
301                         steps_todo_to_process)
302         adoptables: dict[int, list[Todo]] = {}
303         any_adoptables = [Todo.by_id(self.conn, t.id_)
304                           for t in Todo.by_date(self.conn, todo.date)
305                           if t != todo]
306         for id_ in collect_adoptables_keys(steps_todo_to_process):
307             adoptables[id_] = [t for t in any_adoptables
308                                if t.process.id_ == id_]
309         return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
310                 'adoption_candidates_for': adoptables,
311                 'process_candidates': Process.all(self.conn),
312                 'todo_candidates': any_adoptables,
313                 'condition_candidates': Condition.all(self.conn)}
314
315     def do_GET_todos(self) -> dict[str, object]:
316         """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
317         sort_by = self._params.get_str('sort_by')
318         start = self._params.get_str('start')
319         end = self._params.get_str('end')
320         process_id = self._params.get_int_or_none('process_id')
321         comment_pattern = self._params.get_str('comment_pattern')
322         todos = []
323         ret = Todo.by_date_range_with_limits(self.conn, (start, end))
324         todos_by_date_range, start, end = ret
325         todos = [t for t in todos_by_date_range
326                  if comment_pattern in t.comment
327                  and ((not process_id) or t.process.id_ == process_id)]
328         if sort_by == 'doneness':
329             todos.sort(key=lambda t: t.is_done)
330         elif sort_by == '-doneness':
331             todos.sort(key=lambda t: t.is_done, reverse=True)
332         elif sort_by == 'title':
333             todos.sort(key=lambda t: t.title_then)
334         elif sort_by == '-title':
335             todos.sort(key=lambda t: t.title_then, reverse=True)
336         elif sort_by == 'comment':
337             todos.sort(key=lambda t: t.comment)
338         elif sort_by == '-comment':
339             todos.sort(key=lambda t: t.comment, reverse=True)
340         elif sort_by == '-date':
341             todos.sort(key=lambda t: t.date, reverse=True)
342         else:
343             todos.sort(key=lambda t: t.date)
344         return {'start': start, 'end': end, 'process_id': process_id,
345                 'comment_pattern': comment_pattern, 'todos': todos,
346                 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
347
348     def do_GET_conditions(self) -> dict[str, object]:
349         """Show all Conditions."""
350         pattern = self._params.get_str('pattern')
351         conditions = Condition.matching(self.conn, pattern)
352         sort_by = self._params.get_str('sort_by')
353         if sort_by == 'is_active':
354             conditions.sort(key=lambda c: c.is_active)
355         elif sort_by == '-is_active':
356             conditions.sort(key=lambda c: c.is_active, reverse=True)
357         elif sort_by == '-title':
358             conditions.sort(key=lambda c: c.title.newest, reverse=True)
359         else:
360             conditions.sort(key=lambda c: c.title.newest)
361         return {'conditions': conditions,
362                 'sort_by': sort_by,
363                 'pattern': pattern}
364
365     def do_GET_condition(self) -> dict[str, object]:
366         """Show Condition of ?id=."""
367         id_ = self._params.get_int_or_none('id')
368         c = Condition.by_id(self.conn, id_, create=True)
369         ps = Process.all(self.conn)
370         return {'condition': c, 'is_new': c.id_ is None,
371                 'enabled_processes': [p for p in ps if c in p.conditions],
372                 'disabled_processes': [p for p in ps if c in p.blockers],
373                 'enabling_processes': [p for p in ps if c in p.enables],
374                 'disabling_processes': [p for p in ps if c in p.disables]}
375
376     def do_GET_condition_titles(self) -> dict[str, object]:
377         """Show title history of Condition of ?id=."""
378         id_ = self._params.get_int_or_none('id')
379         condition = Condition.by_id(self.conn, id_)
380         return {'condition': condition}
381
382     def do_GET_condition_descriptions(self) -> dict[str, object]:
383         """Show description historys of Condition of ?id=."""
384         id_ = self._params.get_int_or_none('id')
385         condition = Condition.by_id(self.conn, id_)
386         return {'condition': condition}
387
388     def do_GET_process(self) -> dict[str, object]:
389         """Show Process of ?id=."""
390         id_ = self._params.get_int_or_none('id')
391         process = Process.by_id(self.conn, id_, create=True)
392         title_64 = self._params.get_str('title_b64')
393         if title_64:
394             title = b64decode(title_64.encode()).decode()
395             process.title.set(title)
396         owners = process.used_as_step_by(self.conn)
397         for step_id in self._params.get_all_int('step_to'):
398             owners += [Process.by_id(self.conn, step_id)]
399         preset_top_step = None
400         for process_id in self._params.get_all_int('has_step'):
401             preset_top_step = process_id
402         return {'process': process, 'is_new': process.id_ is None,
403                 'preset_top_step': preset_top_step,
404                 'steps': process.get_steps(self.conn), 'owners': owners,
405                 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
406                 'process_candidates': Process.all(self.conn),
407                 'condition_candidates': Condition.all(self.conn)}
408
409     def do_GET_process_titles(self) -> dict[str, object]:
410         """Show title history of Process of ?id=."""
411         id_ = self._params.get_int_or_none('id')
412         process = Process.by_id(self.conn, id_)
413         return {'process': process}
414
415     def do_GET_process_descriptions(self) -> dict[str, object]:
416         """Show description historys of Process of ?id=."""
417         id_ = self._params.get_int_or_none('id')
418         process = Process.by_id(self.conn, id_)
419         return {'process': process}
420
421     def do_GET_process_efforts(self) -> dict[str, object]:
422         """Show default effort history of Process of ?id=."""
423         id_ = self._params.get_int_or_none('id')
424         process = Process.by_id(self.conn, id_)
425         return {'process': process}
426
427     def do_GET_processes(self) -> dict[str, object]:
428         """Show all Processes."""
429         pattern = self._params.get_str('pattern')
430         processes = Process.matching(self.conn, pattern)
431         sort_by = self._params.get_str('sort_by')
432         if sort_by == 'steps':
433             processes.sort(key=lambda p: len(p.explicit_steps))
434         elif sort_by == '-steps':
435             processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
436         elif sort_by == 'owners':
437             processes.sort(key=lambda p: p.n_owners or 0)
438         elif sort_by == '-owners':
439             processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
440         elif sort_by == 'effort':
441             processes.sort(key=lambda p: p.effort.newest)
442         elif sort_by == '-effort':
443             processes.sort(key=lambda p: p.effort.newest, reverse=True)
444         elif sort_by == '-title':
445             processes.sort(key=lambda p: p.title.newest, reverse=True)
446         else:
447             processes.sort(key=lambda p: p.title.newest)
448         return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
449
450     # POST handlers
451
452     def _change_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
453         """Update history timestamps for VersionedAttribute."""
454         id_ = self._params.get_int_or_none('id')
455         item = cls.by_id(self.conn, id_)
456         attr = getattr(item, attr_name)
457         for k, v in self._form_data.get_first_strings_starting('at:').items():
458             old = k[3:]
459             if old[19:] != v:
460                 attr.reset_timestamp(old, f'{v}.0')
461         attr.save(self.conn)
462         cls_name = cls.__name__.lower()
463         return f'/{cls_name}_{attr_name}s?id={item.id_}'
464
465     def do_POST_day(self) -> str:
466         """Update or insert Day of date and Todos mapped to it."""
467         date = self._params.get_str('date')
468         day = Day.by_id(self.conn, date, create=True)
469         day.comment = self._form_data.get_str('day_comment')
470         day.save(self.conn)
471         make_type = self._form_data.get_str('make_type')
472         for process_id in sorted(self._form_data.get_all_int('new_todo')):
473             if 'empty' == make_type:
474                 process = Process.by_id(self.conn, process_id)
475                 todo = Todo(None, process, False, date)
476                 todo.save(self.conn)
477             else:
478                 Todo.create_with_children(self.conn, process_id, date)
479         done_ids = self._form_data.get_all_int('done')
480         comments = self._form_data.get_all_str('comment')
481         efforts = self._form_data.get_all_str('effort')
482         for i, todo_id in enumerate(self._form_data.get_all_int('todo_id')):
483             todo = Todo.by_id(self.conn, todo_id)
484             todo.is_done = todo_id in done_ids
485             if len(comments) > 0:
486                 todo.comment = comments[i]
487             if len(efforts) > 0:
488                 todo.effort = float(efforts[i]) if efforts[i] else None
489             todo.save(self.conn)
490             for condition in todo.enables:
491                 condition.save(self.conn)
492             for condition in todo.disables:
493                 condition.save(self.conn)
494         return f'/day?date={date}&make_type={make_type}'
495
496     def do_POST_todo(self) -> str:
497         """Update Todo and its children."""
498         # pylint: disable=too-many-locals
499         # pylint: disable=too-many-branches
500         id_ = self._params.get_int('id')
501         for _ in self._form_data.get_all_str('delete'):
502             todo = Todo .by_id(self.conn, id_)
503             todo.remove(self.conn)
504             return '/'
505         todo = Todo.by_id(self.conn, id_)
506         adopted_child_ids = self._form_data.get_all_int('adopt')
507         processes_to_make_full = self._form_data.get_all_int('make_full')
508         processes_to_make_empty = self._form_data.get_all_int('make_empty')
509         fill_fors = self._form_data.get_first_strings_starting('fill_for_')
510         for v in fill_fors.values():
511             if v.startswith('make_empty_'):
512                 processes_to_make_empty += [int(v[11:])]
513             elif v.startswith('make_full_'):
514                 processes_to_make_full += [int(v[10:])]
515             elif v != 'ignore':
516                 adopted_child_ids += [int(v)]
517         to_remove = []
518         for child in todo.children:
519             assert isinstance(child.id_, int)
520             if child.id_ not in adopted_child_ids:
521                 to_remove += [child.id_]
522         for id_ in to_remove:
523             child = Todo.by_id(self.conn, id_)
524             todo.remove_child(child)
525         for child_id in adopted_child_ids:
526             if child_id in [c.id_ for c in todo.children]:
527                 continue
528             child = Todo.by_id(self.conn, child_id)
529             todo.add_child(child)
530         for process_id in processes_to_make_empty:
531             process = Process.by_id(self.conn, process_id)
532             made = Todo(None, process, False, todo.date)
533             made.save(self.conn)
534             todo.add_child(made)
535         for process_id in processes_to_make_full:
536             made = Todo.create_with_children(self.conn, process_id, todo.date)
537             todo.add_child(made)
538         effort = self._form_data.get_str('effort', ignore_strict=True)
539         todo.effort = float(effort) if effort else None
540         todo.set_conditions(self.conn,
541                             self._form_data.get_all_int('condition'))
542         todo.set_blockers(self.conn, self._form_data.get_all_int('blocker'))
543         todo.set_enables(self.conn, self._form_data.get_all_int('enables'))
544         todo.set_disables(self.conn, self._form_data.get_all_int('disables'))
545         todo.is_done = len(self._form_data.get_all_str('done')) > 0
546         todo.calendarize = len(self._form_data.get_all_str('calendarize')) > 0
547         todo.comment = self._form_data.get_str('comment', ignore_strict=True)
548         todo.save(self.conn)
549         for condition in todo.enables:
550             condition.save(self.conn)
551         for condition in todo.disables:
552             condition.save(self.conn)
553         return f'/todo?id={todo.id_}'
554
555     def do_POST_process_descriptions(self) -> str:
556         """Update history timestamps for Process.description."""
557         return self._change_versioned_timestamps(Process, 'description')
558
559     def do_POST_process_efforts(self) -> str:
560         """Update history timestamps for Process.effort."""
561         return self._change_versioned_timestamps(Process, 'effort')
562
563     def do_POST_process_titles(self) -> str:
564         """Update history timestamps for Process.title."""
565         return self._change_versioned_timestamps(Process, 'title')
566
567     def do_POST_process(self) -> str:
568         """Update or insert Process of ?id= and fields defined in postvars."""
569         # pylint: disable=too-many-branches
570         id_ = self._params.get_int_or_none('id')
571         for _ in self._form_data.get_all_str('delete'):
572             process = Process.by_id(self.conn, id_)
573             process.remove(self.conn)
574             return '/processes'
575         process = Process.by_id(self.conn, id_, create=True)
576         process.title.set(self._form_data.get_str('title'))
577         process.description.set(self._form_data.get_str('description'))
578         process.effort.set(self._form_data.get_float('effort'))
579         process.set_conditions(self.conn,
580                                self._form_data.get_all_int('condition'))
581         process.set_blockers(self.conn, self._form_data.get_all_int('blocker'))
582         process.set_enables(self.conn, self._form_data.get_all_int('enables'))
583         process.set_disables(self.conn,
584                              self._form_data.get_all_int('disables'))
585         process.calendarize = self._form_data.get_all_str('calendarize') != []
586         process.save(self.conn)
587         assert isinstance(process.id_, int)
588         steps: list[ProcessStep] = []
589         for step_id in self._form_data.get_all_int('keep_step'):
590             if step_id not in self._form_data.get_all_int('steps'):
591                 raise BadFormatException('trying to keep unknown step')
592         for step_id in self._form_data.get_all_int('steps'):
593             if step_id not in self._form_data.get_all_int('keep_step'):
594                 continue
595             step_process_id = self._form_data.get_int(
596                     f'step_{step_id}_process_id')
597             parent_id = self._form_data.get_int_or_none(
598                     f'step_{step_id}_parent_id')
599             steps += [ProcessStep(step_id, process.id_, step_process_id,
600                                   parent_id)]
601         for step_id in self._form_data.get_all_int('steps'):
602             for step_process_id in self._form_data.get_all_int(
603                     f'new_step_to_{step_id}'):
604                 steps += [ProcessStep(None, process.id_, step_process_id,
605                                       step_id)]
606         new_step_title = None
607         for step_identifier in self._form_data.get_all_str('new_top_step'):
608             try:
609                 step_process_id = int(step_identifier)
610                 steps += [ProcessStep(None, process.id_, step_process_id,
611                                       None)]
612             except ValueError:
613                 new_step_title = step_identifier
614         process.uncache()
615         process.set_steps(self.conn, steps)
616         process.set_step_suppressions(self.conn,
617                                       self._form_data.
618                                       get_all_int('suppresses'))
619         process.save(self.conn)
620         owners_to_set = []
621         new_owner_title = None
622         for owner_identifier in self._form_data.get_all_str('step_of'):
623             try:
624                 owners_to_set += [int(owner_identifier)]
625             except ValueError:
626                 new_owner_title = owner_identifier
627         process.set_owners(self.conn, owners_to_set)
628         params = f'id={process.id_}'
629         if new_step_title:
630             title_b64_encoded = b64encode(new_step_title.encode()).decode()
631             params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
632         elif new_owner_title:
633             title_b64_encoded = b64encode(new_owner_title.encode()).decode()
634             params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
635         return f'/process?{params}'
636
637     def do_POST_condition_descriptions(self) -> str:
638         """Update history timestamps for Condition.description."""
639         return self._change_versioned_timestamps(Condition, 'description')
640
641     def do_POST_condition_titles(self) -> str:
642         """Update history timestamps for Condition.title."""
643         return self._change_versioned_timestamps(Condition, 'title')
644
645     def do_POST_condition(self) -> str:
646         """Update/insert Condition of ?id= and fields defined in postvars."""
647         id_ = self._params.get_int_or_none('id')
648         for _ in self._form_data.get_all_str('delete'):
649             condition = Condition.by_id(self.conn, id_)
650             condition.remove(self.conn)
651             return '/conditions'
652         condition = Condition.by_id(self.conn, id_, create=True)
653         condition.is_active = self._form_data.get_all_str('is_active') != []
654         condition.title.set(self._form_data.get_str('title'))
655         condition.description.set(self._form_data.get_str('description'))
656         condition.save(self.conn)
657         return f'/condition?id={condition.id_}'