X-Git-Url: https://plomlompom.com/repos/new_day?a=blobdiff_plain;f=todo.py;h=e0bedaf37888e179f717654683419dee8020c8a0;hb=13a15b95ade73f4455db648b70e1de784c515039;hp=08fb8b82f6e3921ce6d75c3e86428d31c6398902;hpb=2960beb644986049fd975eac8e348ca61ab122b8;p=misc diff --git a/todo.py b/todo.py index 08fb8b8..e0bedaf 100644 --- a/todo.py +++ b/todo.py @@ -1,62 +1,26 @@ -from plomlib import PlomDB, run_server, PlomHandler, PlomException +from plomlib import PlomDB, run_server, PlomHandler, PlomException import json from uuid import uuid4 -from datetime import datetime +from datetime import datetime, timedelta from urllib.parse import parse_qs +from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader +from urllib.parse import urlparse +from os.path import split as path_split db_path = '/home/plom/org/todo_new.json' -# db_path = '/home/plom/public_repos/misc/todo_new.json' server_port = 8082 - -tmpl = """ - -
- -""" +DATE_FORMAT = '%Y-%m-%d' +j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates')) class Task: - def __init__(self, title_history={}, tags_history={}, default_weight_history={}): - self.title_history = title_history.copy() - self.tags_history = tags_history.copy() - self.default_weight_history = default_weight_history.copy() + def __init__(self, db, id_, title_history=None, tags_history=None, default_effort_history=None, links_history=None, comment=''): + self.id_ = id_ + self.db = db + self.title_history = title_history if title_history else {} + self.tags_history = tags_history if tags_history else {} + self.default_effort_history = default_effort_history if default_effort_history else {} + self.links_history = links_history if links_history else {} + self.comment = comment self.visible = True def _set_with_history(self, history, value): @@ -66,249 +30,942 @@ class Task: def _last_of_history(self, history, default): keys = sorted(history.keys()) - return default if 0 == len(history) else history[keys[-1]] + return default if 0 == len(history) else history[keys[-1]] @classmethod - def from_dict(cls, d): - return cls( - d['title_history'], - {k: set(v) for k, v in d['tags_history'].items()}, - d['default_weight_history']) + def from_dict(cls, db, d, id_): + t = cls( + db, + id_, + d['title_history'], + {k: set(v) for k, v in d['tags_history'].items()}, + d['default_effort_history'], + {k: set(v) for k, v in d['links_history'].items()}, + d['comment']) + return t - def tags_from_joined_string(self, tags_string): - tags = set() - for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']: - tags.add(tag) - self.set_tags(tags) + def to_dict(self): + return { + 'title_history': self.title_history, + 'default_effort_history': self.default_effort_history, + 'tags_history': {k: list(v) for k,v in self.tags_history.items()}, + 'links_history': {k: list(v) for k,v in self.links_history.items()}, + 'comment': self.comment, + } @property - def tags_joined(self): - return ';'.join(sorted(list(self.tags))) + def default_effort(self): + return self._last_of_history(self.default_effort_history, 1) - def set_default_weight(self, default_weight): - self._set_with_history(self.default_weight_history, default_weight) + @default_effort.setter + def default_effort(self, default_effort): + self._set_with_history(self.default_effort_history, default_effort) + + def default_effort_at(self, queried_date): + ret = self.default_effort_history[sorted(self.default_effort_history.keys())[0]] + for date_key, default_effort in self.default_effort_history.items(): + if date_key > f'{queried_date} 23:59:59': + break + ret = default_effort + return ret @property - def default_weight(self): - return self._last_of_history(self.default_weight_history, 1) + def current_default_effort(self): + return self.default_effort_at(self.db.selected_date) - def set_title(self, title): - self._set_with_history(self.title_history, title) + def matches(self, search): + if search is None: + return False + else: + return search in self.title or search in self.comment or search in '$'.join(self.tags) or search in self.title @property def title(self): return self._last_of_history(self.title_history, '') - def set_tags(self, tags): - self._set_with_history(self.tags_history, set(tags)) + @title.setter + def title(self, title): + self._set_with_history(self.title_history, title) + + def title_at(self, queried_date): + ret = self.title_history[sorted(self.title_history.keys())[0]] + for date_key, title in self.title_history.items(): + if date_key > f'{queried_date} 23:59:59': + break + ret = title + return ret + + @property + def current_title(self): + return self.title_at(self.db.selected_date) @property def tags(self): return self._last_of_history(self.tags_history, set()) - def to_dict(self): - return { - 'title_history': self.title_history, - 'tags_history': {k: list(v) for k,v in self.tags_history.items()}, - 'default_weight_history': self.default_weight_history} + @tags.setter + def tags(self, tags): + self._set_with_history(self.tags_history, set(tags)) + + @property + def links(self): + return self._last_of_history(self.links_history, set()) + + @links.setter + def links(self, links): + self._set_with_history(self.links_history, set(links)) + + # @property + # def id_(self): + # for k, v in self.db.tasks.items(): + # if v == self: + # return k class Day: - def __init__(self, todos, comment=''): - self.todos = todos + # def __init__(self, db, todos=None, comment='', date=None): + def __init__(self, db, date, comment=''): + self.date = date + self.db = db self.comment = comment + self.archived = True + self.todos = {} # legacy + self.linked_todos_as_list = [] + # if todos: + # for id_, todo_dict in todos.items(): + # self.add_todo(id_, todo_dict) @classmethod - def from_dict(cls, d): - todos = {} + def from_dict(cls, db, d, date=None): + # todos = {} comment = d['comment'] if 'comment' in d.keys() else '' - for uuid, todo_dict in d['todos'].items(): - todos[uuid] = Todo.from_dict(todo_dict) - return cls(todos, comment) + day = cls(db, date, comment) + # if 'todos' in d.keys(): + # for uuid, todo_dict in d['todos'].items(): + # day.add_todo(uuid, todo_dict) + # if 'linked_todos' in d.keys(): + for id_ in d['linked_todos']: + # if id_ in day.linked_todos.keys(): + # continue + # if id_ is None: + # continue + # linked_todo = db.todos[id_] + # linked_todo._day = day + # day.linked_todos_as_list += [linked_todo] + day.linked_todos_as_list += [db.todos[id_]] + return day + + def to_dict(self): + d = {'comment': self.comment, 'linked_todos': []} + for todo_id in self.linked_todos.keys(): + d['linked_todos'] += [todo_id] + # for task_uuid, todo in self.todos.items(): + # for id_, todo in self.todos.items(): + # # d['todos'][task_uuid] = todo.to_dict() + # new_type_todo_id = f'{self.date}_{task_uuid}' + # if not new_type_todo_id in d['linked_todos']: + # # d['linked_todos'] += [todo.id_] + # d['linked_todos'] += [new_type_todo_id] + return d + + # def add_todo(self, task_id, dict_source=None): + # new_type_todo_id = f'{self.date}_{task_id}' + # task = self.db.tasks[task_id] + # if new_type_todo_id in self.db.todos.keys(): + # todo = self.db.todos[new_type_todo_id] + # # elif task_id in self.db.keys(): + # # todo = self.db.todos[task_id] + # else: + # # todo = Todo.from_dict(self.db, dict_source, id_=new_type_todo_id) if dict_source else Todo(db=self.db, day=self) + # todo = Todo.from_dict(self.db, dict_source) + # # todo._id = new_type_todo_id + # todo._task = self.db.tasks[task_id] + # todo._id = new_type_todo_id + # todo._day = self + # # self.todos[task_id] = todo + # self.linked_todos_as_list += [todo] + # self.db.todos[new_type_todo_id] = todo + # # self.db.todos[todo.task_id] = [todo] + # # self.db.todos_as_list += [todo] + # # self.db.all_todos[todo.task_id] = todo + # return todo @property - def todos_sum(self): + def linked_todos(self): + linked_todos = {} + for todo in self.linked_todos_as_list: + linked_todos[todo.id_] = todo + return linked_todos + + def _todos_sum(self, include_undone=False): s = 0 - for todo in [todo for todo in self.todos.values() if (todo.done or todo.day_weight)]: - s += todo.weight + for todo in [todo for todo in self.linked_todos.values() + if self.date in todo.efforts.keys()]: + day_effort = todo.efforts[self.date] + if todo.done: + s += day_effort if day_effort else todo.task.default_effort_at(self.date) + elif include_undone: + s += day_effort if day_effort else 0 return s - def to_dict(self): - d = {'comment': self.comment, 'todos': {}} - for task_uuid, todo in self.todos.items(): - d['todos'][task_uuid] = todo.to_dict() - return d + @property + def todos_sum(self): + return self._todos_sum() + + @property + def todos_sum2(self): + return self._todos_sum(True) + + # @property + # def date(self): + # if self._date: + # return self._date + # else: + # for k, v in self.db.days.items(): + # # print("DEBUG date", k, v) + # if v == self: + # return k + # print("DEBUG FAIL", self.test_date, self) class Todo: - def __init__(self, done=False, day_weight=None): + # def __init__(self, db, id_, task, done=False, day_effort=None, comment='', day_tags=None, importance=1.0, efforts=None): + def __init__(self, db, id_, task, done=False, comment='', day_tags=None, importance=1.0, efforts=None): + self.id_ = id_ + self.db = db + self.task = task self.done = done - self.day_weight = day_weight + # self.day_effort = day_effort + self.efforts = efforts if efforts else {} + self.comment = comment + self.day_tags = day_tags if day_tags else set() + self.importance = importance @classmethod - def from_dict(cls, d): - return cls(d['done'], d['day_weight']) + def from_dict(cls, db, d, id_): + # todo = cls(db, None, None, d['done'], d['day_effort'], d['comment'], set(d['day_tags']), d['importance']) + # todo._task = db.tasks[d['task']] if 'task' in d.keys() else None + # todo._efforts = d['efforts'] if 'efforts' in d.keys() else None + # todo = cls(db, id_, db.tasks[d['task']], d['done'], d['day_effort'], d['comment'], set(d['day_tags']), d['importance'], d['efforts']) + todo = cls(db, id_, db.tasks[d['task']], d['done'], d['comment'], set(d['day_tags']), d['importance'], d['efforts']) + return todo + + # @classmethod + # def OLD_from_dict(cls, day, d): + # todo = cls(day, d['done'], d['day_effort'], d['comment'], set(d['day_tags']), d['importance']) + # if 'efforts' in d.keys(): + # todo._efforts = d['efforts'] + # return todo def to_dict(self): - return {'done': self.done, 'day_weight': self.day_weight} + # return {'task': self.task.id_, 'done': self.done, 'day_effort': self.day_effort, 'comment': self.comment, 'day_tags': list(self.day_tags), 'importance': self.importance, 'efforts': self.efforts} + return {'task': self.task.id_, 'done': self.done, 'comment': self.comment, 'day_tags': list(self.day_tags), 'importance': self.importance, 'efforts': self.efforts} + + @property + def default_effort(self): + return self.task.default_effort_at(self.day.date) + + # @property + # def effort(self): + # if self.day_effort: + # return self.day_effort + # else: + # return self.day_effort if self.day_effort else self.default_effort + + # @property + # def task(self): + # if self._task: + # return self._task + # # else: + # # for k, v in self.day.todos.items(): + # # if v == self: + # # return self.db.tasks[k] + + def matches(self, search): + if search is None: + return False + else: + return search in self.comment or search in '$'.join(self.tags) or search in self.title + + @property + def title(self): + return self.task.title_at(self.day.date) + + @property + def tags(self): + return self.day_tags | self.task.tags + + def internals_empty(self): + return len(self.comment) == 0 and len(self.day_tags) == 0 + + # def ensure_day_efforts_table(self): + # # We don't do this yet at __init__ because self.day.date is unknown, since Todo may be imported with Day, and during the import process the Day is not yet keyed in TodoDB.days. + # if not hasattr(self, '_efforts'): + # self._efforts = {} # {self.day.date: self.day_effort} + + # def set_day_effort(self, date, effort): + # self.ensure_day_efforts_table() + # self._efforts[date] = self.day_effort + + @property + def day_effort(self): + return self.efforts[self.db.selected_date] + + @property + def day(self): + if len(self.efforts) == 0: + return None + dates = list(self.efforts.keys()) + dates.sort() + todo_start_date = dates[0] + return self.db.days[todo_start_date] + + # @property + # def efforts(self): + # self.ensure_day_efforts_table() + # return self._efforts + + # @property + # def id_(self): + # if self._id: + # return self._id + # for k, v in self.db.todos.items(): + # if v == self: + # return k + # # return f'{self.day.date}_{self.task.id_}' class TodoDB(PlomDB): - def __init__(self, t_filter_and = set(), t_filter_not = set()): - self.t_filter_and = t_filter_and - self.t_filter_not = t_filter_not - self.old_days = {} + def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False, hide_done=False): + self.prefix = prefix + self.selected_date = selected_date if selected_date else str(datetime.now())[:10] + self.t_filter_and = t_filter_and if t_filter_and else [] + self.t_filter_not = t_filter_not if t_filter_not else [] + self.hide_unchosen = hide_unchosen + self.hide_done = hide_done + self.days = {} self.tasks = {} - self.reset_today() - self.t_tags = set() + self.t_tags = set() + self.todos = {} super().__init__(db_path) def read_db_file(self, f): d = json.load(f) - self.today = Day.from_dict(d['today']) - self.today_date = d['today_date'] - for uuid, t_dict in d['tasks'].items(): - t = Task.from_dict(t_dict) - self.tasks[uuid] = t - t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\ - and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0 + for id_, t_dict in d['tasks'].items(): + t = self.add_task(id_=id_, dict_source=t_dict) for tag in t.tags: self.t_tags.add(tag) - for date, day_dict in d['old_days'].items(): - self.old_days[date] = Day.from_dict(day_dict) + # if 'todos' in d.keys(): + for id_, todo_dict in d['todos'].items(): + # todo = Todo.from_dict(self, todo_dict, id_) + # todo._id = id_ + # self.todos[id_] = todo + todo = self.add_todo(todo_dict, id_) # Todo.from_dict(self, todo_dict, id_) + self.todos[id_] = todo + for tag in todo.day_tags: + self.t_tags.add(tag) + for date, day_dict in d['days'].items(): + self.add_day(dict_source=day_dict, date=date) + # for todo in self.todos.values(): + # for day in self.days.values(): + # for todo in day.todos.values(): + # for tag in todo.day_tags: + # self.t_tags.add(tag) + self.set_visibilities() + + def set_visibilities(self): + for uuid, t in self.tasks.items(): + t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\ + and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\ + and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys()) + # for day in self.days.values(): + # for todo in day.todos.values(): + # todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags ]) == 0\ + # and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags ]) == 0\ + # and ((not self.hide_done) or (not todo.done)) + for todo in self.todos.values(): + todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags ]) == 0\ + and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags ]) == 0\ + and ((not self.hide_done) or (not todo.done)) def to_dict(self): - d = { - 'today': self.today.to_dict(), - 'today_date': self.today_date, - 't_filter_and': list(self.t_filter_and), - 't_filter_not': list(self.t_filter_not), - 'tasks': {}, - 'old_days': {} - } + d = {'tasks': {}, 'days': {}, 'todos': {}} for uuid, t in self.tasks.items(): d['tasks'][uuid] = t.to_dict() - for date, day in self.old_days.items(): - d['old_days'][date] = day.to_dict() + for date, day in self.days.items(): + d['days'][date] = day.to_dict() + for todo in day.todos.values(): + d['todos'][todo.id_] = todo.to_dict() + for id_, todo in self.todos.items(): + d['todos'][id_] = todo.to_dict() return d + # @property + # def all_todos(self): + # todos = {} + # for todo in self.todos_as_list: + # todos[todo.id_] = todo + # return todos + + @property + def selected_day(self): + if not self.selected_date in self.days.keys(): + self.days[self.selected_date] = self.add_day(date=self.selected_date) + # print("DEBUG selected_day", self.days[self.selected_date].date) + return self.days[self.selected_date] + def write(self): + dates_to_purge = [] + for date, day in self.days.items(): + if len(day.linked_todos) == 0 and len(day.comment) == 0: + dates_to_purge += [date] + for date in dates_to_purge: + del self.days[date] self.write_text_to_db(json.dumps(self.to_dict())) - def reset_today(self, date=None): - if date: - self.today_date = date - self.today = self.old_days[date] - del self.old_days[date] + def add_task(self, id_=None, dict_source=None, return_id=False): + id_ = id_ if id_ else str(uuid4()) + t = Task.from_dict(self, dict_source, id_) if dict_source else Task(self, id) + self.tasks[id_] = t + if return_id: + return id_, t else: - self.today_date = str(datetime.now())[:10] - self.today = Day({}) + return t + + def add_todo(self, todo_dict, id_=None): + id_ = id_ if id_ else str(uuid4()) + todo = Todo.from_dict(self, todo_dict, id_) + self.todos[id_] = todo + return todo + + def add_day(self, date, dict_source=None): + day = Day.from_dict(self, dict_source, date) if dict_source else Day(self, date) + self.days[date] = day + return day + + def show_day(self, task_sort=None): + task_sort = task_sort if task_sort else 'title' + current_date = datetime.strptime(self.selected_date, DATE_FORMAT) + prev_date = current_date - timedelta(days=1) + prev_date_str = prev_date.strftime(DATE_FORMAT) + next_date = current_date + timedelta(days=1) + next_date_str = next_date.strftime(DATE_FORMAT) + task_rows = [] + for uuid, task in self.tasks.items(): + if not task.visible: + continue + todo = None + if uuid in self.selected_day.todos.keys(): + todo = self.selected_day.todos[uuid] + if not todo.visible: + continue + task_rows += [{'uuid': uuid, 'task': task, 'todo': todo}] + if task_sort == 'title': + task_rows.sort(key=lambda r: r['task'].title) + elif task_sort == 'default_effort': + task_rows.sort(key=lambda r: r['task'].default_effort, reverse=True) + elif task_sort == 'done': + task_rows.sort(key=lambda r: 0 if not r['todo'] else r['todo'].day_effort if r['todo'].day_effort else r['task'].default_effort if r['todo'].done else 0, reverse=True) + elif task_sort == 'importance': + task_rows.sort(key=lambda r: 0.0 if not r['todo'] else r['todo'].importance, reverse=True) + elif task_sort == 'chosen': + task_rows.sort(key=lambda r: False if not r['todo'] else True, reverse=True) + elif task_sort == 'comment': + task_rows.sort(key=lambda r: '' if not r['todo'] else r['todo'].comment, reverse=True) + done_tasks = [] + for uuid, task in self.tasks.items(): + if uuid in self.selected_day.todos.keys(): + todo = self.selected_day.todos[uuid] + if todo.done: + done_tasks += [todo] + done_tasks.sort(key=lambda t: t.effort, reverse=True) + return j2env.get_template('day.html').render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str, task_rows=task_rows, sort=task_sort, done_tasks=done_tasks) + + def neighbor_dates(self): + current_date = datetime.strptime(self.selected_date, DATE_FORMAT) + prev_date = current_date - timedelta(days=1) + prev_date_str = prev_date.strftime(DATE_FORMAT) + next_date = current_date + timedelta(days=1) + next_date_str = next_date.strftime(DATE_FORMAT) + return prev_date_str, next_date_str + + def show_do_day(self, sort_order=None): + prev_date_str, next_date_str = self.neighbor_dates() + # current_date = datetime.strptime(self.selected_date, DATE_FORMAT) + # prev_date = current_date - timedelta(days=1) + # prev_date_str = prev_date.strftime(DATE_FORMAT) + # next_date = current_date + timedelta(days=1) + # next_date_str = next_date.strftime(DATE_FORMAT) + todos = [t for t in self.selected_day.linked_todos_as_list if t.visible] + if sort_order == 'title': + todos.sort(key=lambda t: t.task.title) + elif sort_order == 'done': + todos.sort(key=lambda t: t.day_effort if t.day_effort else t.default_effort if t.done else 0, reverse=True) + elif sort_order == 'default_effort': + todos.sort(key=lambda t: t.task.default_effort, reverse=True) + elif sort_order == 'importance': + todos.sort(key=lambda t: t.importance, reverse=True) + return j2env.get_template('do_day.html').render( + day=self.selected_day, + prev_date=prev_date_str, + next_date=next_date_str, + todos=todos, + sort=sort_order, + hide_done=self.hide_done) + + def show_calendar(self, start_date_str, end_date_str): + self.t_filter_and = ['calendar'] + self.t_filter_not = ['deleted'] + self.set_visibilities() + days_to_show = {} + todays_date_str = str(datetime.now())[:10] + todays_date_obj = datetime.strptime(todays_date_str, DATE_FORMAT) + yesterdays_date_obj = todays_date_obj - timedelta(1) + yesterdays_date_str = yesterdays_date_obj.strftime(DATE_FORMAT) + start_date_obj = datetime.strptime(sorted(self.days.keys())[0], DATE_FORMAT) + if start_date_str and len(start_date_str) > 0: + if start_date_str in {'today', 'yesterday'}: + start_date_obj = todays_date_obj if start_date_str == 'today' else yesterdays_date_obj + else: + start_date_obj = datetime.strptime(start_date_str, DATE_FORMAT) + end_date_obj = datetime.strptime(sorted(self.days.keys())[-1], DATE_FORMAT) + if end_date_str and len(end_date_str) > 0: + if end_date_str in {'today', 'yesterday'}: + end_date_obj = todays_date_obj if end_date_str == 'today' else yesterdays_date_obj + else: + end_date_obj = datetime.strptime(end_date_str, DATE_FORMAT) + for n in range(int((end_date_obj - start_date_obj).days) + 1): + current_date_obj = start_date_obj + timedelta(n) + current_date_str = current_date_obj.strftime(DATE_FORMAT) + if current_date_str not in self.days.keys(): + days_to_show[current_date_str] = self.add_day(current_date_str) + else: + days_to_show[current_date_str] = self.days[current_date_str] + days_to_show[current_date_str].weekday = datetime.strptime(current_date_str, DATE_FORMAT).strftime('%A')[:2] + return j2env.get_template('calendar.html').render(db=self, days=days_to_show, action=self.prefix+'/calendar', start_date=start_date_str, end_date=end_date_str) + + def show_todo(self, id_, return_to): + todo = self.todos[id_] + # if selected_date not in self.days.keys(): + # self.days[selected_date] = self.add_day(test_date=f'3:{selected_date}') + # # print("DEBUG show_todo", self.days[selected_date].date) + # if task_uuid in self.days[selected_date].todos: + # todo = self.days[selected_date].todos[task_uuid] + # else: + # todo = self.days[selected_date].add_todo(task_uuid) + return j2env.get_template('todo.html').render(db=self, todo=todo, action=self.prefix+'/todo', return_to=return_to) + + def update_todo_mini(self, task_uuid, date, day_effort, done, importance): + if date not in self.days.keys(): + self.days[date] = self.add_day(test_date=f'Y:{date}') + # print("DEBUG update_todo_min", self.days[date].date) + if task_uuid in self.days[date].todos.keys(): + todo = self.days[date].todos[task_uuid] + else: + todo = self.days[date].add_todo(task_uuid) + todo.day_effort = day_effort + todo.done = done + todo.importance = importance + return todo + + def collect_tags(self, tags_joined, tags_checked): + tags = set() + for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']: + tags.add(tag) + for tag in tags_checked: + tags.add(tag) + return tags + + def update_todo_for_day(self, id_, date, effort, done, comment, importance): + todo = self.todos[id_] + todo.done = done + todo.efforts[date] = effort + todo.comment = comment + todo.importance = importance + + def update_todo(self, id_, efforts, done, comment, day_tags_joined, day_tags_checked, importance): + if len(efforts) == 0: + raise PlomException('todo must have at least one effort!') + todo = self.todos[id_] + todo.done = done + todo.efforts = efforts + for date in todo.efforts: + if not date in self.days.keys(): + self.add_day(date=date) + if not self in self.days[date].linked_todos_as_list: + self.days[date].linked_todos_as_list += [todo] + todo.comment = comment + todo.day_tags = self.collect_tags(day_tags_joined, day_tags_checked) + todo.importance = importance + + def delete_todo(self, id_): + todo = self.todos[id_] + for date in todo.efforts.keys(): + self.delete_effort(todo, date) + del self.todos[id_] + + def delete_effort(self, todo, date): + if todo in self.days[date].linked_todos_as_list: + self.days[date].linked_todos_as_list.remove(todo) + + + # def update_todo(self, task_uuid, date, day_effort, done, comment, day_tags_joined, day_tags_checked, importance): + # day_effort = float(day_effort) if len(day_effort) > 0 else None + # importance = float(importance) + # todo = self.update_todo_mini(task_uuid, date, day_effort, done, importance) + # todo.comment = comment + # todo.day_tags = self.collect_tags(day_tags_joined, day_tags_checked) + + def link_day_with_todo(self, date, todo_id): + print("DEBUG link", date, todo_id) + todo_creation_date, task_uuid = todo_id.split('_') + todo = self.days[todo_creation_date].todos[task_uuid] + if date in todo.efforts.keys(): + raise PlomException('todo already linked to respective day') + todo.set_day_effort(date, None) + if date not in self.days.keys(): + print("DEBUG link_day_with_todo", date) + self.days[date] = self.add_day(test_date=f'Z:{date}') + self.days[date].linked_todos_as_list += [todo] + print("DEBUG", date, self.days[date].linked_todos) + + def show_task(self, id_, return_to=''): + task = self.tasks[id_] if id_ else self.add_task() + selected = id_ in self.selected_day.todos.keys() + return j2env.get_template('task.html').render(db=self, task=task, action=self.prefix+'/task', return_to=return_to, selected=selected) + + def update_task(self, id_, title, default_effort, tags_joined, tags_checked, links, comment): + task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_) + task.title = title + task.default_effort = float(default_effort) if len(default_effort) > 0 else None + task.tags = self.collect_tags(tags_joined, tags_checked) + task.links = links + for link in links: + borrowed_links = self.tasks[link].links + borrowed_links.add(id_) + self.tasks[link].links = borrowed_links + task.comment = comment + + def show_tasks(self, expand_uuid): + expanded_tasks = {} + if expand_uuid: + for uuid in self.tasks[expand_uuid].links: + expanded_tasks[uuid] = self.tasks[uuid] + return j2env.get_template('tasks.html').render(db=self, action=self.prefix+'/tasks', expand_uuid=expand_uuid, expanded_tasks=expanded_tasks) + + def new_day(self, search): + prev_date_str, next_date_str = self.neighbor_dates() + relevant_todos = [] + for todo in self.todos.values(): + # if todo.done or (not todo.visible) or (not todo.matches(search)) or todo.day.date == self.selected_day.date: # TODO or todo is linked by day + if todo.done or (not todo.visible) or (not todo.matches(search)): # or todo.day.date == self.selected_day.date: # TODO or todo is linked by day + continue + relevant_todos += [todo] + tasks = [] + for uuid, task in self.tasks.items(): + if not task.visible or (not task.matches(search)): + continue + tasks += [task] + return j2env.get_template('new_day.html').render( + day=self.selected_day, + prev_date=prev_date_str, + next_date=next_date_str, + tasks=tasks, + relevant_todos=relevant_todos, + search=search) + + +class ParamsParser: + + def __init__(self, parsed_url_query, cookie_db): + self.params = parse_qs(parsed_url_query) + self.cookie_db = cookie_db + + def get(self, key, default=None): + boolean = bool == type(default) + param = self.params.get(key, [default])[0] + if boolean: + param = param != '0' + return param + + def get_cookied(self, key, default=None): + param = self.get(key, default) + if param == '-': + param = None + if key in self.cookie_db.keys(): + del self.cookie_db[key] + if param is None and key in self.cookie_db.keys(): + param = self.cookie_db[key] + if param is not None: + self.cookie_db[key] = param + return param class TodoHandler(PlomHandler): - + + def config_init(self): + return { + 'cookie_name': 'todo_cookie', + 'prefix': '', + 'cookie_path': '/' + } + def app_init(self, handler): default_path = '/todo' - handler.add_route('GET', default_path, self.show_db) - handler.add_route('POST', default_path, self.write_db) - return 'todo', default_path + handler.add_route('GET', default_path, self.show_db) + handler.add_route('POST', default_path, self.write_db) + return 'todo', {'cookie_name': 'todo_cookie', 'prefix': default_path, 'cookie_path': default_path} def do_POST(self): + self.try_do(self.config_init) self.try_do(self.write_db) def write_db(self): from urllib.parse import urlencode - db = TodoDB() + config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init() length = int(self.headers['content-length']) postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1) - - import pprint - pp = pprint.PrettyPrinter(indent=4) - pp.pprint(postvars) - - db.t_filter_and = set() - db.t_filter_not = set() - if 't_filter_and' in postvars.keys(): - for target in postvars['t_filter_and']: - db.t_filter_and.add(target) - if 't_filter_not' in postvars.keys(): - for target in postvars['t_filter_not']: - db.t_filter_not.add(target) - if 't_uuid' in postvars.keys(): - new_postvars_t_uuid = postvars['t_uuid'].copy() - for i, uuid in enumerate(postvars['t_uuid']): - if len(uuid) < 36 and len(postvars['t_title'][i]) > 0: - t = Task() - new_uuid = str(uuid4()) - db.tasks[new_uuid] = t - new_postvars_t_uuid[i] = new_uuid - for key in [k for k in postvars.keys() if not k == 't_uuid']: - if uuid in postvars[key]: - uuid_index = postvars[key].index(uuid) - postvars[key][uuid_index] = new_uuid - postvars['t_uuid'] = new_postvars_t_uuid - for i, uuid in enumerate(postvars['t_uuid']): - if len(uuid) < 36: + parsed_url = urlparse(self.path) + site = path_split(urlparse(self.path).path)[1] + # site = path_split(parsed_url.path)[1] + db = TodoDB(prefix=config['prefix']) + redir_params = [] + # for param_name, filter_db_name in {('t_and', 't_filter_and'), ('t_not', 't_filter_not')}: + # filter_db = getattr(db, filter_db_name) + # if param_name in postvars.keys(): + # for target in postvars[param_name]: + # if len(target) > 0 and not target in filter_db: + # filter_db += [target] + # if len(filter_db) == 0: + # redir_params += [(param_name, '-')] + # redir_params += [(param_name, f) for f in filter_db] + + def collect_checked(prefix, postvars): + tags_checked = [] + for k in postvars.keys(): + if k.startswith(prefix): + tags_checked += [k[len(prefix):]] + return tags_checked + + if 'calendar' == site: + redir_params += [('start', postvars['start'][0] if len(postvars['start'][0]) > 0 else '-')] + redir_params += [('end', postvars['end'][0] if len(postvars['end'][0]) > 0 else '-')] + + elif 'todo' == site: + # task_uuid = postvars['task_uuid'][0] + todo_id = postvars['todo_id'][0] + # date = postvars['date'][0] + old_todo = db.todos[todo_id] + efforts = {} + for i, date in enumerate(postvars['effort_date']): + if '' == date: continue - t = db.tasks[uuid] - t.set_title(postvars['t_title'][i]) - t.tags_from_joined_string(postvars['t_tags'][i]) - t.set_default_weight(float(postvars['t_default_weight'][i])) - if uuid in db.today.todos.keys() and ((not 'do_today' in postvars) or uuid not in postvars['do_today']): - del db.today.todos[uuid] - if 'do_today' in postvars.keys(): - for i, uuid in enumerate(postvars['t_uuid']): - if uuid in postvars['do_today']: - done = 'done' in postvars and uuid in postvars['done'] - day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None - db.today.todos[uuid] = Todo(done, day_weight) - db.today_date = postvars['today_date'][0] - db.today.comment = postvars['comment'][0] - switch_edited_day = None - for date in db.old_days.keys(): - if f'edit_{date}' in postvars.keys(): - switch_edited_day = date - break - if 'archive_today' in postvars.keys() or switch_edited_day: - if db.today_date in db.old_days.keys(): - raise PlomException('cannot use same date twice') - db.old_days[db.today_date] = db.today - if switch_edited_day: - db.reset_today(date) + efforts[date] = postvars['effort'][i] if len(postvars['effort'][i]) > 0 else None + if 'delete_effort' in postvars.keys(): + for date in postvars['delete_effort']: + del efforts[date] + if 'delete' in postvars.keys(): + # old_todo = db.days[date].todos[task_uuid] + if 'done' in postvars or postvars['comment'][0] != '' or len(collect_checked('day_tag_', postvars)) > 0 or postvars['joined_day_tags'][0] != '' or len(efforts) > 0: + raise PlomException('will not remove todo of preserve-worthy values') + db.delete_todo(todo_id) + # db.write() + # self.redirect('new_day') + else: + # redir_params += [('task', task_uuid), ('date', date)] + redir_params += [('id', todo_id)] + # db.update_todo(task_uuid, date, postvars['day_effort'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['joined_day_tags'][0], collect_checked('day_tag_', postvars), postvars['importance'][0]) + # efforts = {} + # for i, date in enumerate(postvars['effort_date']): + # if '' == date: + # continue + # efforts[date] = postvars['effort'][i] if len(postvars['effort'][i]) > 0 else None + if 'delete_effort' in postvars.keys(): + for date in postvars['delete_effort']: + db.delete_effort(old_todo, date) + db.update_todo(id_=todo_id, + efforts=efforts, + done='done' in postvars.keys(), + comment=postvars['comment'][0], + day_tags_joined=postvars['joined_day_tags'][0], + day_tags_checked=collect_checked('day_tag_', postvars), + importance=float(postvars['importance'][0])) + + elif 'task' == site: + id_ = postvars['id'][0] + redir_params += [('id', id_)] + if 'title' in postvars.keys(): + db.update_task(id_, postvars['title'][0], postvars['default_effort'][0], postvars['joined_tags'][0], collect_checked('tag_', postvars), collect_checked('link_', postvars), postvars['comment'][0]) + if 'as_todo' in postvars.keys() and id_ not in db.selected_day.todos.keys(): + db.update_todo_mini(id_, db.selected_date, None, False, 1.0) + elif 'as_todo' not in postvars.keys() and id_ in db.selected_day.todos.keys(): + todo = db.selected_day.todos[id_] + if todo.internals_empty() and (not todo.done) and todo.day_effort is None: + del db.selected_day.todos[id_] + else: + raise PlomException('cannot deselect task as todo of preserve-worthy values') + + elif 'new_day' == site: + redir_params += [('search', postvars['search'][0])] + if 'choose_task' in postvars.keys(): + for i, uuid in enumerate(postvars['choose_task']): + if not uuid in db.selected_day.todos.keys(): + # task = db.tasks[uuid] + db.update_todo_mini(uuid, db.selected_date, None, False, 1.0) + if 'choose_todo' in postvars.keys(): + for i, id_ in enumerate(postvars['choose_todo']): + if not id_ in [todo.id_ for todo in db.selected_day.linked_todos_as_list]: + db.link_day_with_todo(db.selected_date, id_) + + elif 'do_day' == site: + if 'filter' in postvars.keys(): + redir_params += [('hide_done', int('hide_done' in postvars.keys()))] else: - db.reset_today() + db.selected_date = postvars['date'][0] + redir_params += [('date', db.selected_date)] + db.selected_day.comment = postvars['day_comment'][0] + if 'todo_id' in postvars.keys(): + for i, todo_id in enumerate(postvars['todo_id']): + old_todo = None if not todo_id in db.todos.keys() else db.todos[todo_id] + done = ('done' in postvars) and (todo_id in postvars['done']) + day_effort_input = postvars['effort'][i] + day_effort = float(day_effort_input) if len(day_effort_input) > 0 else None + comment = postvars['effort_comment'][i] + importance = float(postvars['importance'][i]) + if old_todo and old_todo.done == done and old_todo.day_effort == day_effort and comment == old_todo.comment and old_todo.importance == importance: + continue + db.update_todo_for_day(todo_id, db.selected_date, day_effort, done, comment, importance) + + elif 'day' == site: + # always store the two hide params in the URL if possible ⦠TODO: find out if really necessary + if 'expect_unchosen_done' in postvars.keys(): + redir_params += [('hide_unchosen', int('hide_unchosen' in postvars.keys()))] + [('hide_done', int('hide_done' in postvars.keys()))] + + if 'date' in postvars.keys(): + db.selected_date = postvars['date'][0] + if 'day_comment' in postvars.keys(): + db.selected_day.comment = postvars['day_comment'][0] + redir_params += [('date', db.selected_date)] + + # handle todo list updates via task UUIDs + if 't_uuid' in postvars.keys(): + for i, uuid in enumerate(postvars['t_uuid']): + task = db.tasks[uuid] + old_todo = None if not uuid in db.selected_day.todos.keys() else db.selected_day.todos[uuid] + selects_as_todo = 'choose' in postvars and uuid in postvars['choose'] + too_much_keepworthy_data = ('done' in postvars and uuid in postvars['done']) or postvars['day_effort'][i] != '' or (old_todo and not old_todo.internals_empty()) + if old_todo and too_much_keepworthy_data and not selects_as_todo: + raise PlomException('cannot deselect task as todo of preserve-worthy values') + elif old_todo and not selects_as_todo: + del db.selected_day.todos[uuid] + elif too_much_keepworthy_data or selects_as_todo: + done = ('done' in postvars) and (uuid in postvars['done']) + day_effort_input = postvars['day_effort'][i] + day_effort = float(day_effort_input) if len(day_effort_input) > 0 else None + importance = float(postvars['importance'][i]) + if old_todo and old_todo.done == done and old_todo.day_effort == day_effort and old_todo.importance == importance: + continue + db.update_todo_mini(uuid, db.selected_date, day_effort, done, importance) + + if 'return_to' in postvars.keys() and len(postvars['return_to'][0]) > 0: + homepage = postvars['return_to'][0] + else: + encoded_params = urlencode(redir_params) + # homepage = f'{parsed_url.path}?{encoded_params}' + homepage = f'{site}?{encoded_params}' db.write() - homepage = self.apps['todo'] if hasattr(self, 'apps') else self.homepage - data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] - encoded_params = urlencode(data) - homepage += '?' + encoded_params self.redirect(homepage) def do_GET(self): + self.try_do(self.config_init) self.try_do(self.show_db) def show_db(self): - from jinja2 import Template - from urllib.parse import urlparse + config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init() + cookie_db = self.get_cookie_db(config['cookie_name']) parsed_url = urlparse(self.path) - params = parse_qs(parsed_url.query) - t_filter_and = set(params.get('t_and', [])) - t_filter_not = set(params.get('t_not', ['deleted'])) - db = TodoDB(t_filter_and, t_filter_not) - for i in range(10): - db.tasks[f'new{i}'] = Task() - for task_uuid, todo in db.today.todos.items(): - todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight - for date, day in db.old_days.items(): - for task_uuid, todo in day.todos.items(): - todo.title = db.tasks[task_uuid].title - todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight - page = Template(tmpl).render(db=db) + site = path_split(parsed_url.path)[1] + # params = parse_qs(parsed_url.query) + params = ParamsParser(parsed_url.query, cookie_db) + + # def get_param(param_name, boolean=False, chained=False, none_as_empty_string=False): + # if chained: + # param = params.get(param_name, None) + # elif none_as_empty_string: + # param = params.get(param_name, [''])[0] + # else: + # param = params.get(param_name, [None])[0] + # if (not chained and param == '-') or (chained and param == ['-']): + # param = None + # if param_name in cookie_db.keys(): + # del cookie_db[param_name] + # if param is None and param_name in cookie_db.keys(): + # param = cookie_db[param_name] + # if param is not None: + # if boolean: + # param = param != '0' + # cookie_db[param_name] = str(int(param)) + # else: + # cookie_db[param_name] = param + # elif param is boolean: + # param = False + # return param + + selected_date = t_filter_and = t_filter_not = None + hide_unchosen = hide_done = False + # return_to = params.get('return_to', [''])[0] + return_to = params.get('return_to', '') + if site in {'day', 'do_day', 'new_day'}: + selected_date = params.get_cookied('date') + # if site in {'day','tasks', 'task', 'new_day'}: + # t_filter_and = get_param('t_and', chained=True) + # t_filter_not = get_param('t_not', chained=True) + if site in {'day', 'do_day'}: + # hide_unchosen = get_param('hide_unchosen', boolean=True) + hide_done = params.get('hide_done', False) + db = TodoDB(config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done) + if 'day' == site: + pass + elif 'do_day' == site: + sort_order = params.get_cookied('sort') + page = db.show_do_day(sort_order) + elif site == 'todo': + todo_id = params.get('id') + page = db.show_todo(todo_id, return_to) + # todo_id = params.get('id') + # if todo_id: + # todo_date, task_uuid = todo_id.split('_') + # else: + # todo_date = params.get('date') + # task_uuid = params.get('task') + # page = db.show_todo(task_uuid, todo_date, return_to) + elif 'task' == site: + id_ = params.get('id') + page = db.show_task(id_, return_to) + elif 'tasks' == site: + expand_uuid = params.get('expand_uuid') + page = db.show_tasks(expand_uuid) + elif 'add_task' == site: + page = db.show_task(None) + elif 'new_day' == site: + search = params.get('search', '') + page = db.new_day(search) + elif 'unset_cookie' == site: + page = 'no cookie to unset.' + if len(cookie_db) > 0: + self.unset_cookie(config['cookie_name'], config['cookie_path']) + page = 'cookie unset!' + else: + start_date = params.get_cookied('start') + end_date = params.get_cookied('end') + page = db.show_calendar(start_date, end_date) + if 'unset_cookie' != site: + self.set_cookie(config['cookie_name'], config['cookie_path'], cookie_db) self.send_HTML(page) -if __name__ == "__main__": +if __name__ == "__main__": run_server(server_port, TodoHandler)