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