home · contact · privacy
Overhaul caching.
[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                     for cls in (Day, Todo, Condition, Process, ProcessStep):
143                         assert hasattr(cls, 'empty_cache')
144                         cls.empty_cache()
145                     tmpl = self.server.jinja.get_template('msg.html')
146                     html = tmpl.render(msg=error)
147                     self._send_html(html, error.http_code)
148                 finally:
149                     self.conn.close()
150             return wrapper
151         return decorator
152
153     @_request_wrapper('GET', 'Unknown page')
154     def do_GET(self, handler: Callable[[], str | dict[str, object]]
155                ) -> str | None:
156         """Render page with result of handler, or redirect if result is str."""
157         template = f'{self._site}.html'
158         ctx_or_redir = handler()
159         if str == type(ctx_or_redir):
160             return ctx_or_redir
161         assert isinstance(ctx_or_redir, dict)
162         html = self.server.jinja.get_template(template).render(**ctx_or_redir)
163         self._send_html(html)
164         return None
165
166     @_request_wrapper('POST', 'Unknown POST target')
167     def do_POST(self, handler: Callable[[], str]) -> str:
168         """Handle POST with handler, prepare redirection to result."""
169         length = int(self.headers['content-length'])
170         postvars = parse_qs(self.rfile.read(length).decode(),
171                             keep_blank_values=True, strict_parsing=True)
172         self._form_data = InputsParser(postvars)
173         redir_target = handler()
174         self.conn.commit()
175         return redir_target
176
177     # GET handlers
178
179     def do_GET_(self) -> str:
180         """Return redirect target on GET /."""
181         return '/day'
182
183     def _do_GET_calendar(self) -> dict[str, object]:
184         """Show Days from ?start= to ?end=.
185
186         Both .do_GET_calendar and .do_GET_calendar_txt refer to this to do the
187         same, the only difference being the HTML template they are rendered to,
188         which .do_GET selects from their method name.
189         """
190         start = self._params.get_str('start')
191         end = self._params.get_str('end')
192         if not end:
193             end = date_in_n_days(366)
194         ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
195         days, start, end = ret
196         days = Day.with_filled_gaps(days, start, end)
197         today = date_in_n_days(0)
198         return {'start': start, 'end': end, 'days': days, 'today': today}
199
200     def do_GET_calendar(self) -> dict[str, object]:
201         """Show Days from ?start= to ?end= – normal view."""
202         return self._do_GET_calendar()
203
204     def do_GET_calendar_txt(self) -> dict[str, object]:
205         """Show Days from ?start= to ?end= – minimalist view."""
206         return self._do_GET_calendar()
207
208     def do_GET_day(self) -> dict[str, object]:
209         """Show single Day of ?date=."""
210         date = self._params.get_str('date', date_in_n_days(0))
211         day = Day.by_id(self.conn, date, create=True)
212         make_type = self._params.get_str('make_type')
213         conditions_present = []
214         enablers_for = {}
215         disablers_for = {}
216         for todo in day.todos:
217             for condition in todo.conditions + todo.blockers:
218                 if condition not in conditions_present:
219                     conditions_present += [condition]
220                     enablers_for[condition.id_] = [p for p in
221                                                    Process.all(self.conn)
222                                                    if condition in p.enables]
223                     disablers_for[condition.id_] = [p for p in
224                                                     Process.all(self.conn)
225                                                     if condition in p.disables]
226         seen_todos: set[int] = set()
227         top_nodes = [t.get_step_tree(seen_todos)
228                      for t in day.todos if not t.parents]
229         return {'day': day,
230                 'top_nodes': top_nodes,
231                 'make_type': make_type,
232                 'enablers_for': enablers_for,
233                 'disablers_for': disablers_for,
234                 'conditions_present': conditions_present,
235                 'processes': Process.all(self.conn)}
236
237     def do_GET_todo(self) -> dict[str, object]:
238         """Show single Todo of ?id=."""
239
240         @dataclass
241         class TodoStepsNode:
242             """Collect what's useful for Todo steps tree display."""
243             id_: int
244             todo: Todo | None
245             process: Process | None
246             children: list[TodoStepsNode]  # pylint: disable=undefined-variable
247             fillable: bool = False
248
249         def walk_process_steps(id_: int,
250                                process_step_nodes: list[ProcessStepsNode],
251                                steps_nodes: list[TodoStepsNode]) -> None:
252             for process_step_node in process_step_nodes:
253                 id_ += 1
254                 node = TodoStepsNode(id_, None, process_step_node.process, [])
255                 steps_nodes += [node]
256                 walk_process_steps(id_, list(process_step_node.steps.values()),
257                                    node.children)
258
259         def walk_todo_steps(id_: int, todos: list[Todo],
260                             steps_nodes: list[TodoStepsNode]) -> None:
261             for todo in todos:
262                 matched = False
263                 for match in [item for item in steps_nodes
264                               if item.process
265                               and item.process == todo.process]:
266                     match.todo = todo
267                     matched = True
268                     for child in match.children:
269                         child.fillable = True
270                     walk_todo_steps(id_, todo.children, match.children)
271                 if not matched:
272                     id_ += 1
273                     node = TodoStepsNode(id_, todo, None, [])
274                     steps_nodes += [node]
275                     walk_todo_steps(id_, todo.children, node.children)
276
277         def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
278                                     ) -> set[int]:
279             ids = set()
280             for node in steps_nodes:
281                 if not node.todo:
282                     assert isinstance(node.process, Process)
283                     assert isinstance(node.process.id_, int)
284                     ids.add(node.process.id_)
285                 ids = ids | collect_adoptables_keys(node.children)
286             return ids
287
288         id_ = self._params.get_int('id')
289         todo = Todo.by_id(self.conn, id_)
290         todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
291         process_tree = todo.process.get_steps(self.conn, None)
292         steps_todo_to_process: list[TodoStepsNode] = []
293         walk_process_steps(0, list(process_tree.values()),
294                            steps_todo_to_process)
295         for steps_node in steps_todo_to_process:
296             steps_node.fillable = True
297         walk_todo_steps(len(steps_todo_to_process), todo_steps,
298                         steps_todo_to_process)
299         adoptables: dict[int, list[Todo]] = {}
300         any_adoptables = [Todo.by_id(self.conn, t.id_)
301                           for t in Todo.by_date(self.conn, todo.date)
302                           if t != todo]
303         for id_ in collect_adoptables_keys(steps_todo_to_process):
304             adoptables[id_] = [t for t in any_adoptables
305                                if t.process.id_ == id_]
306         return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
307                 'adoption_candidates_for': adoptables,
308                 'process_candidates': Process.all(self.conn),
309                 'todo_candidates': any_adoptables,
310                 'condition_candidates': Condition.all(self.conn)}
311
312     def do_GET_todos(self) -> dict[str, object]:
313         """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
314         sort_by = self._params.get_str('sort_by')
315         start = self._params.get_str('start')
316         end = self._params.get_str('end')
317         process_id = self._params.get_int_or_none('process_id')
318         comment_pattern = self._params.get_str('comment_pattern')
319         todos = []
320         ret = Todo.by_date_range_with_limits(self.conn, (start, end))
321         todos_by_date_range, start, end = ret
322         todos = [t for t in todos_by_date_range
323                  if comment_pattern in t.comment
324                  and ((not process_id) or t.process.id_ == process_id)]
325         if sort_by == 'doneness':
326             todos.sort(key=lambda t: t.is_done)
327         elif sort_by == '-doneness':
328             todos.sort(key=lambda t: t.is_done, reverse=True)
329         elif sort_by == 'title':
330             todos.sort(key=lambda t: t.title_then)
331         elif sort_by == '-title':
332             todos.sort(key=lambda t: t.title_then, reverse=True)
333         elif sort_by == 'comment':
334             todos.sort(key=lambda t: t.comment)
335         elif sort_by == '-comment':
336             todos.sort(key=lambda t: t.comment, reverse=True)
337         elif sort_by == '-date':
338             todos.sort(key=lambda t: t.date, reverse=True)
339         else:
340             todos.sort(key=lambda t: t.date)
341         return {'start': start, 'end': end, 'process_id': process_id,
342                 'comment_pattern': comment_pattern, 'todos': todos,
343                 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
344
345     def do_GET_conditions(self) -> dict[str, object]:
346         """Show all Conditions."""
347         pattern = self._params.get_str('pattern')
348         conditions = Condition.matching(self.conn, pattern)
349         sort_by = self._params.get_str('sort_by')
350         if sort_by == 'is_active':
351             conditions.sort(key=lambda c: c.is_active)
352         elif sort_by == '-is_active':
353             conditions.sort(key=lambda c: c.is_active, reverse=True)
354         elif sort_by == '-title':
355             conditions.sort(key=lambda c: c.title.newest, reverse=True)
356         else:
357             conditions.sort(key=lambda c: c.title.newest)
358         return {'conditions': conditions,
359                 'sort_by': sort_by,
360                 'pattern': pattern}
361
362     def do_GET_condition(self) -> dict[str, object]:
363         """Show Condition of ?id=."""
364         id_ = self._params.get_int_or_none('id')
365         c = Condition.by_id(self.conn, id_, create=True)
366         ps = Process.all(self.conn)
367         return {'condition': c, 'is_new': c.id_ is None,
368                 'enabled_processes': [p for p in ps if c in p.conditions],
369                 'disabled_processes': [p for p in ps if c in p.blockers],
370                 'enabling_processes': [p for p in ps if c in p.enables],
371                 'disabling_processes': [p for p in ps if c in p.disables]}
372
373     def do_GET_condition_titles(self) -> dict[str, object]:
374         """Show title history of Condition of ?id=."""
375         id_ = self._params.get_int_or_none('id')
376         condition = Condition.by_id(self.conn, id_)
377         return {'condition': condition}
378
379     def do_GET_condition_descriptions(self) -> dict[str, object]:
380         """Show description historys of Condition of ?id=."""
381         id_ = self._params.get_int_or_none('id')
382         condition = Condition.by_id(self.conn, id_)
383         return {'condition': condition}
384
385     def do_GET_process(self) -> dict[str, object]:
386         """Show Process of ?id=."""
387         id_ = self._params.get_int_or_none('id')
388         process = Process.by_id(self.conn, id_, create=True)
389         title_64 = self._params.get_str('title_b64')
390         if title_64:
391             title = b64decode(title_64.encode()).decode()
392             process.title.set(title)
393         owners = process.used_as_step_by(self.conn)
394         for step_id in self._params.get_all_int('step_to'):
395             owners += [Process.by_id(self.conn, step_id)]
396         preset_top_step = None
397         for process_id in self._params.get_all_int('has_step'):
398             preset_top_step = process_id
399         return {'process': process, 'is_new': process.id_ is None,
400                 'preset_top_step': preset_top_step,
401                 'steps': process.get_steps(self.conn), 'owners': owners,
402                 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
403                 'process_candidates': Process.all(self.conn),
404                 'condition_candidates': Condition.all(self.conn)}
405
406     def do_GET_process_titles(self) -> dict[str, object]:
407         """Show title history of Process of ?id=."""
408         id_ = self._params.get_int_or_none('id')
409         process = Process.by_id(self.conn, id_)
410         return {'process': process}
411
412     def do_GET_process_descriptions(self) -> dict[str, object]:
413         """Show description historys of Process of ?id=."""
414         id_ = self._params.get_int_or_none('id')
415         process = Process.by_id(self.conn, id_)
416         return {'process': process}
417
418     def do_GET_process_efforts(self) -> dict[str, object]:
419         """Show default effort history of Process of ?id=."""
420         id_ = self._params.get_int_or_none('id')
421         process = Process.by_id(self.conn, id_)
422         return {'process': process}
423
424     def do_GET_processes(self) -> dict[str, object]:
425         """Show all Processes."""
426         pattern = self._params.get_str('pattern')
427         processes = Process.matching(self.conn, pattern)
428         sort_by = self._params.get_str('sort_by')
429         if sort_by == 'steps':
430             processes.sort(key=lambda p: len(p.explicit_steps))
431         elif sort_by == '-steps':
432             processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
433         elif sort_by == 'owners':
434             processes.sort(key=lambda p: p.n_owners or 0)
435         elif sort_by == '-owners':
436             processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
437         elif sort_by == 'effort':
438             processes.sort(key=lambda p: p.effort.newest)
439         elif sort_by == '-effort':
440             processes.sort(key=lambda p: p.effort.newest, reverse=True)
441         elif sort_by == '-title':
442             processes.sort(key=lambda p: p.title.newest, reverse=True)
443         else:
444             processes.sort(key=lambda p: p.title.newest)
445         return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
446
447     # POST handlers
448
449     def _change_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
450         """Update history timestamps for VersionedAttribute."""
451         id_ = self._params.get_int_or_none('id')
452         item = cls.by_id(self.conn, id_)
453         attr = getattr(item, attr_name)
454         for k, v in self._form_data.get_first_strings_starting('at:').items():
455             old = k[3:]
456             if old[19:] != v:
457                 attr.reset_timestamp(old, f'{v}.0')
458         attr.save(self.conn)
459         cls_name = cls.__name__.lower()
460         return f'/{cls_name}_{attr_name}s?id={item.id_}'
461
462     def do_POST_day(self) -> str:
463         """Update or insert Day of date and Todos mapped to it."""
464         date = self._params.get_str('date')
465         day = Day.by_id(self.conn, date, create=True)
466         day.comment = self._form_data.get_str('day_comment')
467         day.save(self.conn)
468         make_type = self._form_data.get_str('make_type')
469         for process_id in sorted(self._form_data.get_all_int('new_todo')):
470             if 'empty' == make_type:
471                 process = Process.by_id(self.conn, process_id)
472                 todo = Todo(None, process, False, date)
473                 todo.save(self.conn)
474             else:
475                 Todo.create_with_children(self.conn, process_id, date)
476         done_ids = self._form_data.get_all_int('done')
477         comments = self._form_data.get_all_str('comment')
478         efforts = self._form_data.get_all_str('effort')
479         for i, todo_id in enumerate(self._form_data.get_all_int('todo_id')):
480             todo = Todo.by_id(self.conn, todo_id)
481             todo.is_done = todo_id in done_ids
482             if len(comments) > 0:
483                 todo.comment = comments[i]
484             if len(efforts) > 0:
485                 todo.effort = float(efforts[i]) if efforts[i] else None
486             todo.save(self.conn)
487         return f'/day?date={date}&make_type={make_type}'
488
489     def do_POST_todo(self) -> str:
490         """Update Todo and its children."""
491         # pylint: disable=too-many-locals
492         # pylint: disable=too-many-branches
493         id_ = self._params.get_int('id')
494         for _ in self._form_data.get_all_str('delete'):
495             todo = Todo .by_id(self.conn, id_)
496             todo.remove(self.conn)
497             return '/'
498         todo = Todo.by_id(self.conn, id_)
499         adopted_child_ids = self._form_data.get_all_int('adopt')
500         processes_to_make_full = self._form_data.get_all_int('make_full')
501         processes_to_make_empty = self._form_data.get_all_int('make_empty')
502         fill_fors = self._form_data.get_first_strings_starting('fill_for_')
503         for v in fill_fors.values():
504             if v.startswith('make_empty_'):
505                 processes_to_make_empty += [int(v[11:])]
506             elif v.startswith('make_full_'):
507                 processes_to_make_full += [int(v[10:])]
508             elif v != 'ignore':
509                 adopted_child_ids += [int(v)]
510         to_remove = []
511         for child in todo.children:
512             assert isinstance(child.id_, int)
513             if child.id_ not in adopted_child_ids:
514                 to_remove += [child.id_]
515         for id_ in to_remove:
516             child = Todo.by_id(self.conn, id_)
517             todo.remove_child(child)
518         for child_id in adopted_child_ids:
519             if child_id in [c.id_ for c in todo.children]:
520                 continue
521             child = Todo.by_id(self.conn, child_id)
522             todo.add_child(child)
523         for process_id in processes_to_make_empty:
524             process = Process.by_id(self.conn, process_id)
525             made = Todo(None, process, False, todo.date)
526             made.save(self.conn)
527             todo.add_child(made)
528         for process_id in processes_to_make_full:
529             made = Todo.create_with_children(self.conn, process_id, todo.date)
530             todo.add_child(made)
531         effort = self._form_data.get_str('effort', ignore_strict=True)
532         todo.effort = float(effort) if effort else None
533         todo.set_conditions(self.conn,
534                             self._form_data.get_all_int('condition'))
535         todo.set_blockers(self.conn, self._form_data.get_all_int('blocker'))
536         todo.set_enables(self.conn, self._form_data.get_all_int('enables'))
537         todo.set_disables(self.conn, self._form_data.get_all_int('disables'))
538         todo.is_done = len(self._form_data.get_all_str('done')) > 0
539         todo.calendarize = len(self._form_data.get_all_str('calendarize')) > 0
540         todo.comment = self._form_data.get_str('comment', ignore_strict=True)
541         todo.save(self.conn)
542         return f'/todo?id={todo.id_}'
543
544     def do_POST_process_descriptions(self) -> str:
545         """Update history timestamps for Process.description."""
546         return self._change_versioned_timestamps(Process, 'description')
547
548     def do_POST_process_efforts(self) -> str:
549         """Update history timestamps for Process.effort."""
550         return self._change_versioned_timestamps(Process, 'effort')
551
552     def do_POST_process_titles(self) -> str:
553         """Update history timestamps for Process.title."""
554         return self._change_versioned_timestamps(Process, 'title')
555
556     def do_POST_process(self) -> str:
557         """Update or insert Process of ?id= and fields defined in postvars."""
558         # pylint: disable=too-many-branches
559         id_ = self._params.get_int_or_none('id')
560         for _ in self._form_data.get_all_str('delete'):
561             process = Process.by_id(self.conn, id_)
562             process.remove(self.conn)
563             return '/processes'
564         process = Process.by_id(self.conn, id_, create=True)
565         process.title.set(self._form_data.get_str('title'))
566         process.description.set(self._form_data.get_str('description'))
567         process.effort.set(self._form_data.get_float('effort'))
568         process.set_conditions(self.conn,
569                                self._form_data.get_all_int('condition'))
570         process.set_blockers(self.conn, self._form_data.get_all_int('blocker'))
571         process.set_enables(self.conn, self._form_data.get_all_int('enables'))
572         process.set_disables(self.conn,
573                              self._form_data.get_all_int('disables'))
574         process.calendarize = self._form_data.get_all_str('calendarize') != []
575         process.save(self.conn)
576         assert isinstance(process.id_, int)
577         steps: list[ProcessStep] = []
578         for step_id in self._form_data.get_all_int('keep_step'):
579             if step_id not in self._form_data.get_all_int('steps'):
580                 raise BadFormatException('trying to keep unknown step')
581         for step_id in self._form_data.get_all_int('steps'):
582             if step_id not in self._form_data.get_all_int('keep_step'):
583                 continue
584             step_process_id = self._form_data.get_int(
585                     f'step_{step_id}_process_id')
586             parent_id = self._form_data.get_int_or_none(
587                     f'step_{step_id}_parent_id')
588             steps += [ProcessStep(step_id, process.id_, step_process_id,
589                                   parent_id)]
590         for step_id in self._form_data.get_all_int('steps'):
591             for step_process_id in self._form_data.get_all_int(
592                     f'new_step_to_{step_id}'):
593                 steps += [ProcessStep(None, process.id_, step_process_id,
594                                       step_id)]
595         new_step_title = None
596         for step_identifier in self._form_data.get_all_str('new_top_step'):
597             try:
598                 step_process_id = int(step_identifier)
599                 steps += [ProcessStep(None, process.id_, step_process_id,
600                                       None)]
601             except ValueError:
602                 new_step_title = step_identifier
603         process.set_steps(self.conn, steps)
604         process.set_step_suppressions(self.conn,
605                                       self._form_data.
606                                       get_all_int('suppresses'))
607         owners_to_set = []
608         new_owner_title = None
609         for owner_identifier in self._form_data.get_all_str('step_of'):
610             try:
611                 owners_to_set += [int(owner_identifier)]
612             except ValueError:
613                 new_owner_title = owner_identifier
614         process.set_owners(self.conn, owners_to_set)
615         params = f'id={process.id_}'
616         if new_step_title:
617             title_b64_encoded = b64encode(new_step_title.encode()).decode()
618             params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
619         elif new_owner_title:
620             title_b64_encoded = b64encode(new_owner_title.encode()).decode()
621             params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
622         process.save(self.conn)
623         return f'/process?{params}'
624
625     def do_POST_condition_descriptions(self) -> str:
626         """Update history timestamps for Condition.description."""
627         return self._change_versioned_timestamps(Condition, 'description')
628
629     def do_POST_condition_titles(self) -> str:
630         """Update history timestamps for Condition.title."""
631         return self._change_versioned_timestamps(Condition, 'title')
632
633     def do_POST_condition(self) -> str:
634         """Update/insert Condition of ?id= and fields defined in postvars."""
635         id_ = self._params.get_int_or_none('id')
636         for _ in self._form_data.get_all_str('delete'):
637             condition = Condition.by_id(self.conn, id_)
638             condition.remove(self.conn)
639             return '/conditions'
640         condition = Condition.by_id(self.conn, id_, create=True)
641         condition.is_active = self._form_data.get_all_str('is_active') != []
642         condition.title.set(self._form_data.get_str('title'))
643         condition.description.set(self._form_data.get_str('description'))
644         condition.save(self.conn)
645         return f'/condition?id={condition.id_}'