home · contact · privacy
ba79c5a5a929fb4d02975276a854e5b6de4c999b
[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                 try:
122                     self.conn = DatabaseConnection(self.server.db)
123                     parsed_url = urlparse(self.path)
124                     self.site = path_split(parsed_url.path)[1]
125                     params = parse_qs(parsed_url.query, strict_parsing=True)
126                     self.params = InputsParser(params, False)
127                     handler_name = f'do_{http_method}_{self.site}'
128                     if hasattr(self, handler_name):
129                         handler = getattr(self, handler_name)
130                         redir_target = f(self, handler)
131                         if redir_target:
132                             self.send_response(302)
133                             self.send_header('Location', redir_target)
134                             self.end_headers()
135                     else:
136                         msg = f'{not_found_msg}: {self.site}'
137                         raise NotFoundException(msg)
138                 except HandledException as error:
139                     html = self.server.jinja.\
140                             get_template('msg.html').render(msg=error)
141                     self.send_html(html, error.http_code)
142                 finally:
143                     self.conn.close()
144             return wrapper
145         return decorator
146
147     @_request_wrapper('GET', 'Unknown page')
148     def do_GET(self, handler: Callable[[], str | dict[str, object]]
149                ) -> str | None:
150         """Render page with result of handler, or redirect if result is str."""
151         template = f'{self.site}.html'
152         ctx_or_redir = handler()
153         if str == type(ctx_or_redir):
154             return ctx_or_redir
155         assert isinstance(ctx_or_redir, dict)
156         html = self.server.jinja.get_template(template).render(**ctx_or_redir)
157         self.send_html(html)
158         return None
159
160     @_request_wrapper('POST', 'Unknown POST target')
161     def do_POST(self, handler: Callable[[], str]) -> str:
162         """Handle POST with handler, prepare redirection to result."""
163         length = int(self.headers['content-length'])
164         postvars = parse_qs(self.rfile.read(length).decode(),
165                             keep_blank_values=True, strict_parsing=True)
166         self.form_data = InputsParser(postvars)
167         redir_target = handler()
168         self.conn.commit()
169         return redir_target
170
171     # GET handlers
172
173     def do_GET_(self) -> str:
174         """Return redirect target on GET /."""
175         return '/day'
176
177     def _do_GET_calendar(self) -> dict[str, object]:
178         """Show Days from ?start= to ?end=.
179
180         Both .do_GET_calendar and .do_GET_calendar_txt refer to this to do the
181         same, the only difference being the HTML template they are rendered to,
182         which .do_GET selects from their method name.
183         """
184         start = self.params.get_str('start')
185         end = self.params.get_str('end')
186         if not end:
187             end = date_in_n_days(366)
188         ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
189         days, start, end = ret
190         days = Day.with_filled_gaps(days, start, end)
191         for day in days:
192             day.collect_calendarized_todos(self.conn)
193         today = date_in_n_days(0)
194         return {'start': start, 'end': end, 'days': days, 'today': today}
195
196     def do_GET_calendar(self) -> dict[str, object]:
197         """Show Days from ?start= to ?end= – normal view."""
198         return self._do_GET_calendar()
199
200     def do_GET_calendar_txt(self) -> dict[str, object]:
201         """Show Days from ?start= to ?end= – minimalist view."""
202         return self._do_GET_calendar()
203
204     def do_GET_day(self) -> dict[str, object]:
205         """Show single Day of ?date=."""
206         date = self.params.get_str('date', date_in_n_days(0))
207         make_type = self.params.get_str('make_type')
208         todays_todos = Todo.by_date(self.conn, date)
209         total_effort = 0.0
210         for todo in todays_todos:
211             total_effort += todo.performed_effort
212         conditions_present = []
213         enablers_for = {}
214         disablers_for = {}
215         for todo in todays_todos:
216             for condition in todo.conditions + todo.blockers:
217                 if condition not in conditions_present:
218                     conditions_present += [condition]
219                     enablers_for[condition.id_] = [p for p in
220                                                    Process.all(self.conn)
221                                                    if condition in p.enables]
222                     disablers_for[condition.id_] = [p for p in
223                                                     Process.all(self.conn)
224                                                     if condition in p.disables]
225         seen_todos: set[int] = set()
226         top_nodes = [t.get_step_tree(seen_todos)
227                      for t in todays_todos if not t.parents]
228         return {'day': Day.by_id(self.conn, date, create=True),
229                 'total_effort': total_effort,
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             for condition in todo.enables:
488                 condition.save(self.conn)
489             for condition in todo.disables:
490                 condition.save(self.conn)
491         return f'/day?date={date}&make_type={make_type}'
492
493     def do_POST_todo(self) -> str:
494         """Update Todo and its children."""
495         # pylint: disable=too-many-locals
496         # pylint: disable=too-many-branches
497         id_ = self.params.get_int('id')
498         for _ in self.form_data.get_all_str('delete'):
499             todo = Todo .by_id(self.conn, id_)
500             todo.remove(self.conn)
501             return '/'
502         todo = Todo.by_id(self.conn, id_)
503         adopted_child_ids = self.form_data.get_all_int('adopt')
504         processes_to_make_full = self.form_data.get_all_int('make_full')
505         processes_to_make_empty = self.form_data.get_all_int('make_empty')
506         fill_fors = self.form_data.get_first_strings_starting('fill_for_')
507         for v in fill_fors.values():
508             if v.startswith('make_empty_'):
509                 processes_to_make_empty += [int(v[11:])]
510             elif v.startswith('make_full_'):
511                 processes_to_make_full += [int(v[10:])]
512             elif v != 'ignore':
513                 adopted_child_ids += [int(v)]
514         to_remove = []
515         for child in todo.children:
516             assert isinstance(child.id_, int)
517             if child.id_ not in adopted_child_ids:
518                 to_remove += [child.id_]
519         for id_ in to_remove:
520             child = Todo.by_id(self.conn, id_)
521             todo.remove_child(child)
522         for child_id in adopted_child_ids:
523             if child_id in [c.id_ for c in todo.children]:
524                 continue
525             child = Todo.by_id(self.conn, child_id)
526             todo.add_child(child)
527         for process_id in processes_to_make_empty:
528             process = Process.by_id(self.conn, process_id)
529             made = Todo(None, process, False, todo.date)
530             made.save(self.conn)
531             todo.add_child(made)
532         for process_id in processes_to_make_full:
533             made = Todo.create_with_children(self.conn, process_id, todo.date)
534             todo.add_child(made)
535         effort = self.form_data.get_str('effort', ignore_strict=True)
536         todo.effort = float(effort) if effort else None
537         todo.set_conditions(self.conn,
538                             self.form_data.get_all_int('condition'))
539         todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
540         todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
541         todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
542         todo.is_done = len(self.form_data.get_all_str('done')) > 0
543         todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
544         todo.comment = self.form_data.get_str('comment', ignore_strict=True)
545         todo.save(self.conn)
546         for condition in todo.enables:
547             condition.save(self.conn)
548         for condition in todo.disables:
549             condition.save(self.conn)
550         return f'/todo?id={todo.id_}'
551
552     def do_POST_process_descriptions(self) -> str:
553         """Update history timestamps for Process.description."""
554         return self._change_versioned_timestamps(Process, 'description')
555
556     def do_POST_process_efforts(self) -> str:
557         """Update history timestamps for Process.effort."""
558         return self._change_versioned_timestamps(Process, 'effort')
559
560     def do_POST_process_titles(self) -> str:
561         """Update history timestamps for Process.title."""
562         return self._change_versioned_timestamps(Process, 'title')
563
564     def do_POST_process(self) -> str:
565         """Update or insert Process of ?id= and fields defined in postvars."""
566         # pylint: disable=too-many-branches
567         id_ = self.params.get_int_or_none('id')
568         for _ in self.form_data.get_all_str('delete'):
569             process = Process.by_id(self.conn, id_)
570             process.remove(self.conn)
571             return '/processes'
572         process = Process.by_id(self.conn, id_, create=True)
573         process.title.set(self.form_data.get_str('title'))
574         process.description.set(self.form_data.get_str('description'))
575         process.effort.set(self.form_data.get_float('effort'))
576         process.set_conditions(self.conn,
577                                self.form_data.get_all_int('condition'))
578         process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
579         process.set_enables(self.conn, self.form_data.get_all_int('enables'))
580         process.set_disables(self.conn,
581                              self.form_data.get_all_int('disables'))
582         process.calendarize = self.form_data.get_all_str('calendarize') != []
583         process.save(self.conn)
584         assert isinstance(process.id_, int)
585         steps: list[ProcessStep] = []
586         for step_id in self.form_data.get_all_int('keep_step'):
587             if step_id not in self.form_data.get_all_int('steps'):
588                 raise BadFormatException('trying to keep unknown step')
589         for step_id in self.form_data.get_all_int('steps'):
590             if step_id not in self.form_data.get_all_int('keep_step'):
591                 continue
592             step_process_id = self.form_data.get_int(
593                     f'step_{step_id}_process_id')
594             parent_id = self.form_data.get_int_or_none(
595                     f'step_{step_id}_parent_id')
596             steps += [ProcessStep(step_id, process.id_, step_process_id,
597                                   parent_id)]
598         for step_id in self.form_data.get_all_int('steps'):
599             for step_process_id in self.form_data.get_all_int(
600                     f'new_step_to_{step_id}'):
601                 steps += [ProcessStep(None, process.id_, step_process_id,
602                                       step_id)]
603         new_step_title = None
604         for step_identifier in self.form_data.get_all_str('new_top_step'):
605             try:
606                 step_process_id = int(step_identifier)
607                 steps += [ProcessStep(None, process.id_, step_process_id,
608                                       None)]
609             except ValueError:
610                 new_step_title = step_identifier
611         process.uncache()
612         process.set_steps(self.conn, steps)
613         process.set_step_suppressions(self.conn,
614                                       self.form_data.
615                                       get_all_int('suppresses'))
616         process.save(self.conn)
617         owners_to_set = []
618         new_owner_title = None
619         for owner_identifier in self.form_data.get_all_str('step_of'):
620             try:
621                 owners_to_set += [int(owner_identifier)]
622             except ValueError:
623                 new_owner_title = owner_identifier
624         process.set_owners(self.conn, owners_to_set)
625         params = f'id={process.id_}'
626         if new_step_title:
627             title_b64_encoded = b64encode(new_step_title.encode()).decode()
628             params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
629         elif new_owner_title:
630             title_b64_encoded = b64encode(new_owner_title.encode()).decode()
631             params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
632         return f'/process?{params}'
633
634     def do_POST_condition_descriptions(self) -> str:
635         """Update history timestamps for Condition.description."""
636         return self._change_versioned_timestamps(Condition, 'description')
637
638     def do_POST_condition_titles(self) -> str:
639         """Update history timestamps for Condition.title."""
640         return self._change_versioned_timestamps(Condition, 'title')
641
642     def do_POST_condition(self) -> str:
643         """Update/insert Condition of ?id= and fields defined in postvars."""
644         id_ = self.params.get_int_or_none('id')
645         for _ in self.form_data.get_all_str('delete'):
646             condition = Condition.by_id(self.conn, id_)
647             condition.remove(self.conn)
648             return '/conditions'
649         condition = Condition.by_id(self.conn, id_, create=True)
650         condition.is_active = self.form_data.get_all_str('is_active') != []
651         condition.title.set(self.form_data.get_str('title'))
652         condition.description.set(self.form_data.get_str('description'))
653         condition.save(self.conn)
654         return f'/condition?id={condition.id_}'