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