home · contact · privacy
Improve todo accounting.
[misc] / todo.py
1 from plomlib import PlomDB, run_server, PlomHandler, PlomException 
2 import json
3 from uuid import uuid4
4 from datetime import datetime, timedelta
5 from urllib.parse import parse_qs
6 from jinja2 import Template
7 from urllib.parse import urlparse
8 db_path = '/home/plom/org/todo_new.json'
9 # db_path = '/home/plom/public_repos/misc/todo_new.json'
10 server_port = 8082
11
12 html_head = """
13 <style>
14 tr:nth-child(even) {
15     background-color: #f2f2f2;
16 }
17 tr:nth-child(odd) {
18     background-color: #ffffff;
19 }
20 th, td { border: 1px solid black; text-align: left; vertical_align: top; }
21 td details { display: inline }
22 td.input { width: 100%; }
23 td.checkbox { width: 1.5em; }
24 th.checkbox { width: 1.5em; }
25 input[type="text"] { width: 100%; box-sizing: border-box; }
26 </style>
27 <body>
28 tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day: 
29 <a href="{{db.prefix}}/day{% if date %}?date={{date}}{% endif %}">choose tasks</a>
30 <a href="{{db.prefix}}/day?{% if date %}date={{date}}&{% endif %}hide_unchosen=1">do tasks</a>
31 | <a href="{{db.prefix}}/calendar?t_and=calendar">calendar</a>
32 <hr />
33 """
34 form_footer = '\n</form>'
35
36 form_header_tmpl = """
37 <form action="{{action|e}}" method="POST">
38 """
39 calendar_tmpl = """
40 <table>
41 {% for date, day in days.items() | sort(reverse=True) %}
42 <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>
43 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
44 {% if todo.visible %}
45 <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>
46 {% endif %}
47 {% endfor %}
48 {% endfor %}
49 </table>
50 """
51 todo_tmpl = """
52 <input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
53 <input type="hidden" name="date" value="{{ todo.day.date }}" />
54 <table>
55 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
56 <tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
57 <tr><th>day</th><td>{{ todo.day.date }}</td></tr>
58 <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>
59 <tr><th>comment</th><td class="input"><input type="text" name="comment" value="{{todo.comment|e}}" /></td></tr>
60 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
61 </table>
62 <input type="submit" value="update" />
63 """
64 task_tmpl = """
65 <input type="hidden" name="id" value="{{ task.id_ }}" />
66 <table>
67 <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>
68 <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>
69 <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>
70 </table>
71 <input type="submit" value="update" />
72 """
73 # archived_days_tmpl = """
74 # <table>
75 # {% for date, day in days.items() | sort(reverse=True) %}
76 # {% if day.archived %}
77 # <tr><td>{{ date }} {{ day.weekday }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
78 # {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
79 # <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
80 # {% endfor %}
81 # {% endif %}
82 # {% endfor %}
83 # </table>
84 # """
85 day_tmpl = """
86 <input type="submit" value="OK">
87 hide unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
88 mandatory tags: {% for t_tag in db.t_tags | sort %}
89 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
90 {% endfor %}
91 <br />
92 forbidden tags: {% for t_tag in db.t_tags | sort %}
93 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
94 {% endfor %}
95 </p>
96
97 <p>
98 <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
99 <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 }}">
100 </p>
101
102 <table>
103 <tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>comment</th></tr>
104 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
105 {% if t.visible %}
106 <tr>
107 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
108 <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>
109 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
110 <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>
111 <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>
112 <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>
113 </tr>
114 {% endif %}
115 {% endfor %}
116 </table>
117 <input type="submit" value="OK">
118 """
119 tasks_tmpl = """
120 <p>
121 <input type="submit" value="OK"> mandatory tags: {% for t_tag in db.t_tags | sort %}
122 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
123 {% endfor %}
124 <br />
125 forbidden tags: {% for t_tag in db.t_tags | sort %}
126 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
127 {% endfor %}
128 </p>
129 <table>
130 <tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
131 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
132 {% if t.visible %}
133 <tr>
134 <td>{{ t.default_weight }}</a></td>
135 <td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
136 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
137 {% endif %}
138 {% endfor %}
139 </table>
140 """
141 # selected_day_tmpl = """
142 # <p>
143 # hide unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
144 # mandatory tags: {% for t_tag in db.t_tags | sort %}
145 # <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
146 # {% endfor %}
147 # <br />
148 # forbidden tags: {% for t_tag in db.t_tags | sort %}
149 # <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
150 # {% endfor %}
151 # </p>
152
153 # <p>
154 # <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
155 # 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 }}">
156 # </p>
157
158 # <table>
159 # <tr><th>default<br />weight</th><th>title</th><th>tags</th><th>choose?</th><th>done?</th><th>day<br />weight</th></tr>
160 # {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
161 # {% if t.visible %}
162 # <input name="t_uuid" value="{{ uuid }}" type="hidden" >
163 # <tr>
164 # <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
165 # <td><input name="t_title" value="{{ t.title|e }}"/></td>
166 # <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
167 # <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
168 # <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>
169 # <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>
170 # </tr>
171 # {% endif %}
172 # {% endfor %}
173 # </table>
174 # <input type="submit" value="OK">
175 # """
176
177 class Task:
178
179     def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
180         self.db = db
181         self.title_history = title_history if title_history else {}
182         self.tags_history = tags_history if tags_history else {}
183         self.default_weight_history = default_weight_history if default_weight_history else {}
184         self.visible = True
185
186     def _set_with_history(self, history, value):
187         keys = sorted(history.keys())
188         if len(history) == 0 or value != history[keys[-1]]:
189             history[str(datetime.now())[:19]] = value
190
191     def _last_of_history(self, history, default):
192         keys = sorted(history.keys())
193         return default if 0 == len(history) else history[keys[-1]] 
194
195     @classmethod
196     def from_dict(cls, db, d):
197         return cls(
198                 db,
199                 d['title_history'],
200                 {k: set(v) for k, v in d['tags_history'].items()},
201                 d['default_weight_history'])
202
203     @property
204     def default_weight(self):
205         return self._last_of_history(self.default_weight_history, 1)
206
207     @default_weight.setter
208     def default_weight(self, default_weight):
209         self._set_with_history(self.default_weight_history, default_weight)
210
211     def default_weight_at(self, queried_date):
212         ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]] 
213         for date_key, default_weight in self.default_weight_history.items():
214             if date_key > f'{queried_date} 23:59:59':
215                 break
216             ret = default_weight 
217         return ret
218
219     @property
220     def current_default_weight(self):
221         return self.default_weight_at(self.db.selected_date)
222
223     @property
224     def title(self):
225         return self._last_of_history(self.title_history, '')
226
227     @title.setter
228     def title(self, title):
229         self._set_with_history(self.title_history, title)
230
231     def title_at(self, queried_date):
232         ret = self.title_history[sorted(self.title_history.keys())[0]] 
233         for date_key, title in self.title_history.items():
234             if date_key > f'{queried_date} 23:59:59':
235                 break
236             ret = title
237         return ret
238
239     @property
240     def current_title(self):
241         return self.title_at(self.db.selected_date)
242
243     @property
244     def tags(self):
245         return self._last_of_history(self.tags_history, set())
246
247     @tags.setter
248     def tags(self, tags):
249         self._set_with_history(self.tags_history, set(tags))
250
251     @property
252     def tags_joined(self):
253         return ';'.join(sorted(list(self.tags)))
254
255     @tags_joined.setter
256     def tags_joined(self, tags_string):
257         tags = set()
258         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
259             tags.add(tag)
260         self.tags = tags
261
262     def to_dict(self):
263         return {
264             'title_history': self.title_history,
265             'tags_history': {k: list(v) for k,v in self.tags_history.items()},
266             'default_weight_history': self.default_weight_history}
267
268     @property
269     def id_(self):
270         for k, v in self.db.tasks.items():
271             if v == self:
272                 return k
273
274
275 class Day:
276
277     def __init__(self, db, todos=None, comment=''):
278         self.db = db
279         self.todos = todos if todos else {} 
280         self.comment = comment
281         self.archived = True 
282
283     @classmethod
284     def from_dict(cls, db, d):
285         todos = {}
286         comment = d['comment'] if 'comment' in d.keys() else ''
287         day = cls(db, todos, comment)
288         for uuid, todo_dict in d['todos'].items():
289             day.add_todo(uuid, todo_dict)
290         return day
291
292     def to_dict(self):
293         d = {'comment': self.comment, 'todos': {}}
294         for task_uuid, todo in self.todos.items():
295             d['todos'][task_uuid] = todo.to_dict()
296         return d
297
298     def add_todo(self, id_, dict_source=None):
299         self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
300         return self.todos[id_]
301
302     def _todos_sum(self, include_undone=False):
303         s = 0
304         for todo in [todo for todo in self.todos.values() if todo.done]:
305             s += todo.weight
306         if include_undone:
307             for todo in [todo for todo in self.todos.values() if not todo.done]:
308                 s += todo.day_weight if todo.day_weight else 0
309         return s
310
311     @property
312     def todos_sum(self):
313         return self._todos_sum()
314
315     @property
316     def todos_sum2(self):
317         return self._todos_sum(True)
318
319     @property
320     def date(self):
321         for k, v in self.db.days.items():
322             if v == self:
323                 return k
324
325 class Todo:
326
327     def __init__(self, day, done=False, day_weight=None, comment=''):
328         self.day = day 
329         self.done = done
330         self.day_weight = day_weight
331         self.comment = comment
332
333     @classmethod
334     def from_dict(cls, day, d):
335         return cls(day, d['done'], d['day_weight'], d['comment'])
336
337     def to_dict(self):
338         return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment}
339
340     @property
341     def default_weight(self):
342         return self.task.default_weight_at(self.day.date)
343
344     @property
345     def weight(self):
346         if self.day_weight:
347             return self.day_weight
348         else:
349             return self.day_weight if self.day_weight else self.default_weight
350
351     @property
352     def task(self):
353         for k, v in self.day.todos.items():
354             if v == self:
355                 return self.day.db.tasks[k]
356
357     @property
358     def title(self):
359         return self.task.title_at(self.day.date)
360
361
362 class TodoDB(PlomDB):
363
364     def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False):
365         self.prefix = prefix
366         self.selected_date = selected_date if selected_date else str(datetime.now())[:10] 
367         self.t_filter_and = t_filter_and if t_filter_and else set()
368         self.t_filter_not = t_filter_not if t_filter_not else set()
369         self.hide_unchosen = hide_unchosen 
370         self.days = {}
371         self.tasks = {}
372         self.t_tags = set() 
373         super().__init__(db_path)
374         self.switch_to_day()
375
376     def read_db_file(self, f):
377         d = json.load(f)
378         for date, day_dict in d['days'].items():
379             self.days[date] = self.add_day(dict_source=day_dict)
380         for uuid, t_dict in d['tasks'].items():
381             t = self.add_task(id_=uuid, dict_source=t_dict)
382             t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
383                     and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
384                     and ((not self.hide_unchosen) or uuid in self.selected_day.todos)
385             for tag in t.tags:
386                 self.t_tags.add(tag)
387
388     def to_dict(self):
389         d = {
390                 't_filter_and': list(self.t_filter_and),
391                 't_filter_not': list(self.t_filter_not),
392                 'tasks': {},
393                 'days': {}
394         }
395         for uuid, t in self.tasks.items():
396              d['tasks'][uuid] = t.to_dict()
397         for date, day in self.days.items():
398             d['days'][date] = day.to_dict()
399         return d
400
401     @property
402     def selected_day(self):
403         return self.days[self.selected_date]
404
405     def write(self):
406         self.write_text_to_db(json.dumps(self.to_dict()))
407
408     def switch_to_day(self, date=None):
409         if date:
410             self.selected_date = date 
411             # if self.selected_date in self.days.keys():
412             #      self.selected_day.archived = True 
413         if not self.selected_date in self.days.keys():
414             self.days[self.selected_date] = self.add_day()
415         # self.selected_day.archived = False 
416
417     def add_task(self, id_=None, dict_source=None, return_id=False):
418         t = Task.from_dict(self, dict_source) if dict_source else Task(self)
419         id_ = id_ if id_ else str(uuid4())
420         self.tasks[id_] = t
421         if return_id:
422             return id_, t
423         else: 
424             return t
425
426     def add_day(self, dict_source=None):
427         return Day.from_dict(self, dict_source) if dict_source else Day(self)
428
429     # def show_all(self):
430     #     for i in range(10):
431     #         self.add_task(id_=f'new{i}') 
432     #     return Template(form_header_tmpl + selected_day_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all', days=self.days)
433
434      #def show_selected_day(self):
435      #    return Template(form_header_tmpl + selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
436
437     def show_day(self):
438         current_date = datetime.strptime(self.selected_date, '%Y-%m-%d') 
439         prev_date = current_date - timedelta(days=1) 
440         prev_date_str = prev_date.strftime('%Y-%m-%d')
441         next_date = current_date + timedelta(days=1) 
442         next_date_str = next_date.strftime('%Y-%m-%d')
443         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)
444
445     def show_calendar(self, start_date_str, end_date_str):
446         days_to_show = {}
447         target_start = start_date_str if start_date_str else sorted(self.days.keys())[0]
448         target_start = str(datetime.now())[:10] if 'today' == target_start else target_start
449         target_end = end_date_str if end_date_str else sorted(self.days.keys())[-1]
450         todays_date = str(datetime.now())[:10]
451         start_date = datetime.strptime(target_start, '%Y-%m-%d')
452         end_date = datetime.strptime(target_end, '%Y-%m-%d')
453         for n in range(int((end_date - start_date).days) + 1):
454             current_date_obj = start_date + timedelta(n)
455             current_date = current_date_obj.strftime('%Y-%m-%d') 
456             if current_date not in self.days.keys():
457                 days_to_show[current_date] = self.add_day()
458             else:
459                 days_to_show[current_date] = self.days[current_date] 
460             days_to_show[current_date].weekday = datetime.strptime(current_date, '%Y-%m-%d').strftime('%A')
461             for task_uuid, todo in days_to_show[current_date].todos.items():
462                 todo.visible = self.tasks[task_uuid].visible
463         return Template(calendar_tmpl).render(db=self, days=days_to_show)
464
465     def show_todo(self, task_uuid, selected_date):
466         todo = self.days[selected_date].todos[task_uuid]
467         return Template(form_header_tmpl + todo_tmpl + form_footer).render(db=self, todo=todo, action=self.prefix+'/todo')
468
469     def update_todo(self, task_uuid, date, day_weight, done, comment):
470         if task_uuid in self.days[date].todos.keys():
471             todo = self.days[date].todos[task_uuid]
472         else:
473             todo = self.days[date].add_todo(task_uuid)
474         # todo = self.days[date].todos[task_uuid]
475         todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
476         todo.done = done 
477         todo.comment = comment 
478
479     def show_task(self, id_):
480         task = self.tasks[id_] if id_ else self.add_task()
481         return Template(form_header_tmpl + task_tmpl + form_footer).render(db=self, task=task, action=self.prefix+'/task')
482
483     def update_task(self, id_, title, default_weight, tags_joined):
484         task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
485         task.title = title
486         task.default_weight = float(default_weight) if len(default_weight) > 0 else None
487         task.tags_joined = tags_joined
488
489     def show_tasks(self):
490         return Template(form_header_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
491
492
493
494 class TodoHandler(PlomHandler):
495     
496     def app_init(self, handler):
497         default_path = '/todo'
498         handler.add_route('GET', default_path, self.show_db) 
499         handler.add_route('POST', default_path, self.write_db) 
500         return 'todo', default_path 
501
502     def do_POST(self):
503         self.try_do(self.write_db)
504
505     def write_db(self):
506         from urllib.parse import urlencode
507         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
508         length = int(self.headers['content-length'])
509         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
510         parsed_url = urlparse(self.path)
511         db = TodoDB(prefix=prefix)
512         if parsed_url.path == prefix + '/todo':
513             task_uuid = postvars['task_uuid'][0]
514             date = postvars['date'][0]
515             db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0])
516             homepage = f'{prefix}/todo?task={task_uuid}&date={date}'
517         elif parsed_url.path == prefix + '/task':
518             id_ = postvars['id'][0]
519             db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags'][0])
520             homepage = f'{prefix}/task?id={id_}'
521         elif parsed_url.path in {prefix + '/tasks', prefix + '/day'}:
522             if 't_filter_and' in postvars.keys():
523                 for target in postvars['t_filter_and']:
524                     db.t_filter_and.add(target) 
525             if 't_filter_not' in postvars.keys():
526                 for target in postvars['t_filter_not']:
527                     db.t_filter_not.add(target) 
528             if 'hide_unchosen' in postvars.keys():
529                 db.hide_unchosen = True
530             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))]
531             if parsed_url.path == prefix + '/tasks':
532                 encoded_params = urlencode(data)
533                 homepage = f'{prefix}/tasks?{encoded_params}'
534             elif parsed_url.path == prefix + '/day':
535                 db.switch_to_day(postvars['original_selected_date'][0])
536                 new_selected_date = postvars['new_selected_date'][0]
537                 try:
538                     datetime.strptime(new_selected_date, '%Y-%m-%d')
539                 except ValueError:
540                     raise PlomException(f"{prefix} bad date string: {new_selected_date}")
541                 if new_selected_date != db.selected_date:
542                     if new_selected_date in db.days.keys():
543                         raise PlomException('cannot use same date twice')
544                     else:
545                         db.days[new_selected_date] = db.selected_day
546                         del db.days[db.selected_date]
547                         db.selected_date = new_selected_date
548                 for i, uuid in enumerate(postvars['t_uuid']):
549                     t = db.tasks[uuid]
550                     if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
551                         del db.selected_day.todos[uuid]
552                 if 'choose' in postvars.keys():
553                     for i, uuid in enumerate(postvars['t_uuid']):
554                         if uuid in postvars['choose']:
555                             done = 'done' in postvars and uuid in postvars['done']
556                             db.update_todo(uuid, db.selected_date, postvars['day_weight'][i], done, postvars['todo_comment'][i])
557                 if 'comment' in postvars.keys():
558                     db.selected_day.comment = postvars['comment'][0]
559                 data += [('date', db.selected_date)]
560                 encoded_params = urlencode(data)
561                 homepage = f'{prefix}/day?{encoded_params}'
562         db.write()
563         self.redirect(homepage)
564         # db = TodoDB(prefix=prefix, selected_date=postvars['original_selected_date'][0])
565         # # import pprint
566         # # pp = pprint.PrettyPrinter(indent=4)
567         # # pp.pprint(postvars)
568         # db.t_filter_and = set()
569         # db.t_filter_not = set()
570         # if 't_filter_and' in postvars.keys():
571         #     for target in postvars['t_filter_and']:
572         #         db.t_filter_and.add(target) 
573         # if 't_filter_not' in postvars.keys():
574         #     for target in postvars['t_filter_not']:
575         #         db.t_filter_not.add(target) 
576         # if 'hide_unchosen' in postvars.keys():
577         #     db.hide_unchosen = True
578         # if 't_uuid' in postvars.keys():
579         #     new_postvars_t_uuid = postvars['t_uuid'].copy()
580         #     for i, uuid in enumerate(postvars['t_uuid']):
581         #         if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
582         #             new_uuid, t = db.add_task(return_id=True)
583         #             new_postvars_t_uuid[i] = new_uuid
584         #             for key in [k for k in postvars.keys() if not k == 't_uuid']:
585         #                 if uuid in postvars[key]:
586         #                     uuid_index = postvars[key].index(uuid)
587         #                     postvars[key][uuid_index] = new_uuid
588         #     postvars['t_uuid'] = new_postvars_t_uuid
589         #     for i, uuid in enumerate(postvars['t_uuid']):
590         #         if len(uuid) < 36:
591         #             continue
592         #         t = db.tasks[uuid]
593         #         t.set_title(postvars['t_title'][i])
594         #         t.tags_from_joined_string(postvars['t_tags'][i])
595         #         t.set_default_weight(float(postvars['t_default_weight'][i]))
596         #         if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
597         #             del db.selected_day.todos[uuid]
598         #     if 'choose' in postvars.keys():
599         #         for i, uuid in enumerate(postvars['t_uuid']):
600         #             if uuid in postvars['choose']:
601         #                 done = 'done' in postvars and uuid in postvars['done']
602         #                 day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
603         #                 db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
604
605         # if 'comment' in postvars.keys():
606         #     db.selected_day.comment = postvars['comment'][0]
607         # if 'new_selected_date' in postvars.keys():
608         #     new_selected_date = postvars['new_selected_date'][0]
609         #     try:
610         #         datetime.strptime(new_selected_date, '%Y-%m-%d')
611         #     except ValueError:
612         #         raise PlomException(f"{prefix} bad date string: {new_selected_date}")
613         #     if new_selected_date != db.selected_date:
614         #         if new_selected_date in db.days.keys():
615         #             raise PlomException('cannot use same date twice')
616         #         else:
617         #             db.days[new_selected_date] = db.selected_day
618         #             del db.days[db.selected_date]
619         #             db.selected_date = new_selected_date
620
621         # switch_edited_day = None
622         # day_edit_prefix = 'edit_'
623         # for k in postvars.keys():
624         #     if k.startswith(day_edit_prefix):
625         #         switch_edited_day = k[len(day_edit_prefix):]
626         #         db.switch_to_day(switch_edited_day)
627         #         break
628         # db.write()
629         # 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)]
630         # encoded_params = urlencode(data)
631         # if prefix + '/day' == parsed_url.path:
632         #     homepage = f'{prefix}/day?{encoded_params}'
633         # else:
634         #     homepage = f'{prefix}/all?{encoded_params}'
635         # self.redirect(homepage)
636
637     def do_GET(self):
638         self.try_do(self.show_db)
639
640     def show_db(self):
641         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
642         parsed_url = urlparse(self.path)
643         params = parse_qs(parsed_url.query)
644         selected_date = params.get('date', [None])[0]
645         t_filter_and = set(params.get('t_and', []))
646         t_filter_not = set(params.get('t_not', ['deleted']))
647         hide_unchosen_params = params.get('hide_unchosen', [])
648         hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
649         db = TodoDB(prefix, selected_date, t_filter_and, t_filter_not, hide_unchosen)
650         if parsed_url.path == prefix + '/day':
651             page = db.show_day()
652         elif parsed_url.path == prefix + '/todo':
653             task_uuid = params.get('task', [None])[0]
654             page = db.show_todo(task_uuid, selected_date)
655         elif parsed_url.path == prefix + '/task':
656             id_ = params.get('id', [None])[0]
657             page = db.show_task(id_)
658         elif parsed_url.path == prefix + '/tasks':
659             page = db.show_tasks()
660         elif parsed_url.path == prefix + '/add_task':
661             page = db.show_task(None)
662         else: 
663             start_date = params.get('start', [None])[0]
664             end_date = params.get('end', [None])[0]
665             page = db.show_calendar(start_date, end_date)
666         header = Template(html_head).render(db=db, prefix=prefix, date=selected_date)
667         self.send_HTML(header + page)
668
669
670 if __name__ == "__main__":  
671     run_server(server_port, TodoHandler)