home · contact · privacy
Add 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 db_path = '/home/plom/org/todo_new.json'
7 # db_path = '/home/plom/public_repos/misc/todo_new.json'
8 server_port = 8082
9
10 tmpl = """
11 <style>
12 td { border: 1px solid black; }
13 </style>
14 <body>
15 <form action="{{homepage}}" method="POST">
16
17 mandatory tags: {% for t_tag in db.t_tags | sort %}
18 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
19 {% endfor %}
20 <br />
21 forbidden tags: {% for t_tag in db.t_tags | sort %}
22 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
23 {% endfor %}
24 <table>
25 <tr><th colspan=2></th><th>date</th><td colspan=2><input name="today_date" value="{{ db.today_date }}" size=8 /></td><th>archive?</th><td><input type="checkbox" name="archive_today" /></td><td>{{ db.today.todos_sum|round(2) }}</td><th>comment:</th><td><input name="comment" value="{{ db.today.comment|e }}"></td></tr>
26 <tr><th>weight</th><th>title</th><th>tags</th><th>today?</th><th>done?</th><th colspan=2>day weight</th></tr>
27 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
28 {% if t.visible %}
29 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
30 <tr>
31 <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
32 <td><input name="t_title" value="{{ t.title|e }}"/></td>
33 <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
34 <td><input name="do_today" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() %}checked{% endif %} ></td>
35 <td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() and db.today.todos[uuid].done %}checked{% endif %} ></td>
36 <td colspan=2><input name="day_weight" type="number" step=0.1 size=5 value="{% if uuid in db.today.todos.keys() and db.today.todos[uuid].day_weight %}{{ db.today.todos[uuid].day_weight }}{% endif %}" ></td>
37 </tr>
38 {% endif %}
39 {% endfor %}
40 </table>
41
42 <input type="submit" value="OK">
43 <table>
44 {% for date, day in db.old_days.items() | sort(reverse=True) %}
45 <tr><td>{{ date }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
46 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
47 <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
48 {% endfor %}
49 {% endfor %}
50 </table>
51 </form>
52 """
53
54 class Task:
55
56     def __init__(self, title_history={}, tags_history={}, default_weight_history={}):
57         self.title_history = title_history.copy()
58         self.tags_history = tags_history.copy()
59         self.default_weight_history = default_weight_history.copy()
60         self.visible = True
61
62     def _set_with_history(self, history, value):
63         keys = sorted(history.keys())
64         if len(history) == 0 or value != history[keys[-1]]:
65             history[str(datetime.now())[:19]] = value
66
67     def _last_of_history(self, history, default):
68         keys = sorted(history.keys())
69         return default if 0 == len(history) else history[keys[-1]] 
70
71     @classmethod
72     def from_dict(cls, d):
73         return cls(
74                 d['title_history'],
75                 {k: set(v) for k, v in d['tags_history'].items()},
76                 d['default_weight_history'])
77
78     def tags_from_joined_string(self, tags_string):
79         tags = set()
80         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
81             tags.add(tag)
82         self.set_tags(tags)
83
84     @property
85     def tags_joined(self):
86         return ';'.join(sorted(list(self.tags)))
87
88     def set_default_weight(self, default_weight):
89         self._set_with_history(self.default_weight_history, default_weight)
90
91     @property
92     def default_weight(self):
93         return self._last_of_history(self.default_weight_history, 1)
94
95     def set_title(self, title):
96         self._set_with_history(self.title_history, title)
97
98     @property
99     def title(self):
100         return self._last_of_history(self.title_history, '')
101
102     def set_tags(self, tags):
103         self._set_with_history(self.tags_history, set(tags))
104
105     @property
106     def tags(self):
107         return self._last_of_history(self.tags_history, set())
108
109     def to_dict(self):
110         return {
111             'title_history': self.title_history,
112             'tags_history': {k: list(v) for k,v in self.tags_history.items()},
113             'default_weight_history': self.default_weight_history}
114
115
116 class Day:
117
118     def __init__(self, todos, comment=''):
119         self.todos = todos 
120         self.comment = comment
121
122     @classmethod
123     def from_dict(cls, d):
124         todos = {}
125         comment = d['comment'] if 'comment' in d.keys() else ''
126         for uuid, todo_dict in d['todos'].items():
127             todos[uuid] = Todo.from_dict(todo_dict)
128         return cls(todos, comment)
129
130     @property
131     def todos_sum(self):
132         s = 0
133         for todo in [todo for todo in self.todos.values() if (todo.done or todo.day_weight)]:
134             s += todo.weight
135         return s
136
137     def to_dict(self):
138         d = {'comment': self.comment, 'todos': {}}
139         for task_uuid, todo in self.todos.items():
140             d['todos'][task_uuid] = todo.to_dict()
141         return d
142
143
144 class Todo:
145
146     def __init__(self, done=False, day_weight=None):
147         self.done = done
148         self.day_weight = day_weight
149
150     @classmethod
151     def from_dict(cls, d):
152         return cls(d['done'], d['day_weight'])
153
154     def to_dict(self):
155         return {'done': self.done, 'day_weight': self.day_weight}
156
157
158 class TodoDB(PlomDB):
159
160     def __init__(self, t_filter_and = set(), t_filter_not = set()):
161         self.t_filter_and = t_filter_and
162         self.t_filter_not = t_filter_not
163         self.old_days = {}
164         self.tasks = {}
165         self.reset_today()
166         self.t_tags = set() 
167         super().__init__(db_path)
168
169     def read_db_file(self, f):
170         d = json.load(f)
171         self.today = Day.from_dict(d['today'])
172         self.today_date = d['today_date'] 
173         for uuid, t_dict in d['tasks'].items():
174             t = Task.from_dict(t_dict)
175             self.tasks[uuid] = t
176             t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
177                     and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0
178             for tag in t.tags:
179                 self.t_tags.add(tag)
180         for date, day_dict in d['old_days'].items():
181             self.old_days[date] = Day.from_dict(day_dict)
182
183     def to_dict(self):
184         d = {
185                 'today': self.today.to_dict(),
186                 'today_date': self.today_date,
187                 't_filter_and': list(self.t_filter_and),
188                 't_filter_not': list(self.t_filter_not),
189                 'tasks': {},
190                 'old_days': {}
191         }
192         for uuid, t in self.tasks.items():
193              d['tasks'][uuid] = t.to_dict()
194         for date, day in self.old_days.items():
195             d['old_days'][date] = day.to_dict()
196         return d
197
198     def write(self):
199         self.write_text_to_db(json.dumps(self.to_dict()))
200
201     def reset_today(self, date=None):
202         if date:
203             self.today_date = date 
204             self.today = self.old_days[date]
205             del self.old_days[date]
206         else:
207             self.today_date = str(datetime.now())[:10]
208             self.today = Day({})
209
210
211 class TodoHandler(PlomHandler):
212     
213     def app_init(self, handler):
214         default_path = '/todo'
215         handler.add_route('GET', default_path, self.show_db) 
216         handler.add_route('POST', default_path, self.write_db) 
217         return 'todo', default_path 
218
219     def do_POST(self):
220         self.try_do(self.write_db)
221
222     def write_db(self):
223         from urllib.parse import urlencode
224         db = TodoDB()
225         length = int(self.headers['content-length'])
226         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
227
228         import pprint
229         pp = pprint.PrettyPrinter(indent=4)
230         pp.pprint(postvars)
231
232         db.t_filter_and = set()
233         db.t_filter_not = set()
234         if 't_filter_and' in postvars.keys():
235             for target in postvars['t_filter_and']:
236                 db.t_filter_and.add(target) 
237         if 't_filter_not' in postvars.keys():
238             for target in postvars['t_filter_not']:
239                 db.t_filter_not.add(target) 
240         if 't_uuid' in postvars.keys():
241             new_postvars_t_uuid = postvars['t_uuid'].copy()
242             for i, uuid in enumerate(postvars['t_uuid']):
243                 if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
244                         t = Task() 
245                         new_uuid = str(uuid4()) 
246                         db.tasks[new_uuid] = t
247                         new_postvars_t_uuid[i] = new_uuid
248                         for key in [k for k in postvars.keys() if not k == 't_uuid']:
249                             if uuid in postvars[key]:
250                                 uuid_index = postvars[key].index(uuid)
251                                 postvars[key][uuid_index] = new_uuid
252             postvars['t_uuid'] = new_postvars_t_uuid
253             for i, uuid in enumerate(postvars['t_uuid']):
254                 if len(uuid) < 36:
255                     continue
256                 t = db.tasks[uuid]
257                 t.set_title(postvars['t_title'][i])
258                 t.tags_from_joined_string(postvars['t_tags'][i])
259                 t.set_default_weight(float(postvars['t_default_weight'][i]))
260                 if uuid in db.today.todos.keys() and ((not 'do_today' in postvars) or uuid not in postvars['do_today']):
261                     del db.today.todos[uuid]
262             if 'do_today' in postvars.keys():
263                 for i, uuid in enumerate(postvars['t_uuid']):
264                     if uuid in postvars['do_today']:
265                         done = 'done' in postvars and uuid in postvars['done']
266                         day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
267                         db.today.todos[uuid] = Todo(done, day_weight)
268         db.today_date = postvars['today_date'][0]
269         db.today.comment = postvars['comment'][0]
270         switch_edited_day = None
271         for date in db.old_days.keys():
272             if f'edit_{date}' in postvars.keys():
273                 switch_edited_day = date
274                 break
275         if 'archive_today' in postvars.keys() or switch_edited_day:
276             if db.today_date in db.old_days.keys():
277                 raise PlomException('cannot use same date twice')
278             db.old_days[db.today_date] = db.today
279             if switch_edited_day:
280                 db.reset_today(date) 
281             else:
282                 db.reset_today()
283         db.write()
284         homepage = self.apps['todo'] if hasattr(self, 'apps') else self.homepage
285         data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
286         encoded_params = urlencode(data)
287         homepage += '?' + encoded_params
288         self.redirect(homepage)
289
290     def do_GET(self):
291         self.try_do(self.show_db)
292
293     def show_db(self):
294         from jinja2 import Template
295         from urllib.parse import urlparse
296         parsed_url = urlparse(self.path)
297         params = parse_qs(parsed_url.query)
298         t_filter_and = set(params.get('t_and', []))
299         t_filter_not = set(params.get('t_not', ['deleted']))
300         db = TodoDB(t_filter_and, t_filter_not)
301         for i in range(10):
302             db.tasks[f'new{i}'] = Task()
303         for task_uuid, todo in db.today.todos.items():
304             todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight 
305         for date, day in db.old_days.items():
306             for task_uuid, todo in day.todos.items():
307                 todo.title = db.tasks[task_uuid].title
308                 todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight 
309         page = Template(tmpl).render(db=db)
310         self.send_HTML(page)
311
312
313 if __name__ == "__main__":  
314     run_server(server_port, TodoHandler)