1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
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'
15 background-color: #f2f2f2;
18 background-color: #ffffff;
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; }
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>
34 form_footer = '\n</form>'
36 form_header_tmpl = """
37 <form action="{{action|e}}" method="POST">
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) %}
45 <tr><td class="checkbox">{% if todo.done %}✓{% else %} {% endif %}</td><td><a href="{{db.prefix}}/todo?task={{ todo.task.id_ }}&date={{ date }}">{{ todo.title }}</a></td><td>{{ todo.comment|e }}</td></tr>
52 <input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
53 <input type="hidden" name="date" value="{{ todo.day.date }}" />
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>
62 <input type="submit" value="update" />
65 <input type="hidden" name="id" value="{{ task.id_ }}" />
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>
71 <input type="submit" value="update" />
73 # archived_days_tmpl = """
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>
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 }}
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 }}
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 }}">
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) %}
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>
117 <input type="submit" value="OK">
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 }}
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 }}
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) %}
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>
141 # selected_day_tmpl = """
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 }}
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 }}
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 }}">
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) %}
162 # <input name="t_uuid" value="{{ uuid }}" type="hidden" >
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>
174 # <input type="submit" value="OK">
179 def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
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 {}
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
191 def _last_of_history(self, history, default):
192 keys = sorted(history.keys())
193 return default if 0 == len(history) else history[keys[-1]]
196 def from_dict(cls, db, d):
200 {k: set(v) for k, v in d['tags_history'].items()},
201 d['default_weight_history'])
204 def default_weight(self):
205 return self._last_of_history(self.default_weight_history, 1)
207 @default_weight.setter
208 def default_weight(self, default_weight):
209 self._set_with_history(self.default_weight_history, default_weight)
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':
220 def current_default_weight(self):
221 return self.default_weight_at(self.db.selected_date)
225 return self._last_of_history(self.title_history, '')
228 def title(self, title):
229 self._set_with_history(self.title_history, title)
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':
240 def current_title(self):
241 return self.title_at(self.db.selected_date)
245 return self._last_of_history(self.tags_history, set())
248 def tags(self, tags):
249 self._set_with_history(self.tags_history, set(tags))
252 def tags_joined(self):
253 return ';'.join(sorted(list(self.tags)))
256 def tags_joined(self, tags_string):
258 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
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}
270 for k, v in self.db.tasks.items():
277 def __init__(self, db, todos=None, comment=''):
279 self.todos = todos if todos else {}
280 self.comment = comment
284 def from_dict(cls, db, d):
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)
293 d = {'comment': self.comment, 'todos': {}}
294 for task_uuid, todo in self.todos.items():
295 d['todos'][task_uuid] = todo.to_dict()
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_]
302 def _todos_sum(self, include_undone=False):
304 for todo in [todo for todo in self.todos.values() if todo.done]:
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
313 return self._todos_sum()
316 def todos_sum2(self):
317 return self._todos_sum(True)
321 for k, v in self.db.days.items():
327 def __init__(self, day, done=False, day_weight=None, comment=''):
330 self.day_weight = day_weight
331 self.comment = comment
334 def from_dict(cls, day, d):
335 return cls(day, d['done'], d['day_weight'], d['comment'])
338 return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment}
341 def default_weight(self):
342 return self.task.default_weight_at(self.day.date)
347 return self.day_weight
349 return self.day_weight if self.day_weight else self.default_weight
353 for k, v in self.day.todos.items():
355 return self.day.db.tasks[k]
359 return self.task.title_at(self.day.date)
362 class TodoDB(PlomDB):
364 def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False):
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
373 super().__init__(db_path)
376 def read_db_file(self, 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)
390 't_filter_and': list(self.t_filter_and),
391 't_filter_not': list(self.t_filter_not),
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()
402 def selected_day(self):
403 return self.days[self.selected_date]
406 self.write_text_to_db(json.dumps(self.to_dict()))
408 def switch_to_day(self, date=None):
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
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())
426 def add_day(self, dict_source=None):
427 return Day.from_dict(self, dict_source) if dict_source else Day(self)
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)
434 #def show_selected_day(self):
435 # return Template(form_header_tmpl + selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
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)
445 def show_calendar(self, start_date_str, end_date_str):
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()
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)
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')
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]
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
477 todo.comment = comment
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')
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_)
486 task.default_weight = float(default_weight) if len(default_weight) > 0 else None
487 task.tags_joined = tags_joined
489 def show_tasks(self):
490 return Template(form_header_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
494 class TodoHandler(PlomHandler):
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
503 self.try_do(self.write_db)
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]
538 datetime.strptime(new_selected_date, '%Y-%m-%d')
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')
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']):
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}'
563 self.redirect(homepage)
564 # db = TodoDB(prefix=prefix, selected_date=postvars['original_selected_date'][0])
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']):
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})
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]
610 # datetime.strptime(new_selected_date, '%Y-%m-%d')
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')
617 # db.days[new_selected_date] = db.selected_day
618 # del db.days[db.selected_date]
619 # db.selected_date = new_selected_date
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)
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}'
634 # homepage = f'{prefix}/all?{encoded_params}'
635 # self.redirect(homepage)
638 self.try_do(self.show_db)
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':
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)
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)
670 if __name__ == "__main__":
671 run_server(server_port, TodoHandler)