1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
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'
12 td { border: 1px solid black; }
15 <form action="{{homepage}}" method="POST">
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 }}
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 }}
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) %}
29 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
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>
42 <input type="submit" value="OK">
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>
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()
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
67 def _last_of_history(self, history, default):
68 keys = sorted(history.keys())
69 return default if 0 == len(history) else history[keys[-1]]
72 def from_dict(cls, d):
75 {k: set(v) for k, v in d['tags_history'].items()},
76 d['default_weight_history'])
78 def tags_from_joined_string(self, tags_string):
80 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
85 def tags_joined(self):
86 return ';'.join(sorted(list(self.tags)))
88 def set_default_weight(self, default_weight):
89 self._set_with_history(self.default_weight_history, default_weight)
92 def default_weight(self):
93 return self._last_of_history(self.default_weight_history, 1)
95 def set_title(self, title):
96 self._set_with_history(self.title_history, title)
100 return self._last_of_history(self.title_history, '')
102 def set_tags(self, tags):
103 self._set_with_history(self.tags_history, set(tags))
107 return self._last_of_history(self.tags_history, set())
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}
118 def __init__(self, todos, comment=''):
120 self.comment = comment
123 def from_dict(cls, d):
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)
133 for todo in [todo for todo in self.todos.values() if (todo.done or todo.day_weight)]:
138 d = {'comment': self.comment, 'todos': {}}
139 for task_uuid, todo in self.todos.items():
140 d['todos'][task_uuid] = todo.to_dict()
146 def __init__(self, done=False, day_weight=None):
148 self.day_weight = day_weight
151 def from_dict(cls, d):
152 return cls(d['done'], d['day_weight'])
155 return {'done': self.done, 'day_weight': self.day_weight}
158 class TodoDB(PlomDB):
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
167 super().__init__(db_path)
169 def read_db_file(self, 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)
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
180 for date, day_dict in d['old_days'].items():
181 self.old_days[date] = Day.from_dict(day_dict)
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),
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()
199 self.write_text_to_db(json.dumps(self.to_dict()))
201 def reset_today(self, date=None):
203 self.today_date = date
204 self.today = self.old_days[date]
205 del self.old_days[date]
207 self.today_date = str(datetime.now())[:10]
211 class TodoHandler(PlomHandler):
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
220 self.try_do(self.write_db)
223 from urllib.parse import urlencode
225 length = int(self.headers['content-length'])
226 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
229 pp = pprint.PrettyPrinter(indent=4)
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:
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']):
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
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:
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)
291 self.try_do(self.show_db)
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)
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)
313 if __name__ == "__main__":
314 run_server(server_port, TodoHandler)