From cf116472e137d4fcbcf6ce909de05ef75fb984f8 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Mon, 11 Dec 2023 05:09:33 +0100
Subject: [PATCH] Improve todo accounting.

---
 todo.py | 578 ++++++++++++++++++++++++++++++++++++++++----------------
 1 file changed, 412 insertions(+), 166 deletions(-)

diff --git a/todo.py b/todo.py
index a9e1807..d4ca1e7 100644
--- a/todo.py
+++ b/todo.py
@@ -1,7 +1,7 @@
 from plomlib import PlomDB, run_server, PlomHandler, PlomException 
 import json
 from uuid import uuid4
-from datetime import datetime
+from datetime import datetime, timedelta
 from urllib.parse import parse_qs
 from jinja2 import Template
 from urllib.parse import urlparse
@@ -11,13 +11,24 @@ server_port = 8082
 
 html_head = """
 <style>
-td { border: 1px solid black; }
+tr:nth-child(even) {
+    background-color: #f2f2f2;
+}
+tr:nth-child(odd) {
+    background-color: #ffffff;
+}
+th, td { border: 1px solid black; text-align: left; vertical_align: top; }
+td details { display: inline }
+td.input { width: 100%; }
+td.checkbox { width: 1.5em; }
+th.checkbox { width: 1.5em; }
+input[type="text"] { width: 100%; box-sizing: border-box; }
 </style>
 <body>
-<a href="{{prefix}}/all">all</a> | edit day: 
-<a href="{{prefix}}/day">choose</a>
-<a href="{{prefix}}/day?hide_unchosen=1">do</a>
-<a href="{{prefix}}/coming">coming</a>
+tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day: 
+<a href="{{db.prefix}}/day{% if date %}?date={{date}}{% endif %}">choose tasks</a>
+<a href="{{db.prefix}}/day?{% if date %}date={{date}}&{% endif %}hide_unchosen=1">do tasks</a>
+| <a href="{{db.prefix}}/calendar?t_and=calendar">calendar</a>
 <hr />
 """
 form_footer = '\n</form>'
@@ -25,20 +36,55 @@ form_footer = '\n</form>'
 form_header_tmpl = """
 <form action="{{action|e}}" method="POST">
 """
-archived_days_tmpl = """
+calendar_tmpl = """
 <table>
 {% for date, day in days.items() | sort(reverse=True) %}
-{% if day.archived %}
-<tr><td>{{ date }} {{ day.weekday }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
+<tr><td colspan=3><a href="{{db.prefix}}/day?date={{date}}&hide_unchosen=1">{{ date }}</a> {{ day.weekday }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }}</td></tr>
 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
-<tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
-{% endfor %}
+{% 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 }}">{{ todo.title }}</a></td><td>{{ todo.comment|e }}</td></tr>
 {% endif %}
 {% endfor %}
+{% endfor %}
+</table>
+"""
+todo_tmpl = """
+<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=5 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>
 </table>
+<input type="submit" value="update" />
 """
-selected_day_tmpl = """
-hiden unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
+task_tmpl = """
+<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=5 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 class="input"><input name="tags" type="text" value="{{ task.tags_joined|e }}" ><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" />
+"""
+# archived_days_tmpl = """
+# <table>
+# {% for date, day in days.items() | sort(reverse=True) %}
+# {% if day.archived %}
+# <tr><td>{{ date }} {{ day.weekday }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
+# {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
+# <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
+# {% endfor %}
+# {% endif %}
+# {% endfor %}
+# </table>
+# """
+day_tmpl = """
+<input type="submit" value="OK">
+hide unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
 mandatory tags: {% for t_tag in db.t_tags | sort %}
 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
 {% endfor %}
@@ -46,33 +92,95 @@ mandatory tags: {% for t_tag in db.t_tags | sort %}
 forbidden tags: {% for t_tag in db.t_tags | sort %}
 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
 {% endfor %}
+</p>
+
+<p>
+<input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
+<a href="{{db.prefix}}/day?date={{prev_date}}{% if db.hide_unchosen %}&hide_unchosen=1{% endif %}">prev</a> <a href="{{db.prefix}}/day?date={{next_date}}{% if db.hide_unchosen %}&hide_unchosen=1{% endif %}">next</a> date: <input name="new_selected_date" value="{{ db.selected_date }}" size=8 /> {{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) comment: <input name="comment" value="{{ db.selected_day.comment|e }}">
+</p>
+
 <table>
-<tr><th colspan=2></th><th>date</th><td colspan=2><input name="selected_day_date" value="{{ db.selected_day_date }}" size=8 /></td><th>archive?</th><td><input type="checkbox" name="archive_day" /></td><td>{{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}})</td><th>comment:</th><td><input name="comment" value="{{ db.selected_day.comment|e }}"></td></tr>
-<tr><th>default<br />weight</th><th>title</th><th>tags</th><th>choose?</th><th>done?</th><th colspan=2>day<br />weight</th></tr>
+<tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>comment</th></tr>
 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
 {% if t.visible %}
-<input name="t_uuid" value="{{ uuid }}" type="hidden" >
 <tr>
-<td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
-<td><input name="t_title" value="{{ t.title|e }}"/></td>
-<td><input name="t_tags" value="{{ t.tags_joined|e }}" >
+<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?date={{ db.selected_date }}&t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</details></td>
 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
-<td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].done %}checked{% endif %} ></td>
-<td colspan=2><input name="day_weight" type="number" step=0.1 size=5 value="{% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].day_weight %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" ></td>
+<td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].done %}checked{% endif %} ></td>
+<td class="checkbox"><input name="day_weight" type="number" step=0.1 size=5 value="{% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].day_weight %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" placeholder={{ t.current_default_weight }} ></td>
+<td type="input"><input name="todo_comment" type="text" value="{% if uuid in db.selected_day.todos.keys() %}{{ db.selected_day.todos[uuid].comment|e }}{% endif %}" ></td>
 </tr>
 {% endif %}
 {% endfor %}
 </table>
 <input type="submit" value="OK">
 """
+tasks_tmpl = """
+<p>
+<input type="submit" value="OK"> mandatory tags: {% for t_tag in db.t_tags | sort %}
+<input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
+{% endfor %}
+<br />
+forbidden tags: {% for t_tag in db.t_tags | sort %}
+<input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
+{% endfor %}
+</p>
+<table>
+<tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
+{% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
+{% if t.visible %}
+<tr>
+<td>{{ 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>
+"""
+# selected_day_tmpl = """
+# <p>
+# hide unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
+# mandatory tags: {% for t_tag in db.t_tags | sort %}
+# <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
+# {% endfor %}
+# <br />
+# forbidden tags: {% for t_tag in db.t_tags | sort %}
+# <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
+# {% endfor %}
+# </p>
+# 
+# <p>
+# <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
+# date: <input name="new_selected_date" value="{{ db.selected_date }}" size=8 /> {{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) comment: <input name="comment" value="{{ db.selected_day.comment|e }}">
+# </p>
+# 
+# <table>
+# <tr><th>default<br />weight</th><th>title</th><th>tags</th><th>choose?</th><th>done?</th><th>day<br />weight</th></tr>
+# {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
+# {% if t.visible %}
+# <input name="t_uuid" value="{{ uuid }}" type="hidden" >
+# <tr>
+# <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
+# <td><input name="t_title" value="{{ t.title|e }}"/></td>
+# <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
+# <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
+# <td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].done %}checked{% endif %} ></td>
+# <td colspan=2><input name="day_weight" type="number" step=0.1 size=5 value="{% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].day_weight %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" ></td>
+# </tr>
+# {% endif %}
+# {% endfor %}
+# </table>
+# <input type="submit" value="OK">
+# """
 
 class Task:
 
-    def __init__(self, db, title_history={}, tags_history={}, default_weight_history={}):
+    def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
         self.db = db
-        self.title_history = title_history.copy()
-        self.tags_history = tags_history.copy()
-        self.default_weight_history = default_weight_history.copy()
+        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.visible = True
 
     def _set_with_history(self, history, value):
@@ -92,30 +200,34 @@ class Task:
                 {k: set(v) for k, v in d['tags_history'].items()},
                 d['default_weight_history'])
 
-    def tags_from_joined_string(self, tags_string):
-        tags = set()
-        for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
-            tags.add(tag)
-        self.set_tags(tags)
-
     @property
-    def tags_joined(self):
-        return ';'.join(sorted(list(self.tags)))
+    def default_weight(self):
+        return self._last_of_history(self.default_weight_history, 1)
 
-    def set_default_weight(self, default_weight):
+    @default_weight.setter
+    def default_weight(self, default_weight):
         self._set_with_history(self.default_weight_history, default_weight)
 
-    @property
-    def default_weight(self):
-        return self._last_of_history(self.default_weight_history, 1)
+    def default_weight_at(self, queried_date):
+        ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]] 
+        for date_key, default_weight in self.default_weight_history.items():
+            if date_key > f'{queried_date} 23:59:59':
+                break
+            ret = default_weight 
+        return ret
 
-    def set_title(self, title):
-        self._set_with_history(self.title_history, title)
+    @property
+    def current_default_weight(self):
+        return self.default_weight_at(self.db.selected_date)
 
     @property
     def title(self):
         return self._last_of_history(self.title_history, '')
 
+    @title.setter
+    def title(self, title):
+        self._set_with_history(self.title_history, title)
+
     def title_at(self, queried_date):
         ret = self.title_history[sorted(self.title_history.keys())[0]] 
         for date_key, title in self.title_history.items():
@@ -124,25 +236,47 @@ class Task:
             ret = title
         return ret
 
-    def set_tags(self, tags):
-        self._set_with_history(self.tags_history, set(tags))
+    @property
+    def current_title(self):
+        return self.title_at(self.db.selected_date)
 
     @property
     def tags(self):
         return self._last_of_history(self.tags_history, set())
 
+    @tags.setter
+    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
+
     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}
 
+    @property
+    def id_(self):
+        for k, v in self.db.tasks.items():
+            if v == self:
+                return k
+
 
 class Day:
 
-    def __init__(self, db, todos={}, comment=''):
+    def __init__(self, db, todos=None, comment=''):
         self.db = db
-        self.todos = todos 
+        self.todos = todos if todos else {} 
         self.comment = comment
         self.archived = True 
 
@@ -163,6 +297,7 @@ class Day:
 
     def add_todo(self, id_, dict_source=None):
         self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
+        return self.todos[id_]
 
     def _todos_sum(self, include_undone=False):
         s = 0
@@ -181,49 +316,67 @@ class Day:
     def todos_sum2(self):
         return self._todos_sum(True)
 
+    @property
+    def date(self):
+        for k, v in self.db.days.items():
+            if v == self:
+                return k
+
 class Todo:
 
-    def __init__(self, day, done=False, day_weight=None):
+    def __init__(self, day, done=False, day_weight=None, comment=''):
         self.day = day 
         self.done = done
         self.day_weight = day_weight
+        self.comment = comment
 
     @classmethod
     def from_dict(cls, day, d):
-        return cls(day, d['done'], d['day_weight'])
+        return cls(day, d['done'], d['day_weight'], d['comment'])
 
     def to_dict(self):
-        return {'done': self.done, 'day_weight': self.day_weight}
+        return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment}
+
+    @property
+    def default_weight(self):
+        return self.task.default_weight_at(self.day.date)
 
     @property
     def weight(self):
         if self.day_weight:
             return self.day_weight
         else:
-            task_uuid = [k for k,v in self.day.todos.items() if v == self][0]
-            return self.day_weight if self.day_weight else self.day.db.tasks[task_uuid].default_weight
+            return self.day_weight if self.day_weight else self.default_weight
+
+    @property
+    def task(self):
+        for k, v in self.day.todos.items():
+            if v == self:
+                return self.day.db.tasks[k]
+
+    @property
+    def title(self):
+        return self.task.title_at(self.day.date)
 
 
 class TodoDB(PlomDB):
 
-    def __init__(self, prefix, t_filter_and = set(), t_filter_not = set(), hide_unchosen=False):
+    def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False):
         self.prefix = prefix
-        self.t_filter_and = t_filter_and
-        self.t_filter_not = t_filter_not
+        self.selected_date = selected_date if selected_date else str(datetime.now())[:10] 
+        self.t_filter_and = t_filter_and if t_filter_and else set()
+        self.t_filter_not = t_filter_not if t_filter_not else set()
         self.hide_unchosen = hide_unchosen 
         self.days = {}
         self.tasks = {}
         self.t_tags = set() 
         super().__init__(db_path)
-        if not hasattr(self, 'selected_day_date'):
-            self.switch_to_day()
+        self.switch_to_day()
 
     def read_db_file(self, f):
         d = json.load(f)
-        self.selected_day_date = d['selected_day_date'] 
         for date, day_dict in d['days'].items():
             self.days[date] = self.add_day(dict_source=day_dict)
-        self.selected_day.archived = False 
         for uuid, t_dict in d['tasks'].items():
             t = self.add_task(id_=uuid, dict_source=t_dict)
             t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
@@ -234,7 +387,6 @@ class TodoDB(PlomDB):
 
     def to_dict(self):
         d = {
-                'selected_day_date': self.selected_day_date,
                 't_filter_and': list(self.t_filter_and),
                 't_filter_not': list(self.t_filter_not),
                 'tasks': {},
@@ -248,21 +400,19 @@ class TodoDB(PlomDB):
 
     @property
     def selected_day(self):
-        return self.days[self.selected_day_date]
+        return self.days[self.selected_date]
 
     def write(self):
         self.write_text_to_db(json.dumps(self.to_dict()))
 
     def switch_to_day(self, date=None):
-        if self.selected_day_date in self.days.keys():
-            self.selected_day.archived = True 
         if date:
-            self.selected_day_date = date 
-        else:
-            self.selected_day_date = str(datetime.now())[:10]
-        if not self.selected_day_date in self.days.keys():
-            self.days[self.selected_day_date] = self.add_day()
-        self.selected_day.archived = False 
+            self.selected_date = date 
+            # if self.selected_date in self.days.keys():
+            #      self.selected_day.archived = True 
+        if not self.selected_date in self.days.keys():
+            self.days[self.selected_date] = self.add_day()
+        # self.selected_day.archived = False 
 
     def add_task(self, id_=None, dict_source=None, return_id=False):
         t = Task.from_dict(self, dict_source) if dict_source else Task(self)
@@ -276,36 +426,69 @@ class TodoDB(PlomDB):
     def add_day(self, dict_source=None):
         return Day.from_dict(self, dict_source) if dict_source else Day(self)
 
-    def show_all(self):
-        for i in range(10):
-            self.add_task(id_=f'new{i}') 
-        for date, day in self.days.items():
-            for task_uuid, todo in day.todos.items():
-                todo.title = self.tasks[task_uuid].title_at(date)
-        return Template(form_header_tmpl + selected_day_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all', days=self.days)
-
-    def show_selected_day(self):
-        return Template(form_header_tmpl + selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
-
-    def show_coming(self):
-        from datetime import timedelta
+    # def show_all(self):
+    #     for i in range(10):
+    #         self.add_task(id_=f'new{i}') 
+    #     return Template(form_header_tmpl + selected_day_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all', days=self.days)
+
+     #def show_selected_day(self):
+     #    return Template(form_header_tmpl + selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
+
+    def show_day(self):
+        current_date = datetime.strptime(self.selected_date, '%Y-%m-%d') 
+        prev_date = current_date - timedelta(days=1) 
+        prev_date_str = prev_date.strftime('%Y-%m-%d')
+        next_date = current_date + timedelta(days=1) 
+        next_date_str = next_date.strftime('%Y-%m-%d')
+        return Template(form_header_tmpl + day_tmpl + form_footer).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):
+        days_to_show = {}
+        target_start = start_date_str if start_date_str else sorted(self.days.keys())[0]
+        target_start = str(datetime.now())[:10] if 'today' == target_start else target_start
+        target_end = end_date_str if end_date_str else sorted(self.days.keys())[-1]
         todays_date = str(datetime.now())[:10]
-        days_to_show = self.days.copy()
-        for day in days_to_show.values():
-            day.archived = False 
-        last_date = sorted(days_to_show.keys())[-1]
-        start_date = datetime.strptime(todays_date, '%Y-%m-%d')
-        end_date = datetime.strptime(last_date, '%Y-%m-%d')
+        start_date = datetime.strptime(target_start, '%Y-%m-%d')
+        end_date = datetime.strptime(target_end, '%Y-%m-%d')
         for n in range(int((end_date - start_date).days) + 1):
             current_date_obj = start_date + timedelta(n)
             current_date = current_date_obj.strftime('%Y-%m-%d') 
-            if current_date not in days_to_show.keys():
+            if current_date not in self.days.keys():
                 days_to_show[current_date] = self.add_day()
-            days_to_show[current_date].archived = True 
+            else:
+                days_to_show[current_date] = self.days[current_date] 
             days_to_show[current_date].weekday = datetime.strptime(current_date, '%Y-%m-%d').strftime('%A')
             for task_uuid, todo in days_to_show[current_date].todos.items():
-                todo.title = self.tasks[task_uuid].title_at(current_date)
-        return Template(form_header_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/day', days=days_to_show)
+                todo.visible = self.tasks[task_uuid].visible
+        return Template(calendar_tmpl).render(db=self, days=days_to_show)
+
+    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')
+
+    def update_todo(self, task_uuid, date, day_weight, done, comment):
+        if task_uuid in self.days[date].todos.keys():
+            todo = self.days[date].todos[task_uuid]
+        else:
+            todo = self.days[date].add_todo(task_uuid)
+        # todo = self.days[date].todos[task_uuid]
+        todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
+        todo.done = done 
+        todo.comment = comment 
+
+    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')
+
+    def update_task(self, id_, title, default_weight, tags_joined):
+        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
+        task.tags_joined = tags_joined
+
+    def show_tasks(self):
+        return Template(form_header_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
+
 
 
 class TodoHandler(PlomHandler):
@@ -322,82 +505,134 @@ class TodoHandler(PlomHandler):
     def write_db(self):
         from urllib.parse import urlencode
         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
-        db = TodoDB(prefix)
         length = int(self.headers['content-length'])
         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
-        # import pprint
-        # pp = pprint.PrettyPrinter(indent=4)
-        # pp.pprint(postvars)
-        db.t_filter_and = set()
-        db.t_filter_not = set()
-        if 't_filter_and' in postvars.keys():
-            for target in postvars['t_filter_and']:
-                db.t_filter_and.add(target) 
-        if 't_filter_not' in postvars.keys():
-            for target in postvars['t_filter_not']:
-                db.t_filter_not.add(target) 
-        if 'hide_unchosen' in postvars.keys():
-            db.hide_unchosen = True
-        if 't_uuid' in postvars.keys():
-            new_postvars_t_uuid = postvars['t_uuid'].copy()
-            for i, uuid in enumerate(postvars['t_uuid']):
-                if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
-                        new_uuid, t = db.add_task(return_id=True)
-                        new_postvars_t_uuid[i] = new_uuid
-                        for key in [k for k in postvars.keys() if not k == 't_uuid']:
-                            if uuid in postvars[key]:
-                                uuid_index = postvars[key].index(uuid)
-                                postvars[key][uuid_index] = new_uuid
-            postvars['t_uuid'] = new_postvars_t_uuid
-            for i, uuid in enumerate(postvars['t_uuid']):
-                if len(uuid) < 36:
-                    continue
-                t = db.tasks[uuid]
-                t.set_title(postvars['t_title'][i])
-                t.tags_from_joined_string(postvars['t_tags'][i])
-                t.set_default_weight(float(postvars['t_default_weight'][i]))
-                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():
+        parsed_url = urlparse(self.path)
+        db = TodoDB(prefix=prefix)
+        if parsed_url.path == prefix + '/todo':
+            task_uuid = postvars['task_uuid'][0]
+            date = postvars['date'][0]
+            db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0])
+            homepage = f'{prefix}/todo?task={task_uuid}&date={date}'
+        elif parsed_url.path == prefix + '/task':
+            id_ = postvars['id'][0]
+            db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags'][0])
+            homepage = f'{prefix}/task?id={id_}'
+        elif parsed_url.path in {prefix + '/tasks', prefix + '/day'}:
+            if 't_filter_and' in postvars.keys():
+                for target in postvars['t_filter_and']:
+                    db.t_filter_and.add(target) 
+            if 't_filter_not' in postvars.keys():
+                for target in postvars['t_filter_not']:
+                    db.t_filter_not.add(target) 
+            if 'hide_unchosen' in postvars.keys():
+                db.hide_unchosen = True
+            data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] + [('hide_unchosen', int(db.hide_unchosen))]
+            if parsed_url.path == prefix + '/tasks':
+                encoded_params = urlencode(data)
+                homepage = f'{prefix}/tasks?{encoded_params}'
+            elif parsed_url.path == prefix + '/day':
+                db.switch_to_day(postvars['original_selected_date'][0])
+                new_selected_date = postvars['new_selected_date'][0]
+                try:
+                    datetime.strptime(new_selected_date, '%Y-%m-%d')
+                except ValueError:
+                    raise PlomException(f"{prefix} bad date string: {new_selected_date}")
+                if new_selected_date != db.selected_date:
+                    if new_selected_date in db.days.keys():
+                        raise PlomException('cannot use same date twice')
+                    else:
+                        db.days[new_selected_date] = db.selected_day
+                        del db.days[db.selected_date]
+                        db.selected_date = new_selected_date
                 for i, uuid in enumerate(postvars['t_uuid']):
-                    if uuid in postvars['choose']:
-                        done = 'done' in postvars and uuid in postvars['done']
-                        day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
-                        db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
-
-        if 'comment' in postvars.keys():
-            db.selected_day.comment = postvars['comment'][0]
-        if 'selected_day_date' in postvars.keys():
-            new_selected_day_date = postvars['selected_day_date'][0]
-            try:
-                datetime.strptime(new_selected_day_date, '%Y-%m-%d')
-            except ValueError:
-                raise PlomException(f"{prefix} bad date string: {new_selected_day_date}")
-            if new_selected_day_date != db.selected_day_date:
-                if new_selected_day_date in db.days.keys():
-                    raise PlomException('cannot use same date twice')
-                else:
-                    db.days[new_selected_day_date] = db.selected_day
-                    del db.days[db.selected_day_date]
-                    db.selected_day_date = new_selected_day_date
-
-        switch_edited_day = None
-        day_edit_prefix = 'edit_'
-        for k in postvars.keys():
-            if k.startswith(day_edit_prefix):
-                switch_edited_day = k[len(day_edit_prefix):]
-                break
-        if 'archive_day' in postvars.keys() or switch_edited_day:
-            db.switch_to_day(switch_edited_day)
+                    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(uuid, db.selected_date, postvars['day_weight'][i], done, postvars['todo_comment'][i])
+                if 'comment' in postvars.keys():
+                    db.selected_day.comment = postvars['comment'][0]
+                data += [('date', db.selected_date)]
+                encoded_params = urlencode(data)
+                homepage = f'{prefix}/day?{encoded_params}'
         db.write()
-        data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] + [('hide_unchosen', int(db.hide_unchosen))]
-        encoded_params = urlencode(data)
-        parsed_url = urlparse(self.path)
-        if prefix + '/day' == parsed_url.path:
-            homepage = f'{prefix}/day?{encoded_params}'
-        else:
-            homepage = f'{prefix}/all?{encoded_params}'
         self.redirect(homepage)
+        # db = TodoDB(prefix=prefix, selected_date=postvars['original_selected_date'][0])
+        # # import pprint
+        # # pp = pprint.PrettyPrinter(indent=4)
+        # # pp.pprint(postvars)
+        # db.t_filter_and = set()
+        # db.t_filter_not = set()
+        # if 't_filter_and' in postvars.keys():
+        #     for target in postvars['t_filter_and']:
+        #         db.t_filter_and.add(target) 
+        # if 't_filter_not' in postvars.keys():
+        #     for target in postvars['t_filter_not']:
+        #         db.t_filter_not.add(target) 
+        # if 'hide_unchosen' in postvars.keys():
+        #     db.hide_unchosen = True
+        # if 't_uuid' in postvars.keys():
+        #     new_postvars_t_uuid = postvars['t_uuid'].copy()
+        #     for i, uuid in enumerate(postvars['t_uuid']):
+        #         if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
+        #             new_uuid, t = db.add_task(return_id=True)
+        #             new_postvars_t_uuid[i] = new_uuid
+        #             for key in [k for k in postvars.keys() if not k == 't_uuid']:
+        #                 if uuid in postvars[key]:
+        #                     uuid_index = postvars[key].index(uuid)
+        #                     postvars[key][uuid_index] = new_uuid
+        #     postvars['t_uuid'] = new_postvars_t_uuid
+        #     for i, uuid in enumerate(postvars['t_uuid']):
+        #         if len(uuid) < 36:
+        #             continue
+        #         t = db.tasks[uuid]
+        #         t.set_title(postvars['t_title'][i])
+        #         t.tags_from_joined_string(postvars['t_tags'][i])
+        #         t.set_default_weight(float(postvars['t_default_weight'][i]))
+        #         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']
+        #                 day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
+        #                 db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
+
+        # if 'comment' in postvars.keys():
+        #     db.selected_day.comment = postvars['comment'][0]
+        # if 'new_selected_date' in postvars.keys():
+        #     new_selected_date = postvars['new_selected_date'][0]
+        #     try:
+        #         datetime.strptime(new_selected_date, '%Y-%m-%d')
+        #     except ValueError:
+        #         raise PlomException(f"{prefix} bad date string: {new_selected_date}")
+        #     if new_selected_date != db.selected_date:
+        #         if new_selected_date in db.days.keys():
+        #             raise PlomException('cannot use same date twice')
+        #         else:
+        #             db.days[new_selected_date] = db.selected_day
+        #             del db.days[db.selected_date]
+        #             db.selected_date = new_selected_date
+
+        # switch_edited_day = None
+        # day_edit_prefix = 'edit_'
+        # for k in postvars.keys():
+        #     if k.startswith(day_edit_prefix):
+        #         switch_edited_day = k[len(day_edit_prefix):]
+        #         db.switch_to_day(switch_edited_day)
+        #         break
+        # db.write()
+        # data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] + [('hide_unchosen', int(db.hide_unchosen))] + [('date', db.selected_date)]
+        # encoded_params = urlencode(data)
+        # if prefix + '/day' == parsed_url.path:
+        #     homepage = f'{prefix}/day?{encoded_params}'
+        # else:
+        #     homepage = f'{prefix}/all?{encoded_params}'
+        # self.redirect(homepage)
 
     def do_GET(self):
         self.try_do(self.show_db)
@@ -406,18 +641,29 @@ class TodoHandler(PlomHandler):
         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
         parsed_url = urlparse(self.path)
         params = parse_qs(parsed_url.query)
+        selected_date = params.get('date', [None])[0]
         t_filter_and = set(params.get('t_and', []))
         t_filter_not = set(params.get('t_not', ['deleted']))
         hide_unchosen_params = params.get('hide_unchosen', [])
         hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
-        db = TodoDB(prefix, t_filter_and, t_filter_not, hide_unchosen)
+        db = TodoDB(prefix, selected_date, t_filter_and, t_filter_not, hide_unchosen)
         if parsed_url.path == prefix + '/day':
-            page = db.show_selected_day()
-        elif parsed_url.path == prefix + '/coming':
-            page = db.show_coming()
-        else:
-            page = db.show_all()
-        header = Template(html_head).render(prefix=prefix)
+            page = db.show_day()
+        elif parsed_url.path == prefix + '/todo':
+            task_uuid = params.get('task', [None])[0]
+            page = db.show_todo(task_uuid, selected_date)
+        elif parsed_url.path == prefix + '/task':
+            id_ = params.get('id', [None])[0]
+            page = db.show_task(id_)
+        elif parsed_url.path == prefix + '/tasks':
+            page = db.show_tasks()
+        elif parsed_url.path == prefix + '/add_task':
+            page = db.show_task(None)
+        else: 
+            start_date = params.get('start', [None])[0]
+            end_date = params.get('end', [None])[0]
+            page = db.show_calendar(start_date, end_date)
+        header = Template(html_head).render(db=db, prefix=prefix, date=selected_date)
         self.send_HTML(header + page)
 
 
-- 
2.30.2