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