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
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 td { border: 1px solid black; }
15 </style>
16 <body>
17 <a href="{{prefix}}/all">all</a> | edit day: 
18 <a href="{{prefix}}/day">choose</a>
19 <a href="{{prefix}}/day?hide_unchosen=1">do</a>
20 <hr />
21 """
22
23 form_footer = '\n</form>'
24
25 archived_days_tmpl = """
26 <table>
27 {% for date, day in db.days.items() | sort(reverse=True) %}
28 {% if day.archived %}
29 <tr><td>{{ date }} ({{ day.todos_sum |round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
30 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
31 <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
32 {% endfor %}
33 {% endif %}
34 {% endfor %}
35 </table>
36 """
37
38 selected_day_tmpl = """
39 <form action="{{action|e}}" method="POST">
40 hiden unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br /> 
41 mandatory tags: {% for t_tag in db.t_tags | sort %}
42 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
43 {% endfor %}
44 <br />
45 forbidden tags: {% for t_tag in db.t_tags | sort %}
46 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
47 {% endfor %}
48 <table>
49 <tr><th colspan=2></th><th>date</th><td colspan=2><input name="selected_day_date" value="{{ db.selected_day_date }}" size=8 /></td><th>archive?</th><td><input type="checkbox" name="archive_day" /></td><td>{{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}})</td><th>comment:</th><td><input name="comment" value="{{ db.selected_day.comment|e }}"></td></tr>
50 <tr><th>default<br />weight</th><th>title</th><th>tags</th><th>choose?</th><th>done?</th><th colspan=2>day<br />weight</th></tr>
51 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
52 {% if t.visible %}
53 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
54 <tr>
55 <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
56 <td><input name="t_title" value="{{ t.title|e }}"/></td>
57 <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
58 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
59 <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>
60 <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>
61 </tr>
62 {% endif %}
63 {% endfor %}
64 </table>
65 <input type="submit" value="OK">
66 """
67
68 class Task:
69
70     def __init__(self, db, title_history={}, tags_history={}, default_weight_history={}):
71         self.db = db
72         self.title_history = title_history.copy()
73         self.tags_history = tags_history.copy()
74         self.default_weight_history = default_weight_history.copy()
75         self.visible = True
76
77     def _set_with_history(self, history, value):
78         keys = sorted(history.keys())
79         if len(history) == 0 or value != history[keys[-1]]:
80             history[str(datetime.now())[:19]] = value
81
82     def _last_of_history(self, history, default):
83         keys = sorted(history.keys())
84         return default if 0 == len(history) else history[keys[-1]] 
85
86     @classmethod
87     def from_dict(cls, db, d):
88         return cls(
89                 db,
90                 d['title_history'],
91                 {k: set(v) for k, v in d['tags_history'].items()},
92                 d['default_weight_history'])
93
94     def tags_from_joined_string(self, tags_string):
95         tags = set()
96         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
97             tags.add(tag)
98         self.set_tags(tags)
99
100     @property
101     def tags_joined(self):
102         return ';'.join(sorted(list(self.tags)))
103
104     def set_default_weight(self, default_weight):
105         self._set_with_history(self.default_weight_history, default_weight)
106
107     @property
108     def default_weight(self):
109         return self._last_of_history(self.default_weight_history, 1)
110
111     def set_title(self, title):
112         self._set_with_history(self.title_history, title)
113
114     @property
115     def title(self):
116         return self._last_of_history(self.title_history, '')
117
118     def title_at(self, queried_date):
119         ret = self.title_history[sorted(self.title_history.keys())[0]] 
120         for date_key, title in self.title_history.items():
121             if date_key > f'{queried_date} 23:59:59':
122                 break
123             ret = title
124         return ret
125
126     def set_tags(self, tags):
127         self._set_with_history(self.tags_history, set(tags))
128
129     @property
130     def tags(self):
131         return self._last_of_history(self.tags_history, set())
132
133     def to_dict(self):
134         return {
135             'title_history': self.title_history,
136             'tags_history': {k: list(v) for k,v in self.tags_history.items()},
137             'default_weight_history': self.default_weight_history}
138
139
140 class Day:
141
142     def __init__(self, db, todos={}, comment=''):
143         self.db = db
144         self.todos = todos 
145         self.comment = comment
146         self.archived = True 
147
148     @classmethod
149     def from_dict(cls, db, d):
150         todos = {}
151         comment = d['comment'] if 'comment' in d.keys() else ''
152         day = cls(db, todos, comment)
153         for uuid, todo_dict in d['todos'].items():
154             day.add_todo(uuid, todo_dict)
155         return day
156
157     def to_dict(self):
158         d = {'comment': self.comment, 'todos': {}}
159         for task_uuid, todo in self.todos.items():
160             d['todos'][task_uuid] = todo.to_dict()
161         return d
162
163     def add_todo(self, id_, dict_source=None):
164         self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
165
166     def _todos_sum(self, include_undone=False):
167         s = 0
168         for todo in [todo for todo in self.todos.values() if todo.done]:
169             s += todo.weight
170         if include_undone:
171             for todo in [todo for todo in self.todos.values() if not todo.done]:
172                 s += todo.day_weight if todo.day_weight else 0
173         return s
174
175     @property
176     def todos_sum(self):
177         return self._todos_sum()
178
179     @property
180     def todos_sum2(self):
181         return self._todos_sum(True)
182
183 class Todo:
184
185     def __init__(self, day, done=False, day_weight=None):
186         self.day = day 
187         self.done = done
188         self.day_weight = day_weight
189
190     @classmethod
191     def from_dict(cls, day, d):
192         return cls(day, d['done'], d['day_weight'])
193
194     def to_dict(self):
195         return {'done': self.done, 'day_weight': self.day_weight}
196
197     @property
198     def weight(self):
199         if self.day_weight:
200             return self.day_weight
201         else:
202             task_uuid = [k for k,v in self.day.todos.items() if v == self][0]
203             return self.day_weight if self.day_weight else self.day.db.tasks[task_uuid].default_weight
204
205
206 class TodoDB(PlomDB):
207
208     def __init__(self, prefix, t_filter_and = set(), t_filter_not = set(), hide_unchosen=False):
209         self.prefix = prefix
210         self.t_filter_and = t_filter_and
211         self.t_filter_not = t_filter_not
212         self.hide_unchosen = hide_unchosen 
213         self.days = {}
214         self.tasks = {}
215         self.t_tags = set() 
216         super().__init__(db_path)
217         if not hasattr(self, 'selected_day_date'):
218             self.switch_to_day()
219
220     def read_db_file(self, f):
221         d = json.load(f)
222         self.selected_day_date = d['selected_day_date'] 
223         for date, day_dict in d['days'].items():
224             self.days[date] = self.add_day(dict_source=day_dict)
225         self.selected_day.archived = False 
226         for uuid, t_dict in d['tasks'].items():
227             t = self.add_task(id_=uuid, dict_source=t_dict)
228             t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
229                     and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
230                     and ((not self.hide_unchosen) or uuid in self.selected_day.todos)
231             for tag in t.tags:
232                 self.t_tags.add(tag)
233
234     def to_dict(self):
235         d = {
236                 'selected_day_date': self.selected_day_date,
237                 't_filter_and': list(self.t_filter_and),
238                 't_filter_not': list(self.t_filter_not),
239                 'tasks': {},
240                 'days': {}
241         }
242         for uuid, t in self.tasks.items():
243              d['tasks'][uuid] = t.to_dict()
244         for date, day in self.days.items():
245             d['days'][date] = day.to_dict()
246         return d
247
248     def write(self):
249         self.write_text_to_db(json.dumps(self.to_dict()))
250
251     def switch_to_day(self, date=None):
252         if self.selected_day_date in self.days.keys():
253             self.selected_day.archived = True 
254         if date:
255             self.selected_day_date = date 
256         else:
257             self.selected_day_date = str(datetime.now())[:10]
258             if not self.selected_day_date in self.days.keys():
259                 self.days[self.selected_day_date] = self.add_day()
260         self.selected_day.archived = False 
261
262     def add_task(self, id_=None, dict_source=None, return_id=False):
263         t = Task.from_dict(self, dict_source) if dict_source else Task(self)
264         id_ = id_ if id_ else str(uuid4())
265         self.tasks[id_] = t
266         if return_id:
267             return id_, t
268         else: 
269             return t
270
271     def add_day(self, dict_source=None):
272         return Day.from_dict(self, dict_source) if dict_source else Day(self)
273
274     def show_all(self):
275         for i in range(10):
276             self.add_task(id_=f'new{i}') 
277         for date, day in self.days.items():
278             for task_uuid, todo in day.todos.items():
279                 todo.title = self.tasks[task_uuid].title_at(date)
280         return Template(selected_day_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all')
281
282     @property
283     def selected_day(self):
284         return self.days[self.selected_day_date]
285
286     def show_selected_day(self):
287         return Template(selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
288
289
290 class TodoHandler(PlomHandler):
291     
292     def app_init(self, handler):
293         default_path = '/todo'
294         handler.add_route('GET', default_path, self.show_db) 
295         handler.add_route('POST', default_path, self.write_db) 
296         return 'todo', default_path 
297
298     def do_POST(self):
299         self.try_do(self.write_db)
300
301     def write_db(self):
302         from urllib.parse import urlencode
303         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
304         db = TodoDB(prefix)
305         length = int(self.headers['content-length'])
306         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
307         # import pprint
308         # pp = pprint.PrettyPrinter(indent=4)
309         # pp.pprint(postvars)
310         db.t_filter_and = set()
311         db.t_filter_not = set()
312         if 't_filter_and' in postvars.keys():
313             for target in postvars['t_filter_and']:
314                 db.t_filter_and.add(target) 
315         if 't_filter_not' in postvars.keys():
316             for target in postvars['t_filter_not']:
317                 db.t_filter_not.add(target) 
318         if 'hide_unchosen' in postvars.keys():
319             db.hide_unchosen = True
320         if 't_uuid' in postvars.keys():
321             new_postvars_t_uuid = postvars['t_uuid'].copy()
322             for i, uuid in enumerate(postvars['t_uuid']):
323                 if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
324                         new_uuid, t = db.add_task(return_id=True)
325                         new_postvars_t_uuid[i] = new_uuid
326                         for key in [k for k in postvars.keys() if not k == 't_uuid']:
327                             if uuid in postvars[key]:
328                                 uuid_index = postvars[key].index(uuid)
329                                 postvars[key][uuid_index] = new_uuid
330             postvars['t_uuid'] = new_postvars_t_uuid
331             for i, uuid in enumerate(postvars['t_uuid']):
332                 if len(uuid) < 36:
333                     continue
334                 t = db.tasks[uuid]
335                 t.set_title(postvars['t_title'][i])
336                 t.tags_from_joined_string(postvars['t_tags'][i])
337                 t.set_default_weight(float(postvars['t_default_weight'][i]))
338                 if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
339                     del db.selected_day.todos[uuid]
340             if 'choose' in postvars.keys():
341                 for i, uuid in enumerate(postvars['t_uuid']):
342                     if uuid in postvars['choose']:
343                         done = 'done' in postvars and uuid in postvars['done']
344                         day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
345                         db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
346
347         db.selected_day.comment = postvars['comment'][0]
348         new_selected_day_date = postvars['selected_day_date'][0]
349         if new_selected_day_date != db.selected_day_date:
350             if new_selected_day_date in db.days.keys():
351                 raise PlomException('cannot use same date twice')
352             else:
353                 db.days[new_selected_day_date] = db.selected_day
354                 del db.days[db.selected_day_date]
355                 db.selected_day_date = new_selected_day_date
356
357         switch_edited_day = None
358         for date in db.days.keys():
359             if f'edit_{date}' in postvars.keys():
360                 switch_edited_day = date
361                 break
362         if 'archive_day' in postvars.keys() or switch_edited_day:
363             if switch_edited_day:
364                 db.switch_to_day(date) 
365             else:
366                 db.switch_to_day()
367         db.write()
368         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))]
369         encoded_params = urlencode(data)
370         parsed_url = urlparse(self.path)
371         if prefix + '/day' == parsed_url.path:
372             homepage = f'{prefix}/day?{encoded_params}'
373         else:
374             homepage = f'{prefix}/all?{encoded_params}'
375         self.redirect(homepage)
376
377     def do_GET(self):
378         self.try_do(self.show_db)
379
380     def show_db(self):
381         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
382         parsed_url = urlparse(self.path)
383         params = parse_qs(parsed_url.query)
384         t_filter_and = set(params.get('t_and', []))
385         t_filter_not = set(params.get('t_not', ['deleted']))
386         hide_unchosen_params = params.get('hide_unchosen', [])
387         hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
388         db = TodoDB(prefix, t_filter_and, t_filter_not, hide_unchosen)
389         if parsed_url.path == prefix + '/day':
390             page = db.show_selected_day()
391         else:
392             page = db.show_all()
393         header = Template(html_head).render(prefix=prefix)
394         self.send_HTML(header + page)
395
396
397 if __name__ == "__main__":  
398     run_server(server_port, TodoHandler)