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'
11 DATE_FORMAT = '%Y-%m-%d'
15 table.alternating tr:nth-child(even) {
16 background-color: #f2f2f2;
18 table.alternating tr:nth-child(odd) {
19 background-color: #ffffff;
21 th, td { border: 1px solid black; text-align: left; vertical_align: top; }
22 td details { display: inline }
23 td.input { width: 100%; }
24 td.checkbox { width: 0.7em; }
25 th.checkbox { width: 0.7em; }
26 tr.week_row td { height: 0.1em; border: 0px; background-color: black; }
27 tr.day_row td { background-color: #f2f2f2; }
28 input[type="text"] { width: 100%; box-sizing: border-box; }
31 tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day:
32 <a href="{{db.prefix}}/day{% if date %}?date={{date}}{% endif %}">choose tasks</a>
33 <a href="{{db.prefix}}/day?{% if date %}date={{date}}&{% endif %}hide_unchosen=1">do tasks</a>
34 | <a href="{{db.prefix}}/calendar?t_and=calendar">calendar</a>
37 form_footer = '\n</form>'
38 form_header_tmpl = """
39 <form action="{{action|e}}" method="POST">
43 from: <input name="start" {% if start_date %}value="{{ start_date }}"{% endif %} placeholder="{{ today }}" />
44 to: <input name="end" {% if end_date %}value="{{ end_date }}"{% endif %} placeholder="2030-12-31" />
45 <input type="submit" value="OK" />
48 {% for date, day in days.items() | sort() %}
49 {% if day.weekday == "Monday" %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
50 <tr class="day_row"><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>
51 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True) %}
53 <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>
60 <input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
61 <input type="hidden" name="date" value="{{ todo.day.date }}" />
63 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
64 <tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
65 <tr><th>day</th><td>{{ todo.day.date }}</td></tr>
66 <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>
67 <tr><th>comment</th><td class="input"><input type="text" name="comment" value="{{todo.comment|e}}" /></td></tr>
68 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
70 <input type="submit" value="update" />
73 <input type="hidden" name="id" value="{{ task.id_ }}" />
75 <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>
76 <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>
77 <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>
79 <input type="submit" value="update" />
83 <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /> hide unchosen |
84 <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> |
85 <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
86 date: <input name="new_selected_date" value="{{ db.selected_date }}" size=8 /> |
87 {{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) |
88 comment: <input name="day_comment" value="{{ db.selected_day.comment|e }}">
91 <table class="alternating">
92 <tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>comment</th></tr>
93 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
96 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
97 <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>
98 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
99 <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>
100 <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>
101 <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>
106 <input type="submit" value="OK">
108 tag_filters_tmpl = """
109 <p style="float: left; margin-right: 1em;">
110 <input type="submit" value="OK">
114 {% for and_filter in db.t_filter_and %}
115 <select name="t_and">
117 {% for tag in db.t_tags | sort %}
118 <option value="{{tag|e}}" {% if and_filter == tag %}selected{% endif %}>{{tag|e}}</option>
122 <select name="t_and">
124 {% for tag in db.t_tags | sort %}
125 <option value="{{tag|e}}">{{tag|e}}</option>
130 {% for not_filter in db.t_filter_not %}
131 <select name="t_not">
133 {% for tag in db.t_tags | sort %}
134 <option value="{{tag|e}}" {% if not_filter == tag %}selected{% endif %}>{{tag|e}}</option>
138 <select name="t_not">
140 {% for tag in db.t_tags | sort %}
141 <option value="{{tag|e}}">{{tag|e}}</option>
147 <table class="alternating">
148 <tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
149 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
152 <td>{{ t.default_weight }}</a></td>
153 <td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
154 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
162 def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
164 self.title_history = title_history if title_history else {}
165 self.tags_history = tags_history if tags_history else {}
166 self.default_weight_history = default_weight_history if default_weight_history else {}
169 def _set_with_history(self, history, value):
170 keys = sorted(history.keys())
171 if len(history) == 0 or value != history[keys[-1]]:
172 history[str(datetime.now())[:19]] = value
174 def _last_of_history(self, history, default):
175 keys = sorted(history.keys())
176 return default if 0 == len(history) else history[keys[-1]]
179 def from_dict(cls, db, d):
183 {k: set(v) for k, v in d['tags_history'].items()},
184 d['default_weight_history'])
187 def default_weight(self):
188 return self._last_of_history(self.default_weight_history, 1)
190 @default_weight.setter
191 def default_weight(self, default_weight):
192 self._set_with_history(self.default_weight_history, default_weight)
194 def default_weight_at(self, queried_date):
195 ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]]
196 for date_key, default_weight in self.default_weight_history.items():
197 if date_key > f'{queried_date} 23:59:59':
203 def current_default_weight(self):
204 return self.default_weight_at(self.db.selected_date)
208 return self._last_of_history(self.title_history, '')
211 def title(self, title):
212 self._set_with_history(self.title_history, title)
214 def title_at(self, queried_date):
215 ret = self.title_history[sorted(self.title_history.keys())[0]]
216 for date_key, title in self.title_history.items():
217 if date_key > f'{queried_date} 23:59:59':
223 def current_title(self):
224 return self.title_at(self.db.selected_date)
228 return self._last_of_history(self.tags_history, set())
231 def tags(self, tags):
232 self._set_with_history(self.tags_history, set(tags))
235 def tags_joined(self):
236 return ';'.join(sorted(list(self.tags)))
239 def tags_joined(self, tags_string):
241 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
247 'title_history': self.title_history,
248 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
249 'default_weight_history': self.default_weight_history}
253 for k, v in self.db.tasks.items():
260 def __init__(self, db, todos=None, comment=''):
262 self.todos = todos if todos else {}
263 self.comment = comment
267 def from_dict(cls, db, d):
269 comment = d['comment'] if 'comment' in d.keys() else ''
270 day = cls(db, todos, comment)
271 for uuid, todo_dict in d['todos'].items():
272 day.add_todo(uuid, todo_dict)
276 d = {'comment': self.comment, 'todos': {}}
277 for task_uuid, todo in self.todos.items():
278 d['todos'][task_uuid] = todo.to_dict()
281 def add_todo(self, id_, dict_source=None):
282 self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
283 return self.todos[id_]
285 def _todos_sum(self, include_undone=False):
287 for todo in [todo for todo in self.todos.values() if todo.done]:
290 for todo in [todo for todo in self.todos.values() if not todo.done]:
291 s += todo.day_weight if todo.day_weight else 0
296 return self._todos_sum()
299 def todos_sum2(self):
300 return self._todos_sum(True)
304 for k, v in self.db.days.items():
310 def __init__(self, day, done=False, day_weight=None, comment=''):
313 self.day_weight = day_weight
314 self.comment = comment
317 def from_dict(cls, day, d):
318 return cls(day, d['done'], d['day_weight'], d['comment'])
321 return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment}
324 def default_weight(self):
325 return self.task.default_weight_at(self.day.date)
330 return self.day_weight
332 return self.day_weight if self.day_weight else self.default_weight
336 for k, v in self.day.todos.items():
338 return self.day.db.tasks[k]
342 return self.task.title_at(self.day.date)
345 class TodoDB(PlomDB):
347 def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False):
349 self.selected_date = selected_date if selected_date else str(datetime.now())[:10]
350 self.t_filter_and = t_filter_and if t_filter_and else []
351 self.t_filter_not = t_filter_not if t_filter_not else []
352 self.hide_unchosen = hide_unchosen
356 super().__init__(db_path)
358 def read_db_file(self, f):
360 for date, day_dict in d['days'].items():
361 self.days[date] = self.add_day(dict_source=day_dict)
362 for uuid, t_dict in d['tasks'].items():
363 t = self.add_task(id_=uuid, dict_source=t_dict)
364 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
365 and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
366 and ((not self.hide_unchosen) or uuid in self.selected_day.todos)
372 't_filter_and': self.t_filter_and,
373 't_filter_not': self.t_filter_not,
377 for uuid, t in self.tasks.items():
378 d['tasks'][uuid] = t.to_dict()
379 for date, day in self.days.items():
380 d['days'][date] = day.to_dict()
384 def selected_day(self):
385 if not self.selected_date in self.days.keys():
386 self.days[self.selected_date] = self.add_day()
387 return self.days[self.selected_date]
389 def change_selected_days_date(self, new_date):
390 if new_date in self.days.keys():
391 raise PlomException('cannot use same date twice')
393 self.days[new_date] = self.selected_day
394 del self.days[self.selected_date]
395 self.selected_date = new_date
399 for date, day in self.days.items():
400 if len(day.todos) == 0 and len(day.comment) == 0:
401 dates_to_purge += [date]
402 for date in dates_to_purge:
404 self.write_text_to_db(json.dumps(self.to_dict()))
406 def add_task(self, id_=None, dict_source=None, return_id=False):
407 t = Task.from_dict(self, dict_source) if dict_source else Task(self)
408 id_ = id_ if id_ else str(uuid4())
415 def add_day(self, dict_source=None):
416 return Day.from_dict(self, dict_source) if dict_source else Day(self)
419 current_date = datetime.strptime(self.selected_date, DATE_FORMAT)
420 prev_date = current_date - timedelta(days=1)
421 prev_date_str = prev_date.strftime(DATE_FORMAT)
422 next_date = current_date + timedelta(days=1)
423 next_date_str = next_date.strftime(DATE_FORMAT)
424 return Template(form_header_tmpl + tag_filters_tmpl + day_tmpl + form_footer).render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str)
426 def show_calendar(self, start_date_str, end_date_str):
428 target_start = start_date_str if start_date_str else sorted(self.days.keys())[0]
429 # target_start = str(datetime.now())[:10] if 'today' == target_start else target_start
430 target_end = end_date_str if end_date_str else sorted(self.days.keys())[-1]
431 # todays_date = str(datetime.now())[:10]
432 start_date = datetime.strptime(target_start, DATE_FORMAT)
433 end_date = datetime.strptime(target_end, DATE_FORMAT)
434 for n in range(int((end_date - start_date).days) + 1):
435 current_date_obj = start_date + timedelta(n)
436 current_date = current_date_obj.strftime(DATE_FORMAT)
437 if current_date not in self.days.keys():
438 days_to_show[current_date] = self.add_day()
440 days_to_show[current_date] = self.days[current_date]
441 days_to_show[current_date].weekday = datetime.strptime(current_date, DATE_FORMAT).strftime('%A')
442 for task_uuid, todo in days_to_show[current_date].todos.items():
443 todo.visible = self.tasks[task_uuid].visible
444 return Template(form_header_tmpl + calendar_tmpl + form_footer).render(db=self, days=days_to_show, action=self.prefix+'/calendar', today=str(datetime.now())[:10], start_date=start_date_str, end_date=end_date_str)
446 def show_todo(self, task_uuid, selected_date):
447 todo = self.days[selected_date].todos[task_uuid]
448 return Template(form_header_tmpl + todo_tmpl + form_footer).render(db=self, todo=todo, action=self.prefix+'/todo')
450 def update_todo(self, task_uuid, date, day_weight, done, comment):
451 if task_uuid in self.days[date].todos.keys():
452 todo = self.days[date].todos[task_uuid]
454 todo = self.days[date].add_todo(task_uuid)
455 todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
457 todo.comment = comment
459 def show_task(self, id_):
460 task = self.tasks[id_] if id_ else self.add_task()
461 return Template(form_header_tmpl + task_tmpl + form_footer).render(db=self, task=task, action=self.prefix+'/task')
463 def update_task(self, id_, title, default_weight, tags_joined):
464 task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
466 task.default_weight = float(default_weight) if len(default_weight) > 0 else None
467 task.tags_joined = tags_joined
469 def show_tasks(self):
470 return Template(form_header_tmpl + tag_filters_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
474 class TodoHandler(PlomHandler):
476 def app_init(self, handler):
477 default_path = '/todo'
478 handler.add_route('GET', default_path, self.show_db)
479 handler.add_route('POST', default_path, self.write_db)
480 return 'todo', default_path
483 self.try_do(self.write_db)
486 from urllib.parse import urlencode
487 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
488 length = int(self.headers['content-length'])
489 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
490 parsed_url = urlparse(self.path)
491 db = TodoDB(prefix=prefix)
493 if parsed_url.path == prefix + '/calendar':
494 start = postvars['start'][0] if len(postvars['start'][0]) > 0 else ''
495 end = postvars['end'][0] if len(postvars['end'][0]) > 0 else ''
496 homepage = f'{prefix}/calendar?t_and=calendar&start={start}&end={end}'
498 elif parsed_url.path == prefix + '/todo':
499 task_uuid = postvars['task_uuid'][0]
500 date = postvars['date'][0]
501 db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0])
502 homepage = f'{prefix}/todo?task={task_uuid}&date={date}'
504 elif parsed_url.path == prefix + '/task':
505 id_ = postvars['id'][0]
506 db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags'][0])
507 homepage = f'{prefix}/task?id={id_}'
509 elif parsed_url.path in {prefix + '/tasks', prefix + '/day'}:
510 for target in postvars['t_and']:
511 if not target in db.t_filter_and:
512 db.t_filter_and += [target]
513 for target in postvars['t_not']:
514 if not target in db.t_filter_not:
515 db.t_filter_not += [target]
516 if 'hide_unchosen' in postvars.keys():
517 db.hide_unchosen = True
518 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))]
520 if parsed_url.path == prefix + '/tasks':
521 encoded_params = urlencode(data)
522 homepage = f'{prefix}/tasks?{encoded_params}'
524 elif parsed_url.path == prefix + '/day':
525 db.selected_date = postvars['original_selected_date'][0]
526 new_selected_date = postvars['new_selected_date'][0]
528 datetime.strptime(new_selected_date, DATE_FORMAT)
530 raise PlomException(f"{prefix} bad date string: {new_selected_date}")
531 if new_selected_date != db.selected_date:
532 db.change_selected_days_date(new_selected_date)
533 if 't_uuid' in postvars.keys():
534 for i, uuid in enumerate(postvars['t_uuid']):
536 if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
537 del db.selected_day.todos[uuid]
538 if 'choose' in postvars.keys():
539 for i, uuid in enumerate(postvars['t_uuid']):
540 if uuid in postvars['choose']:
541 done = 'done' in postvars and uuid in postvars['done']
542 db.update_todo(uuid, db.selected_date, postvars['day_weight'][i], done, postvars['todo_comment'][i])
543 if 'day_comment' in postvars.keys():
544 db.selected_day.comment = postvars['day_comment'][0]
545 data += [('date', db.selected_date)]
546 encoded_params = urlencode(data)
547 homepage = f'{prefix}/day?{encoded_params}'
550 self.redirect(homepage)
553 self.try_do(self.show_db)
556 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
557 parsed_url = urlparse(self.path)
558 params = parse_qs(parsed_url.query)
559 selected_date = params.get('date', [None])[0]
560 t_filter_and = params.get('t_and', [])
561 t_filter_not = params.get('t_not', ['deleted'])
562 hide_unchosen_params = params.get('hide_unchosen', [])
563 hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
564 db = TodoDB(prefix, selected_date, t_filter_and, t_filter_not, hide_unchosen)
565 if parsed_url.path == prefix + '/day':
567 elif parsed_url.path == prefix + '/todo':
568 task_uuid = params.get('task', [None])[0]
569 page = db.show_todo(task_uuid, selected_date)
570 elif parsed_url.path == prefix + '/task':
571 id_ = params.get('id', [None])[0]
572 page = db.show_task(id_)
573 elif parsed_url.path == prefix + '/tasks':
574 page = db.show_tasks()
575 elif parsed_url.path == prefix + '/add_task':
576 page = db.show_task(None)
578 start_date = params.get('start', [None])[0]
579 end_date = params.get('end', [None])[0]
580 page = db.show_calendar(start_date, end_date)
581 header = Template(html_head).render(db=db, prefix=prefix, date=selected_date)
582 self.send_HTML(header + page)
585 if __name__ == "__main__":
586 run_server(server_port, TodoHandler)