From 53b84307929582af2aaeac2247cc57db4a7bedf4 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Wed, 20 Dec 2023 02:39:59 +0100
Subject: [PATCH] Improve todo accounting.

---
 ledger.py                      |  42 ++--
 todo.py                        | 401 +++++++++------------------------
 todo_templates/base.html       |  15 ++
 todo_templates/calendar.html   |  27 +++
 todo_templates/day.html        |  80 +++++++
 todo_templates/tagfilters.html |  37 +++
 todo_templates/task.html       |  47 ++++
 todo_templates/tasks.html      |  27 +++
 todo_templates/todo.html       |  33 +++
 todo_templates/watch_form.html |  19 ++
 10 files changed, 415 insertions(+), 313 deletions(-)
 create mode 100644 todo_templates/base.html
 create mode 100644 todo_templates/calendar.html
 create mode 100644 todo_templates/day.html
 create mode 100644 todo_templates/tagfilters.html
 create mode 100644 todo_templates/task.html
 create mode 100644 todo_templates/tasks.html
 create mode 100644 todo_templates/todo.html
 create mode 100644 todo_templates/watch_form.html

diff --git a/ledger.py b/ledger.py
index 22e36a3..36cca98 100755
--- a/ledger.py
+++ b/ledger.py
@@ -46,13 +46,13 @@ booking_html = """
 </table></p>
 """
 add_form_header = """<form method="POST" action="{{action|e}}">
-<input type="submit" name="check" value="check" />
-<input type="submit" name="revert" value="revert" />
+<input type="submit" name="check" value="check" tabindex="5"  />
+<input type="submit" name="revert" value="revert" tabindex="5"  />
 """
 add_form_footer = """
 <input type="hidden" name="start" value={{start}} />
 <input type="hidden" name="end" value={{end}} />
-<input type="submit" name="save" value="save!">
+<input type="submit" name="save" value="save!" tabindex="5" >
 </form>
 """
 add_free_html = """<br />
@@ -62,27 +62,27 @@ add_free_html = """<br />
 </textarea>
 """
 add_structured_html = """
-<input type="submit" name="add_taxes" value="add taxes" />
-<input type="submit" name="add_taxes2" value="add taxes2" />
-<input type="submit" name="add_sink" value="add sink" />
-<input name="replace_from" />
-<input type="submit" name="replace" value="-> replace ->" />
-<input name="replace_to" />
-<input type="submit" name="add_mirror" value="add mirror" />
+<input type="submit" name="add_taxes" value="add taxes" tabindex="5" />
+<input type="submit" name="add_taxes2" value="add taxes2" tabindex="5"  />
+<input type="submit" name="add_sink" value="add sink" tabindex="5"  />
+<input name="replace_from" tabindex="5"  />
+<input type="submit" name="replace" value="-> replace ->" tabindex="5"  />
+<input name="replace_to" tabindex="5"  />
+<input type="submit" name="add_mirror" value="add mirror" tabindex="5"  />
 <br />
-<input name="date" value="{{date|e}}" size=9 />
-<input name="description" value="{{desc|e}}" list="descriptions" />
-<textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
-<input type="submit" name="line_0_add" value="[+]" />
+<input name="date" value="{{date|e}}" size=9 tabindex="3"  />
+<input name="description" value="{{desc|e}}" list="descriptions" tabindex="3"  />
+<textarea name="line_0_comment" rows=1 cols=20 tabindex="3" >{{head_comment|e}}</textarea>
+<input type="submit" name="line_0_add" value="[+]" tabindex="5"  />
 <br />
 {% for line in booking_lines %}
-<input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
-<input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
-<input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
-<input type="submit" name="line_{{line.i}}_delete" value="[x]" />
-<input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
-<input type="submit" name="line_{{line.i}}_add" value="[+]" />
-<textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
+<input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" tabindex="3" />
+<input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 tabindex="3" />
+<input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" tabindex="5" />
+<input type="submit" name="line_{{line.i}}_delete" value="[x]" tabindex="5" />
+<input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" tabindex="5" />
+<input type="submit" name="line_{{line.i}}_add" value="[+]" tabindex="5" />
+<textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %} tabindex="3">{{line.comment|e}}</textarea>
 <br />
 {% endfor %}
 {% for name, items in datalist_sets.items() %}
diff --git a/todo.py b/todo.py
index 6cade91..46108a8 100644
--- a/todo.py
+++ b/todo.py
@@ -4,198 +4,21 @@ from uuid import uuid4
 from datetime import datetime, timedelta
 from urllib.parse import parse_qs
 from jinja2 import Template
+from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader 
 from urllib.parse import urlparse
 db_path = '/home/plom/org/todo_new.json'
-# db_path = '/home/plom/public_repos/misc/todo_new.json'
 server_port = 8082
 DATE_FORMAT = '%Y-%m-%d'
-
-html_head = """
-<style>
-body { font-family: monospace; }
-table.alternating tr:nth-child(even) {
-    background-color: #f2f2f2;
-}
-table.alternating tr:nth-child(odd) {
-    background-color: #ffffff;
-}
-th, td { text-align: left; vertical_align: top; border-bottom: 1px dotted black; }
-td details { display: inline }
-td.input { width: 100%; }
-td.number { text-align: right; }
-td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
-tr.week_row td { height: 0.1em; border: 0px; background-color: black; }
-tr.day_row td { background-color: #f2f2f2 }
-input { font-family: monospace; padding: 0em; margin: 0em; }
-input[type="number"] { font-family: monospace; text-align: right; }
-input[type="text"] { width: 100%; box-sizing: border-box; }
-</style>
-<body>
-tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day:
-<a href="{{db.prefix}}/day?hide_unchosen=0&hide_done=0">choose tasks</a>
-<a href="{{db.prefix}}/day?hide_unchosen=1&hide_done=1">do tasks</a>
-| <a href="{{db.prefix}}/calendar">calendar</a>
-| <a href="{{db.prefix}}/unset_cookie">unset cookie</a>
-<hr />
-"""
-form_footer = '\n</form>'
-form_header_tmpl = """
-<form action="{{action|e}}" method="POST">
-"""
-calendar_tmpl = """
-<p>
-from: <input name="start" {% if start_date %}value="{{ start_date }}"{% endif %} placeholder="{{ today }}" />
-to: <input name="end" {% if end_date %}value="{{ end_date }}"{% endif %} placeholder="2030-12-31" />
-<input type="submit" value="OK" />
-</p>
-<table>
-{% for date, day in days.items() | sort() %}
-{% if day.weekday == "Mo" %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
-<tr class="day_row"><td colspan=3><a href="{{db.prefix}}/day?selected_date={{date}}&hide_unchosen=1">{{ day.weekday }} {{ date }}</a> |{{ '%04.1f' % day.todos_sum|round(2) }}| {{ day.comment|e }}</td></tr>
-{% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
-{% if todo.visible %}
-<tr><td class="checkbox">{% if todo.done %}✓{% else %}&nbsp;&nbsp;{% endif %}</td><td><a href="{{db.prefix}}/todo?task={{ todo.task.id_ }}&date={{ date }}">{%if "cancelled" in todo.tags%}<s>{% endif %}{% if "deadline" in todo.tags %}DEADLINE: {% endif %}{{ todo.title|e }}{%if "cancelled" in todo.tags%}</s>{% endif %}</a></td><td>{{ todo.comment|e }}</td></tr>
-{% endif %}
-{% endfor %}
-{% endfor %}
-</table>
-"""
-todo_tmpl = """
-<h3>todo</h3>
-<input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
-<input type="hidden" name="date" value="{{ todo.day.date }}" />
-<table>
-<tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
-<tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
-<tr><th>day</th><td>{{ todo.day.date }}</td></tr>
-<tr><th>day weight</th><td class="input"><input type="number" name="day_weight" step=0.1 size=8 value="{{ todo.day_weight }}" /></td></tr>
-<tr><th>comment</th><td class="input"><input type="text" name="comment" value="{{todo.comment|e}}" /></td></tr>
-<tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
-<tr><th>day tags</th>
-<td>
-{% for tag in db.t_tags | sort %}
-{% if tag in todo.task.tags %}&nbsp;✓{% else %}<input type="checkbox" name="day_tag_{{tag|e}}"{% if tag in todo.day_tags %} checked{% endif %}/>{% endif %} {{ tag }}<br />
-{% endfor %}
-add: <input name="day_tags_joined" type="text" value="" >
-</td>
-</tr>
-</table>
-<input type="submit" value="update" />
-"""
-task_tmpl = """
-<h3>task</h3>
-<input type="hidden" name="id" value="{{ task.id_ }}" />
-<table>
-<tr><th>title</th><td class="input"><input name="title" type="text" value="{{ task.title|e }}" /><details><summary>history</summary><ul>{% for k,v in task.title_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
-<tr><th>default weight</th><td class="input"><input type="number" name="default_weight" value="{{ task.default_weight }}" step=0.1 size=8 required /><details><summary>history</summary><ul>{% for k,v in task.default_weight_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
-<tr><th>tags</th>
-<td>
-{% for tag in db.t_tags | sort %}
-<input type="checkbox" name="tag_{{tag|e}}"{% if tag in task.tags %} checked{% endif %}/> {{ tag }}<br />
-{% endfor %}
-add: <input name="tags_joined" type="text" value="" ><br />
-<details><summary>history</summary><ul>{% for k,v in task.tags_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details>
-</td></tr>
-</table>
-<input type="submit" value="update" />
-"""
-day_tmpl = """
-<p>
-<input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /> hide unchosen <input name="hide_done" type="checkbox" {% if db.hide_done %}checked{% endif %} /> hide done |
-<a href="{{db.prefix}}/day?selected_date={{prev_date}}">prev</a> <a href="{{db.prefix}}/day?selected_date={{next_date}}">next</a> |
-<input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
-date: <input name="new_selected_date" value="{{ db.selected_date }}" size=10 /> |
-{{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) |
-comment: <input name="day_comment" value="{{ db.selected_day.comment|e }}">
-</p>
-
-<table class="alternating">
-<tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>edit?</th><th>day tags</th><th>comment</th></tr>
-{% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
-{% if t.visible and (uuid not in db.selected_day.todos.keys() or db.selected_day.todos[uuid].visible) %}
-<tr>
-<input name="t_uuid" value="{{ uuid }}" type="hidden" >
-<td><details><summary>] <a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.current_title|e }}</a></summary>tags: {% for tag in t.tags | sort %}<a href="{{db.prefix}}/day?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</details></td>
-{% if uuid in db.selected_day.todos.keys() %}
-<td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}" checked></td>
-<td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}" {% if db.selected_day.todos[uuid].done %}checked{% endif %}></td>
-<td class="checkbox"><input name="day_weight" type="number" step=0.1 size=8 value="{% if db.selected_day.todos[uuid].day_weight is not none %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" placeholder={{ t.current_default_weight }} ></td>
-<td><a href="{{db.prefix}}/todo?task={{uuid}}&date={{ db.selected_date }}">edit</a></td>
-<td>{% for tag in db.selected_day.todos[uuid].day_tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
-<td>{{ db.selected_day.todos[uuid].comment|e }}</td>
-{% else %}
-<td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}"</td>
-<td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}"></td>
-<td class="checkbox"><input name="day_weight" type="number" step=0.1 size=8 placeholder={{ t.current_default_weight }} ></td>
-<td></td>
-<td></td>
-<td></td>
-{% endif %}
-</tr>
-{% endif %}
-{% endfor %}
-</table>
-<input type="submit" value="OK">
-"""
-tag_filters_tmpl = """
-<p style="float: left; margin-right: 1em;">
-<input type="submit" value="OK">
-</p>
-<p>
-mandatory tags:
-{% for and_filter in db.t_filter_and %}
-<select name="t_and">
-<option></option>
-{% for tag in db.t_tags | sort %}
-<option value="{{tag|e}}" {% if and_filter == tag %}selected{% endif %}>{{tag|e}}</option>
-{% endfor %}
-</select>
-{% endfor %}
-<select name="t_and">
-<option></option>
-{% for tag in db.t_tags | sort %}
-<option value="{{tag|e}}">{{tag|e}}</option>
-{% endfor %}
-</select>
-<br />
-forbidden tags:
-{% for not_filter in db.t_filter_not %}
-<select name="t_not">
-<option></option>
-{% for tag in db.t_tags | sort %}
-<option value="{{tag|e}}" {% if not_filter == tag %}selected{% endif %}>{{tag|e}}</option>
-{% endfor %}
-</select>
-{% endfor %}
-<select name="t_not">
-<option></option>
-{% for tag in db.t_tags | sort %}
-<option value="{{tag|e}}">{{tag|e}}</option>
-{% endfor %}
-</select>
-</p>
-"""
-tasks_tmpl = """
-<table class="alternating">
-<tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
-{% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
-{% if t.visible %}
-<tr>
-<td class="number">{{ t.default_weight }}</a></td>
-<td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
-<td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
-{% endif %}
-{% endfor %}
-</table>
-"""
+j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates'))
 
 class Task:
 
-    def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
+    def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None, links_history=None):
         self.db = db
         self.title_history = title_history if title_history else {}
         self.tags_history = tags_history if tags_history else {}
         self.default_weight_history = default_weight_history if default_weight_history else {}
+        self.links_history = links_history if links_history else {}
         self.visible = True
 
     def _set_with_history(self, history, value):
@@ -209,11 +32,27 @@ class Task:
 
     @classmethod
     def from_dict(cls, db, d):
-        return cls(
-                db,
-                d['title_history'],
-                {k: set(v) for k, v in d['tags_history'].items()},
-                d['default_weight_history'])
+        if 'links_history' in d.keys():
+            return cls(
+                   db,
+                   d['title_history'],
+                   {k: set(v) for k, v in d['tags_history'].items()},
+                   d['default_weight_history'],
+                   {k: set(v) for k, v in d['links_history'].items()})
+        else:
+            return cls(
+                   db,
+                   d['title_history'],
+                   {k: set(v) for k, v in d['tags_history'].items()},
+                   d['default_weight_history'])
+
+    def to_dict(self):
+        return {
+            'title_history': self.title_history,
+            'default_weight_history': self.default_weight_history,
+            'tags_history': {k: list(v) for k,v in self.tags_history.items()},
+            'links_history': {k: list(v) for k,v in self.links_history.items()},
+        }
 
     @property
     def default_weight(self):
@@ -263,22 +102,13 @@ class Task:
     def tags(self, tags):
         self._set_with_history(self.tags_history, set(tags))
 
-    # @property
-    # def tags_joined(self):
-    #     return ';'.join(sorted(list(self.tags)))
-
-    # @tags_joined.setter
-    # def tags_joined(self, tags_string):
-    #     tags = set()
-    #     for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
-    #         tags.add(tag)
-    #     self.tags = tags
+    @property
+    def links(self):
+        return self._last_of_history(self.links_history, set())
 
-    def to_dict(self):
-        return {
-            'title_history': self.title_history,
-            'tags_history': {k: list(v) for k,v in self.tags_history.items()},
-            'default_weight_history': self.default_weight_history}
+    @links.setter
+    def links(self, links):
+        self._set_with_history(self.links_history, set(links))
 
     @property
     def id_(self):
@@ -374,17 +204,6 @@ class Todo:
     def title(self):
         return self.task.title_at(self.day.date)
 
-    # @property
-    # def day_tags_joined(self):
-    #     return ';'.join(sorted(list(self.day_tags)))
-
-    # @day_tags_joined.setter
-    # def day_tags_joined(self, tags_string):
-    #     tags = set()
-    #     for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
-    #         tags.add(tag)
-    #     self.day_tags = tags
-
     @property
     def tags(self):
         return self.day_tags | self.task.tags
@@ -431,8 +250,8 @@ class TodoDB(PlomDB):
 
     def to_dict(self):
         d = {
-                't_filter_and': self.t_filter_and,
-                't_filter_not': self.t_filter_not,
+                # 't_filter_and': self.t_filter_and,
+                # 't_filter_not': self.t_filter_not,
                 'tasks': {},
                 'days': {}
         }
@@ -483,7 +302,7 @@ class TodoDB(PlomDB):
         prev_date_str = prev_date.strftime(DATE_FORMAT)
         next_date = current_date + timedelta(days=1)
         next_date_str = next_date.strftime(DATE_FORMAT)
-        return Template(form_header_tmpl + tag_filters_tmpl + day_tmpl + form_footer).render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str)
+        return j2env.get_template('day.html').render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str)
 
     def show_calendar(self, start_date_str, end_date_str):
         self.t_filter_and = ['calendar']
@@ -505,11 +324,11 @@ class TodoDB(PlomDB):
             else:
                 days_to_show[current_date] = self.days[current_date]
             days_to_show[current_date].weekday = datetime.strptime(current_date, DATE_FORMAT).strftime('%A')[:2]
-        return Template(form_header_tmpl + calendar_tmpl + form_footer).render(db=self, days=days_to_show, action=self.prefix+'/calendar', today=str(datetime.now())[:10], start_date=start_date_str, end_date=end_date_str)
+        return j2env.get_template('calendar.html').render(db=self, days=days_to_show, action=self.prefix+'/calendar', today=str(datetime.now())[:10], start_date=start_date_str, end_date=end_date_str)
 
     def show_todo(self, task_uuid, selected_date):
         todo = self.days[selected_date].todos[task_uuid]
-        return Template(form_header_tmpl + todo_tmpl + form_footer).render(db=self, todo=todo, action=self.prefix+'/todo')
+        return j2env.get_template('todo.html').render(db=self, todo=todo, action=self.prefix+'/todo')
 
     def update_todo_mini(self, task_uuid, date, day_weight, done):
         if task_uuid in self.days[date].todos.keys():
@@ -520,33 +339,39 @@ class TodoDB(PlomDB):
         todo.done = done
         return todo
 
+    def collect_tags(self, tags_joined, tags_checked):
+        tags = set()
+        for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']:
+            tags.add(tag)
+        for tag in tags_checked:
+            tags.add(tag)
+        return tags
+
     def update_todo(self, task_uuid, date, day_weight, done, comment, day_tags_joined, day_tags_checked):
         todo = self.update_todo_mini(task_uuid, date, day_weight, done)
         todo.comment = comment
-        day_tags = set()
-        for tag in [tag.strip() for tag in day_tags_joined.split(';') if tag.strip() != '']:
-            day_tags.add(tag)
-        for tag in day_tags_checked:
-            day_tags.add(tag)
-        todo.day_tags = day_tags
+        todo.day_tags = self.collect_tags(day_tags_joined, day_tags_checked) 
 
     def show_task(self, id_):
         task = self.tasks[id_] if id_ else self.add_task()
-        return Template(form_header_tmpl + task_tmpl + form_footer).render(db=self, task=task, action=self.prefix+'/task')
+        return j2env.get_template('task.html').render(db=self, task=task, action=self.prefix+'/task')
 
-    def update_task(self, id_, title, default_weight, tags_joined, tags_checked):
+    def update_task(self, id_, title, default_weight, tags_joined, tags_checked, links):
         task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
         task.title = title
         task.default_weight = float(default_weight) if len(default_weight) > 0 else None
-        tags = set()
-        for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']:
-            tags.add(tag)
-        for tag in tags_checked:
-            tags.add(tag)
-        task.tags = tags
+        task.tags = self.collect_tags(tags_joined, tags_checked) 
+        task.links = links 
+        for link in links:
+            print("DEBUG DEBUG", links)
+            borrowed_links = self.tasks[link].links 
+            print("DEBUG DEBUG brorowed1", borrowed_links)
+            borrowed_links.add(id_)
+            print("DEBUG DEBUG brorowed2", borrowed_links)
+            self.tasks[link].links = borrowed_links 
 
     def show_tasks(self):
-        return Template(form_header_tmpl + tag_filters_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
+        return j2env.get_template('tasks.html').render(db=self, action=self.prefix+'/tasks')
 
 
 
@@ -576,7 +401,28 @@ class TodoHandler(PlomHandler):
         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
         parsed_url = urlparse(self.path)
         db = TodoDB(prefix=app_config['prefix'])
+        params_to_encode = []
+        if 't_and' in postvars.keys():
+            for target in postvars['t_and']:
+                if len(target) > 0 and not target in db.t_filter_and:
+                    db.t_filter_and += [target]
+            if len(db.t_filter_and) == 0:
+                params_to_encode += [('t_and', '-')]
+        if 't_not' in postvars.keys():
+            for target in postvars['t_not']:
+                if len(target) > 0 and not target in db.t_filter_not:
+                    db.t_filter_not += [target]
+            if len(db.t_filter_not) == 0:
+                params_to_encode += [('t_not', '-')]
+        params_to_encode += [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
 
+        def collect_checked(prefix, postvars):
+            tags_checked = []
+            for k in postvars.keys():
+                if k.startswith(prefix):
+                    tags_checked += [k[len(prefix):]]
+            return tags_checked
+        
         if parsed_url.path == app_config['prefix'] + '/calendar':
             start = postvars['start'][0] if len(postvars['start'][0]) > 0 else '-'
             end = postvars['end'][0] if len(postvars['end'][0]) > 0 else '-'
@@ -585,69 +431,40 @@ class TodoHandler(PlomHandler):
         elif parsed_url.path == app_config['prefix'] + '/todo':
             task_uuid = postvars['task_uuid'][0]
             date = postvars['date'][0]
-            tags_checked = []
-            prefix = 'day_tag_'
-            for k in postvars.keys():
-                if k.startswith(prefix):
-                    tags_checked += [k[len(prefix):]]
-            db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['day_tags_joined'][0], tags_checked)
+            db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['joined_day_tags'][0], collect_checked('day_tag_', postvars))
             homepage = f'{app_config["prefix"]}/todo?task={task_uuid}&date={date}'
 
         elif parsed_url.path == app_config['prefix'] + '/task':
+            encoded_params = urlencode(params_to_encode)
             id_ = postvars['id'][0]
-            tags_checked = []
-            prefix = 'tag_'
-            for k in postvars.keys():
-                if k.startswith(prefix):
-                    tags_checked += [k[len(prefix):]]
-            db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags_joined'][0], tags_checked)
-            homepage = f'{app_config["prefix"]}/task?id={id_}'
+            if 'title' in postvars.keys():
+                db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['joined_tags'][0], collect_checked('tag_', postvars), collect_checked('link_', postvars))
+            homepage = f'{app_config["prefix"]}/task?id={id_}&{encoded_params}'
 
-        elif parsed_url.path in {app_config['prefix'] + '/tasks', app_config['prefix'] + '/day'}:
-            data = []
-            for target in postvars['t_and']:
-                if len(target) > 0 and not target in db.t_filter_and:
-                    db.t_filter_and += [target]
-            if len(db.t_filter_and) == 0:
-                data += [('t_and', '-')]
-            for target in postvars['t_not']:
-                if len(target) > 0 and not target in db.t_filter_not:
-                    db.t_filter_not += [target]
-            if len(db.t_filter_not) == 0:
-                data += [('t_not', '-')]
-            data += [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
-            if parsed_url.path == app_config['prefix'] + '/tasks':
-                encoded_params = urlencode(data)
-                homepage = f'{app_config["prefix"]}/tasks?{encoded_params}'
-
-            elif parsed_url.path == app_config['prefix'] + '/day':
-                db.hide_unchosen = 'hide_unchosen' in postvars.keys()
-                db.hide_done = 'hide_done' in postvars.keys()
-                data += [('hide_unchosen', int(db.hide_unchosen))] + [('hide_done', int(db.hide_done))]
-
-                db.selected_date = postvars['original_selected_date'][0]
-                new_selected_date = postvars['new_selected_date'][0]
-                try:
-                    datetime.strptime(new_selected_date, DATE_FORMAT)
-                except ValueError:
-                    raise PlomException(f'{app_config["prefix"]} bad date string: {new_selected_date}')
-                if new_selected_date != db.selected_date:
-                    db.change_selected_days_date(new_selected_date)
-                if 't_uuid' in postvars.keys():
-                    for i, uuid in enumerate(postvars['t_uuid']):
-                        t = db.tasks[uuid]
-                        if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
-                            del db.selected_day.todos[uuid]
-                    if 'choose' in postvars.keys():
-                        for i, uuid in enumerate(postvars['t_uuid']):
-                            if uuid in postvars['choose']:
-                                done = 'done' in postvars and uuid in postvars['done']
-                                db.update_todo_mini(uuid, db.selected_date, postvars['day_weight'][i], done)
-                if 'day_comment' in postvars.keys():
-                    db.selected_day.comment = postvars['day_comment'][0]
-                data += [('selected_date', db.selected_date)]
-                encoded_params = urlencode(data)
-                homepage = f'{app_config["prefix"]}/day?{encoded_params}'
+        elif parsed_url.path == app_config['prefix'] + '/tasks':
+            encoded_params = urlencode(params_to_encode)
+            homepage = f'{app_config["prefix"]}/tasks?{encoded_params}'
+
+        elif parsed_url.path == app_config['prefix'] + '/day':
+            if 'expect_unchosen_done' in postvars.keys():
+                params_to_encode += [('hide_unchosen', int('hide_unchosen' in postvars.keys()))] + [('hide_done', int('hide_done' in postvars.keys()))]
+            if 'selected_date' in postvars.keys():
+                 db.selected_date = postvars['selected_date'][0]
+                 if 't_uuid' in postvars.keys():
+                     for i, uuid in enumerate(postvars['t_uuid']):
+                         t = db.tasks[uuid]
+                         if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
+                             del db.selected_day.todos[uuid]
+                     if 'choose' in postvars.keys():
+                         for i, uuid in enumerate(postvars['t_uuid']):
+                             if uuid in postvars['choose']:
+                                 done = 'done' in postvars and uuid in postvars['done']
+                                 db.update_todo_mini(uuid, db.selected_date, postvars['day_weight'][i], done)
+                 if 'day_comment' in postvars.keys():
+                     db.selected_day.comment = postvars['day_comment'][0]
+                 params_to_encode += [('selected_date', db.selected_date)]
+            encoded_params = urlencode(params_to_encode)
+            homepage = f'{app_config["prefix"]}/day?{encoded_params}'
 
         db.write()
         self.redirect(homepage)
@@ -671,6 +488,7 @@ class TodoHandler(PlomHandler):
             if selected_date is None and 'selected_date' in cookie_db.keys():
                 selected_date = cookie_db['selected_date']
             cookie_db['selected_date'] = selected_date
+        if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks', app_config['prefix'] + '/task'}:
             t_filter_and = params.get('t_and', None)
             if t_filter_and is None and 't_and' in cookie_db.keys():
                 t_filter_and = cookie_db['t_and']
@@ -737,10 +555,9 @@ class TodoHandler(PlomHandler):
                 end_date = None
             cookie_db['calendar_end'] = end_date
             page = db.show_calendar(start_date, end_date)
-        header = Template(html_head).render(db=db, prefix=app_config['prefix'], date=selected_date)
         if parsed_url.path != app_config['prefix'] + '/unset_cookie':
             self.set_cookie(app_config['cookie_name'], app_config['cookie_path'], cookie_db)
-        self.send_HTML(header + page)
+        self.send_HTML(page)
 
 
 if __name__ == "__main__":
diff --git a/todo_templates/base.html b/todo_templates/base.html
new file mode 100644
index 0000000..882c727
--- /dev/null
+++ b/todo_templates/base.html
@@ -0,0 +1,15 @@
+<style>
+body { font-family: monospace; }
+input { font-family: monospace; padding: 0em; margin: 0em; }
+{% block css %}
+{% endblock %}
+</style>
+<body>
+tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day:
+<a href="{{db.prefix}}/day?hide_unchosen=0&hide_done=0">choose tasks</a>
+<a href="{{db.prefix}}/day?hide_unchosen=1&hide_done=1">do tasks</a>
+| <a href="{{db.prefix}}/calendar">calendar</a>
+| <a href="{{db.prefix}}/unset_cookie">unset cookie</a>
+<hr />
+{% block content %}
+{% endblock %}
diff --git a/todo_templates/calendar.html b/todo_templates/calendar.html
new file mode 100644
index 0000000..8f0aa8e
--- /dev/null
+++ b/todo_templates/calendar.html
@@ -0,0 +1,27 @@
+{% extends 'base.html' %}
+{% block css %}
+tr.week_row td { height: 0.1em; background-color: black; }
+tr.day_row td { background-color: #f2f2f2 }
+td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
+{% endblock %}
+{% block content %}
+<form action="{{action|e}}" method="POST">
+<p>
+from: <input name="start" {% if start_date %}value="{{ start_date }}"{% endif %} placeholder="{{ today }}" />
+to: <input name="end" {% if end_date %}value="{{ end_date }}"{% endif %} placeholder="2030-12-31" />
+<input type="submit" value="OK" />
+</p>
+<table>
+{% for date, day in days.items() | sort() %}
+{% if day.weekday == 'Mo' %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
+<tr class="day_row"><td colspan=3><a href="{{db.prefix}}/day?selected_date={{date}}&hide_unchosen=1">{{ day.weekday }} {{ date }}</a> |{{ '%04.1f' % day.todos_sum|round(2) }}| {{ day.comment|e }}</td></tr>
+{% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
+{% if todo.visible %}
+<tr><td class="checkbox">{% if todo.done %}✓{% else %}&nbsp;&nbsp;{% endif %}</td><td><a href="{{db.prefix}}/todo?task={{ todo.task.id_ }}&date={{ date }}">{%if "cancelled" in todo.tags%}<s>{% endif %}{% if "deadline" in todo.tags %}DEADLINE: {% endif %}{{ todo.title|e }}{%if "cancelled" in todo.tags%}</s>{% endif %}</a></td><td>{{ todo.comment|e }}</td></tr>
+{% endif %}
+{% endfor %}
+{% endfor %}
+</table>
+</form>
+{% endblock %}
+
diff --git a/todo_templates/day.html b/todo_templates/day.html
new file mode 100644
index 0000000..5c63670
--- /dev/null
+++ b/todo_templates/day.html
@@ -0,0 +1,80 @@
+{% extends 'base.html' %}
+{% block css %}
+table.alternating tr:nth-child(even) {
+    background-color: #f2f2f2;
+}
+table.alternating tr:nth-child(odd) {
+    background-color: #ffffff;
+}
+td.checkbox, td.number { height: 0.1em; padding: 0em; text-align: center; }
+td.checkbox { width: 0.1em }
+td button { height: 1.5em; padding: 0em; margin: 0em }
+td details { display: inline }
+input[type="number"] { text-align: right; }
+{% endblock %}
+{% block content %}
+<form action="{{action|e}}" method="POST">
+{% include 'tagfilters.html' %}
+<p>
+<input name="expect_unchosen_done" type="hidden" value="1"/>
+<input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /> hide unchosen <input name="hide_done" type="checkbox" {% if db.hide_done %}checked{% endif %} /> hide done
+</p>
+</form>
+
+<form id="form_to_watch" action="{{action|e}}" method="POST">
+<h3>edit day</h3>
+<p>
+<a href="{{db.prefix}}/day?selected_date={{prev_date}}">prev</a> | {{db.selected_date}} | <a href="{{db.prefix}}/day?selected_date={{next_date}}">next</a> | 
+{{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) |
+comment: <input name="day_comment" value="{{ db.selected_day.comment|e }}">
+<input type="submit" value="update">
+<input type="hidden" name="selected_date" value="{{ db.selected_date }}" />
+</p>
+<table class="alternating">
+<tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>edit?</th><th>day tags</th><th>comment</th></tr>
+{% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
+{% if t.visible and (uuid not in db.selected_day.todos.keys() or db.selected_day.todos[uuid].visible) %}
+<tr>
+<input name="t_uuid" value="{{ uuid }}" type="hidden" >
+<td><details><summary>] <a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.current_title|e }}</a></summary>tags: {% for tag in t.tags | sort %}<a href="{{db.prefix}}/day?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</details></td>
+{% if uuid in db.selected_day.todos.keys() %}
+<td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}" checked></td>
+<td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}" {% if db.selected_day.todos[uuid].done %}checked{% endif %}></td>
+<td class="number"><input class="day_weight_input" name="day_weight" type="number" step=0.1 size=8 value="{% if db.selected_day.todos[uuid].day_weight is not none %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" placeholder={{ t.current_default_weight }} ></td>
+<td><a href="{{db.prefix}}/todo?task={{uuid}}&date={{ db.selected_date }}">edit</a></td>
+<td>{% for tag in db.selected_day.todos[uuid].day_tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
+<td>{{ db.selected_day.todos[uuid].comment|e }}</td>
+{% else %}
+<td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}"</td>
+<td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}"></td>
+<td class="number"><input name="day_weight" type="number" step=0.1 size=8 placeholder={{ t.current_default_weight }} ></td>
+<td></td>
+<td></td>
+<td></td>
+{% endif %}
+</tr>
+{% endif %}
+{% endfor %}
+</table>
+<input type="submit" value="update">
+</form>
+<script>
+var day_weight_inputs = document.getElementsByClassName("day_weight_input");
+for (let i = 0; i < day_weight_inputs.length; i++) {
+    let input = day_weight_inputs[i];
+    let button = document.createElement('button');
+    button.innerHTML = '+1×';
+    button.onclick = function(event) {
+        event.preventDefault();
+        if (input.value) {
+            input.value = parseFloat(input.value) + parseFloat(input.placeholder);
+        } else {
+            input.value = parseFloat(input.placeholder);
+        }
+        input.value = parseFloat(input.value).toFixed(1);
+    };
+    input.insertAdjacentElement('afterend', button);
+}
+</script>
+{% include 'watch_form.html' %}
+{% endblock %}
diff --git a/todo_templates/tagfilters.html b/todo_templates/tagfilters.html
new file mode 100644
index 0000000..3f784ea
--- /dev/null
+++ b/todo_templates/tagfilters.html
@@ -0,0 +1,37 @@
+<p style="float: left; margin-right: 1em;">
+<input type="submit" value="filter">
+</p>
+<p>
+mandatory tags:
+{% for and_filter in db.t_filter_and %}
+<select name="t_and">
+<option></option>
+{% for tag in db.t_tags | sort %}
+<option value="{{tag|e}}" {% if and_filter == tag %}selected{% endif %}>{{tag|e}}</option>
+{% endfor %}
+</select>
+{% endfor %}
+<select name="t_and">
+<option></option>
+{% for tag in db.t_tags | sort %}
+<option value="{{tag|e}}">{{tag|e}}</option>
+{% endfor %}
+</select>
+<br />
+forbidden tags:
+{% for not_filter in db.t_filter_not %}
+<select name="t_not">
+<option></option>
+{% for tag in db.t_tags | sort %}
+<option value="{{tag|e}}" {% if not_filter == tag %}selected{% endif %}>{{tag|e}}</option>
+{% endfor %}
+</select>
+{% endfor %}
+<select name="t_not">
+<option></option>
+{% for tag in db.t_tags | sort %}
+<option value="{{tag|e}}">{{tag|e}}</option>
+{% endfor %}
+</select>
+</p>
+
diff --git a/todo_templates/task.html b/todo_templates/task.html
new file mode 100644
index 0000000..56d0abe
--- /dev/null
+++ b/todo_templates/task.html
@@ -0,0 +1,47 @@
+{% extends 'base.html' %}
+{% block css %}
+th, td { vertical-align: top; text-align: left}
+td.input { width: 100%; }
+td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
+input[type="number"] { text-align: right; }
+input[type="text"] { width: 100% }
+textarea { width: 100% };
+{% endblock %}
+{% block content %}
+<form id="form_to_watch" action="{{action|e}}" method="POST">
+<h3>edit task</h3>
+<input type="hidden" name="id" value="{{ task.id_ }}" />
+<table>
+<tr><th>title</th><td class="input"><input name="title" type="text" value="{{ task.title|e }}" /><details><summary>history</summary><ul>{% for k,v in task.title_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
+<tr><th>default weight</th><td class="input"><input type="number" name="default_weight" value="{{ task.default_weight }}" step=0.1 size=8 required /><details><summary>history</summary><ul>{% for k,v in task.default_weight_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
+<tr><th>tags</th>
+<td>
+{% for tag in db.t_tags | sort %}
+<input type="checkbox" name="tag_{{tag|e}}"{% if tag in task.tags %} checked{% endif %}/> {{ tag }}<br />
+{% endfor %}
+add: <input name="joined_tags" type="text" value="" ><br />
+<details><summary>history</summary><ul>{% for k,v in task.tags_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details>
+</td></tr>
+<tr><th>links</th>
+<td>
+{% for other_task_id, other_task in db.tasks.items() | sort(attribute='1.title') %}
+{% if task.id_ != other_task_id and other_task.visible and other_task_id in task.links %}
+<input name="link_{{other_task_id}}" type="checkbox" checked /> <a href="{{db.prefix}}/task?id={{ other_task_id }}">{{ other_task.title|e }}</a><br />
+{% endif %}
+{% endfor %}
+{% for other_task_id, other_task in db.tasks.items() | sort(attribute='1.title') %}
+{% if task.id_ != other_task_id and other_task.visible and not other_task_id in task.links %}
+<input name="link_{{other_task_id}}" type="checkbox"/> <a href="{{db.prefix}}/task?id={{ other_task_id }}">{{ other_task.title|e }}</a><br />
+{% endif %}
+{% endfor %}
+</td>
+</tr>
+</table>
+<input type="submit" value="update" />
+</form>
+<form action="{{action|e}}" method="POST">
+<input type="hidden" name="id" value="{{ task.id_ }}" />
+{% include 'tagfilters.html' %}
+</form>
+{% include 'watch_form.html' %}
+{% endblock %}
diff --git a/todo_templates/tasks.html b/todo_templates/tasks.html
new file mode 100644
index 0000000..34976eb
--- /dev/null
+++ b/todo_templates/tasks.html
@@ -0,0 +1,27 @@
+{% extends 'base.html' %}
+{% block css %}
+table.alternating tr:nth-child(even) {
+    background-color: #f2f2f2;
+}
+table.alternating tr:nth-child(odd) {
+    background-color: #ffffff;
+}
+td.number { text-align: right; }
+{% endblock %}
+{% block content %}
+<form action="{{action|e}}" method="POST">
+{% include 'tagfilters.html' %}
+</form>
+<table class="alternating">
+<tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
+{% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
+{% if t.visible %}
+<tr>
+<td class="number">{{ t.default_weight }}</a></td>
+<td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
+<td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tasks?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
+{% endif %}
+{% endfor %}
+</table>
+{% endblock %}
+
diff --git a/todo_templates/todo.html b/todo_templates/todo.html
new file mode 100644
index 0000000..b3926da
--- /dev/null
+++ b/todo_templates/todo.html
@@ -0,0 +1,33 @@
+{% extends 'base.html' %}
+{% block css %}
+th, td { vertical-align: top; text-align: left}
+td.input { width: 100%; }
+td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
+input[type="number"] { text-align: right; }
+input[type="text"] { width: 100% }
+textarea { width: 100% };
+{% endblock %}
+{% block content %}
+<form action="{{action|e}}" method="POST">
+<h3>edit todo</h3>
+<input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
+<input type="hidden" name="date" value="{{ todo.day.date }}" />
+<table>
+<tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
+<tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
+<tr><th>day</th><td>{{ todo.day.date }}</td></tr>
+<tr><th>day weight</th><td class="input"><input type="number" name="day_weight" step=0.1 size=8 value="{{ todo.day_weight }}" /></td></tr>
+<tr><th>comment</th><td class="input"><textarea name="comment">{{todo.comment|e}}</textarea></td></tr>
+<tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
+<tr><th>day tags</th>
+<td>
+{% for tag in db.t_tags | sort %}
+{% if tag in todo.task.tags %}&nbsp;✓{% else %}<input type="checkbox" name="day_tag_{{tag|e}}"{% if tag in todo.day_tags %} checked{% endif %}/>{% endif %} {{ tag }}<br />
+{% endfor %}
+add: <input name="joined_day_tags" type="text" value="" >
+</td>
+</tr>
+</table>
+<input type="submit" value="update" />
+</form>
+{% endblock %}
diff --git a/todo_templates/watch_form.html b/todo_templates/watch_form.html
new file mode 100644
index 0000000..979c1da
--- /dev/null
+++ b/todo_templates/watch_form.html
@@ -0,0 +1,19 @@
+<script>
+    var formHasChanged = false;
+    var submitted = false;
+    var form_to_watch = document.getElementById('form_to_watch');
+    form_to_watch.addEventListener('input', function() {
+        formHasChanged = true;
+    });
+    form_to_watch.addEventListener('submit', function() {
+        submitted = true;
+    });
+    window.addEventListener('beforeunload', function(event) {
+        if (formHasChanged && !submitted) {
+            var confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
+            event.returnValue = confirmationMessage;
+            return confirmationMessage;
+        }
+    });
+</script> 
+
-- 
2.30.2