X-Git-Url: https://plomlompom.com/repos/new_day?a=blobdiff_plain;f=todo.py;h=c3551a44aefb9040cf406cf133628c08a7c60241;hb=2ad9f7785539c0cd9f119d1f22b8057fab348114;hp=8c7029cab8eda5683b668857a220d7faa283b4fe;hpb=3faab835bd9d842cc0a529ba33007b3f85839e12;p=misc diff --git a/todo.py b/todo.py index 8c7029c..c3551a4 100644 --- a/todo.py +++ b/todo.py @@ -1,325 +1,1067 @@ -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 +DATE_FORMAT = '%Y-%m-%d' +j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates')) -tmpl = """ - -
- -""" - -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() - self.visible = True - - def _set_with_history(self, history, value): - keys = sorted(history.keys()) - if len(history) == 0 or value != history[keys[-1]]: - history[str(datetime.now())[:19]] = value - - def _last_of_history(self, history, default): - keys = sorted(history.keys()) - 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 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) - @property - def tags_joined(self): - return ';'.join(sorted(list(self.tags))) +def today_date(with_time=False): + length = 19 if with_time else 10 + return str(datetime.now())[:length] - def set_default_weight(self, default_weight): - self._set_with_history(self.default_weight_history, default_weight) - @property - def default_weight(self): - return self._last_of_history(self.default_weight_history, 1) - def set_title(self, title): - self._set_with_history(self.title_history, title) +class AttributeWithHistory: - @property - def title(self): - return self._last_of_history(self.title_history, '') + def __init__(self, default_if_empty, history=None, then_date='2000-01-01', set_check=None): + self.default = default_if_empty + self.then_date = then_date + self.history = history if history else {} + self.set_check = set_check + + def set(self, value): + print("DEBUG set", value, "HAS SET CHECK?", self.set_check) + if self.set_check: + print("DEBUG set CALLED SET CHECK") + self.set_check(value) + keys = sorted(self.history.keys()) + if len(self.history) == 0 or value != self.history[keys[-1]]: + self.history[today_date(with_time=True)] = value - 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(): + def at(self, queried_date): + if 0 == len(self.history): + return self.default + ret = self.history[sorted(self.history.keys())[0]] + for date_key, item in self.history.items(): if date_key > f'{queried_date} 23:59:59': break - ret = title + ret = item return ret - def set_tags(self, tags): - self._set_with_history(self.tags_history, set(tags)) + @property + def now(self): + keys = sorted(self.history.keys()) + return self.default if 0 == len(self.history) else self.history[keys[-1]] @property - def tags(self): - return self._last_of_history(self.tags_history, set()) + def then(self): + return self.at(self.then_date) + + + +class TaskLike: + + def __init__(self, db, id_, comment): + self.db = db + self.id_ = id_ + self.comment = comment + self.dependers = [] + + @property + def visible(self): + visible_by_and = 0 == len([tag for tag in self.db.tag_filter_and + if not tag in self.tags]) + visible_by_not = 0 == len([tag for tag in self.db.tag_filter_not + if tag in self.tags]) + return visible_by_and and visible_by_not + + @property + def deps_depth(self): + if len(self.deps) == 0: + return 0 + return 1 + max([d.deps_depth for d in self.deps]) + + @property + def deps_chain(self): + all_deps = set() + def add_deps(todo, all_deps): + for dep in todo.deps: + all_deps.add(dep) + add_deps(dep, all_deps) + add_deps(self, all_deps) + chain = list(all_deps) + chain.sort(key=lambda t: t.deps_depth) + return chain + + + +class Task(TaskLike): + + def __init__(self, + db, + id_, + title_history=None, + tags_history=None, + default_effort_history=None, + dep_ids_history=None, + comment=''): + super().__init__(db, id_, comment) + self.title = AttributeWithHistory('', title_history, self.db.selected_date) + self.tags = AttributeWithHistory(set(), tags_history, self.db.selected_date) + self.default_effort = AttributeWithHistory(0.0, default_effort_history, self.db.selected_date) + self.dep_ids = AttributeWithHistory(set(), dep_ids_history, self.db.selected_date, set_check=self.dep_loop_checker()) + + @classmethod + 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['deps_history'].items()}, + d['comment']) + return t 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} + '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()}, + 'deps_history': {k: list(v) for k, v in self.dep_ids.history.items()}, + 'comment': self.comment, + } + + @property + def deps(self): + deps = [] + for id_ in self.dep_ids.now: + if len(id_) == 0: + continue + elif id_ not in self.db.tasks.keys(): + raise PlomException(f'dep referenced on Task {self.id_} not found: {id_}') + deps += [self.db.tasks[id_]] + return deps + + @property + def deps_weight(self): + def count_weight(task): + sub_count = 1 + for dep in task.deps: + sub_count += count_weight(dep) + return sub_count + return count_weight(self) + + def dep_loop_checker(self): + def f(dep_ids_now): + loop_msg = "can't set dep, would create loop" + for id_ in dep_ids_now: + if id_ == self.id_: + raise PlomException(loop_msg) + elif id_ in self.db.tasks.keys(): + dep = self.db.tasks[id_] + f(dep.dep_ids.now) + return f + + def matches(self, search): + if search is None: + return False + else: + return search in self.title.now or search in self.comment or search in '$'.join(self.tags.now) + class Day: - def __init__(self, todos, comment=''): - self.todos = todos + def __init__(self, db, date, comment=''): + self.date = date + self.db = db self.comment = comment + self.linked_todos_as_list = [] @classmethod - def from_dict(cls, d): - todos = {} + def from_dict(cls, db, d, date=None): 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) + return day + + def to_dict(self): + d = {'comment': self.comment} + return d @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]: - 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() + + def sorted_todos(self, done, is_tree_shaped, sort_order, legal_keys): + todos = [t for t in self.linked_todos_as_list if t.visible and t.done == done] + reverse = False + sort_column = sort_order[:] + if sort_order and '-' == sort_order[0]: + reverse = True + sort_column = sort_order[1:] + if sort_column in legal_keys: + todos.sort(key=lambda t: getattr(t, sort_column)) + if reverse: + todos.reverse() + if is_tree_shaped: + def walk_tree(todo, sorted_todos): + todo.deps = [t for t in sorted_todos if t in todo.deps] + for dep in [t for t in sorted_todos if t in todo.deps]: + walk_tree(dep, sorted_todos) + if done: + trunk = [t for t in todos if len([td for td in t.dependers if td.done]) == 0] + else: + trunk = [t for t in todos if len(t.dependers) == 0] + for node in trunk: + walk_tree(node, todos) + todos = trunk + return todos -class Todo: - def __init__(self, done=False, weight=None): - self.done = done - self.weight = weight +class Todo(TaskLike): + + def __init__(self, + db, + id_, + task, + done=False, + comment='', + day_tags=None, + importance=1.0, + efforts=None, + dep_ids=None): + super().__init__(db, id_, comment) + self.task = task + self._done = done + self.efforts = efforts if efforts else {} + self.day_tags = day_tags if day_tags else set() + self.importance = importance + self._dep_ids = dep_ids if dep_ids else [] + self.already_listed = False + self.been_observed = False @classmethod - def from_dict(cls, d): - return cls(d['done'], d['weight']) + def from_dict(cls, db, d, id_): + todo = cls( + db, + id_, + db.tasks[d['task']], + d['done'], + d['comment'], + set(d['day_tags']), + d['importance'], + d['efforts'], + d['deps']) + return todo def to_dict(self): - return {'done': self.done, 'weight': self.weight} + return { + 'task': self.task.id_, + 'done': self.done, + 'comment': self.comment, + 'day_tags': list(self.day_tags), + 'importance': self.importance, + 'efforts': self.efforts, + 'deps': self._dep_ids} + + @property + def title(self): + return self.task.title.at(self.db.selected_date) + + @property + def dated_title(self): + return f'{self.earliest_date}:{self.title}' + + @property + def deps(self): + return [self.db.todos[id_] for id_ in self._dep_ids] + + @deps.setter + def deps(self, deps): + self._dep_ids = [dep.id_ for dep in deps] + def f(deps): + loop_msg = "can't set dep, would create loop" + for dep in deps: + if dep == self: + raise PlomException(loop_msg) + else: + f(dep.deps) + f(self.deps) + + @property + def default_effort(self): + return self.task.default_effort.at(self.earliest_date) + + @property + def done(self): + return self.deps_done and self._done + + @done.setter + def done(self, doneness): + self._done = doneness + + @property + def deps_done(self): + if len(self.deps) > 0: + for dep in self.deps: + if not dep.done: + return False + return True + + @property + def dep_efforts(self): + dep_efforts = 0 + if self.deps: + for dep in self.deps: + dep_efforts += dep.all_days_effort + dep_efforts += dep.dep_efforts + return dep_efforts + + def depender_path(self, dep): + if self.dependers: + return f'Y{depender.depender_path()}:{self.title}Y' + else: + return f'X{self.title}X' + + @property + def depender_paths(self): + paths = [] + for depender in self.dependers: + if len(depender.depender_paths) == 0: + paths += [[depender]] + else: + for path in depender.depender_paths: + paths += [path + [depender]] + return paths + + @property + def shortened_depender_paths(self): + new_paths = [] + for path in self.depender_paths: + new_path = [] + for i, step in enumerate(path): + next_step = None if len(path) <= i+1 else path[i+1] + for distinct_path in new_paths: + if len(distinct_path) >= i+2 and distinct_path[i+1] == next_step: + step = None + new_path += [step] + new_paths += [new_path] + return new_paths + + @property + def all_days_effort(self): + total = 0 + for effort in self.efforts.values(): + total += effort if effort else 0 + if self.done: + total = max(total, self.task.default_effort.at(self.latest_date)) + return total + + 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 + + def is_effort_removable(self, date): + if not date in self.efforts.keys(): + return False + if self.efforts[date]: + return False + if self.done and date == self.latest_date: + return False + return True + + @property + def tags(self): + return self.day_tags | self.task.tags.now + + @property + def day_effort(self): + return self.efforts[self.db.selected_date] + + @property + def effort_at_selected_date(self): + if self.db.selected_date in self.efforts.keys() and self.day_effort is not None: + return self.day_effort + else: + return self.task.default_effort.then + + @property + def day(self): + return self.db.days[self.earliest_date] + + @property + def sorted_effort_dates(self): + dates = list(self.efforts.keys()) + dates.sort() + return dates + + @property + def earliest_date(self): + return self.sorted_effort_dates[0] + + @property + def latest_date(self): + return self.sorted_effort_dates[-1] + + @property + def has_dependers(self): + return len(self.dependers) > 0 + + @property + def has_deps(self): + return len(self.deps) > 0 + + @property + def sort_done(self): + return self.day_effort if self.day_effort else 0 + + @property + def family_effort(self): + return self.effort_at_selected_date + self.dep_efforts + + def observe(self): + self.been_observed = True + return '' + 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, + selected_date=None, + tag_filter_and = None, + tag_filter_not = None): + self.selected_date = selected_date if selected_date else today_date() + self.tag_filter_and = tag_filter_and if tag_filter_and else [] + self.tag_filter_not = tag_filter_not if tag_filter_not else [] + + self.days = {} self.tasks = {} - self.reset_today() - self.t_tags = set() + self.t_tags = set() + self.todos = {} super().__init__(db_path) + # savefile I/O + 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 tag in t.tags: + + for id_, t_dict in d['tasks'].items(): + t = self.add_task(id_=id_, dict_source=t_dict) + for tag in t.tags.now: self.t_tags.add(tag) - for date, day_dict in d['old_days'].items(): - self.old_days[date] = Day.from_dict(day_dict) + for task in self.tasks.values(): + for dep in task.deps: + dep.dependers += [task] + + for id_, todo_dict in d['todos'].items(): + todo = self.add_todo(todo_dict, id_, link_into_day=False) + for tag in todo.day_tags: + self.t_tags.add(tag) + for todo in self.todos.values(): + for dep in todo.deps: + dep.dependers += [todo] + + for date, day_dict in d['days'].items(): + self.add_day(dict_source=day_dict, date=date) + for todo in self.todos.values(): + for date in todo.efforts.keys(): + if not date in self.days.keys(): + self.add_day(date) + self.days[date].linked_todos_as_list += [todo] + + # self.set_visibilities() 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 id_, todo in self.todos.items(): + d['todos'][id_] = todo.to_dict() return d 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 save_today(self): - if self.today_date in self.old_days.keys(): - raise PlomException('cannot use same date twice') - for task_uuid, todo in [(task_uuid, todo) for task_uuid, todo in self.today.todos.items() - if not todo.weight]: - todo.weight = self.tasks[task_uuid].default_weight - self.old_days[self.today_date] = self.today - - def reset_today(self, date=None): - if date: - self.today_date = date - self.today = self.old_days[date] - del self.old_days[date] + # properties + + @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) + return self.days[self.selected_date] + + # table manipulations + + 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 add_task(self, id_=None, dict_source=None): + 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 + return t + + def update_task(self, id_, title, default_effort, tags, dep_ids, comment): + task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_) + task.title.set(title) + task.default_effort.set(default_effort) + task.tags.set(tags) + task.dep_ids.set(dep_ids) + task.comment = comment + return task + + def add_todo(self, todo_dict=None, id_=None, task=None, efforts=None, link_into_day=True, adopt_if_possible=True): + id_ = id_ if id_ else str(uuid4()) + if todo_dict: + todo = Todo.from_dict(self, todo_dict, id_) + elif task and efforts: + todo = Todo(self, id_, task, efforts=efforts) + deps = [] + for dep_task in task.deps: + # if Todo expects dependencies, adopt any compatibles found in DB.selected_date + # before creating new depended Todos + dep_todo = None + if adopt_if_possible and list(efforts.keys())[0] == self.selected_date: + adoptable_todos = [t for t in self.selected_day.linked_todos_as_list + if t.task.id_ == dep_task.id_] + if len(adoptable_todos) > 0: + dep_todo = adoptable_todos[0] + if not dep_todo: + dep_todo = self.add_todo(task=dep_task, efforts=efforts, + link_into_day=link_into_day, + adopt_if_possible=adopt_if_possible) + deps += [dep_todo] + # todo.dep_ids = [dep.id_ for dep in deps] + todo.deps = deps + self.todos[id_] = todo + if link_into_day: + self.selected_day.linked_todos_as_list += [todo] + return todo + + def _update_todo_shared(self, id_, done, comment, importance): + todo = self.todos[id_] + todo.done = done + todo.comment = comment + todo.importance = importance + return todo + + def update_todo_for_day(self, id_, date, effort, done, comment, importance): + todo = self._update_todo_shared(id_, done, comment, importance) + todo.efforts[date] = effort + + def update_todo(self, id_, efforts, done, comment, tags, importance, deps): + todo = self._update_todo_shared(id_, done, comment, importance) + if len(efforts) == 0 and not todo.deps: + raise PlomException('todo must have at least one effort!') + todo.deps = deps + todo.efforts = efforts + for date in todo.efforts.keys(): + 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.day_tags = tags + + def delete_todo(self, id_): + todo = self.todos[id_] + dates_to_delete = [] + for date in todo.efforts.keys(): + dates_to_delete += [date] + for date in dates_to_delete: + self.delete_effort(todo, date, force=True) + for depender in todo.dependers: + depender._dep_ids.remove(todo.id_) + del self.todos[id_] + + def delete_task(self, id_): + del self.tasks[id_] + + def delete_effort(self, todo, date, force=False): + if (not force) and len(todo.efforts) == 1: + raise PlomException('todo must retain at least one effort!') + self.days[date].linked_todos_as_list.remove(todo) + del todo.efforts[date] + + # views + + def show_message(self, message): + return j2env.get_template('message.html').render(message=message) + + def show_calendar(self, start_date_str, end_date_str): + self.tag_filter_and = ['calendar'] + self.tag_filter_not = ['deleted'] + + todays_date_obj = datetime.strptime(today_date(), DATE_FORMAT) + yesterdays_date_obj = todays_date_obj - timedelta(1) + def get_day_limit_obj(index, day_limit_string): + date_obj = datetime.strptime(sorted(self.days.keys())[index], DATE_FORMAT) + if day_limit_string and len(day_limit_string) > 0: + if day_limit_string in {'today', 'yesterday'}: + date_obj = todays_date_obj if day_limit_string == 'today' else yesterdays_date_obj + else: + date_obj = datetime.strptime(day_limit_string, DATE_FORMAT) + return date_obj + start_date_obj = get_day_limit_obj(0, start_date_str) + end_date_obj = get_day_limit_obj(-1, end_date_str) + + days_to_show = {} + for n in range(int((end_date_obj - start_date_obj).days) + 1): + date_obj = start_date_obj + timedelta(n) + date_str = date_obj.strftime(DATE_FORMAT) + if date_str not in self.days.keys(): + days_to_show[date_str] = self.add_day(date_str) + else: + days_to_show[date_str] = self.days[date_str] + days_to_show[date_str].month_title = date_obj.strftime('%B') if date_obj.day == 1 else None + days_to_show[date_str].weekday = datetime.strptime(date_str, DATE_FORMAT).strftime('%A')[:2] + + return j2env.get_template('calendar.html').render( + selected_date=self.selected_date, + days=days_to_show, + start_date=start_date_str, + end_date=end_date_str) + + def show_day_todos(self, undone_sort_order=None, done_sort_order=None, is_tree_shaped=False): + legal_undone_sort_keys = {'title', 'sort_done', 'default_effort', 'importance'} + legal_done_sort_keys = {'title', 'effort_at_selected_date', 'family_effort'} + + 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) + + adoptable_past_todos = [] + for todo in [t for t in self.todos.values() + if t.visible + and (not t.done) + and t.earliest_date < self.selected_date]: + adoptable_past_todos += [todo] + undone_todos = self.selected_day.sorted_todos(False, is_tree_shaped, undone_sort_order, + legal_undone_sort_keys) + done_todos = self.selected_day.sorted_todos(True, is_tree_shaped, done_sort_order, + legal_done_sort_keys) + + return j2env.get_template('day_todos.html').render( + day=self.selected_day, + tags=self.t_tags, + filter_and=self.tag_filter_and, + filter_not=self.tag_filter_not, + prev_date=prev_date_str, + adoptable_past_todos=adoptable_past_todos, + next_date=next_date_str, + all_tasks=[t for t in self.tasks.values()], + undone_todos=undone_todos, + done_todos=done_todos, + is_tree_shaped=is_tree_shaped, + undone_sort=undone_sort_order, + done_sort=done_sort_order) + + def show_todo(self, id_): + todo = self.todos[id_] + filtered_tasks = [t for t in self.tasks.values() + if t != todo.task] + filtered_todos = [t for t in self.todos.values() + if t != todo + and t not in todo.deps] + + legal_dates = list(todo.efforts.keys()) + date_filtered_todos = [] + for date in legal_dates: + for filtered_todo in filtered_todos: + if filtered_todo in date_filtered_todos: + continue + if date in filtered_todo.efforts.keys(): + date_filtered_todos += [filtered_todo] + + dep_slots = [] + for dep in todo.task.deps: + dep_slots += [{'task': dep, + 'todos': [t for t in todo.deps if t.task == dep]}] + + suggested_todos = {} + for dep in todo.task.deps: + suggested_todos[dep.id_] = [t for t in date_filtered_todos if t.task.id_ == dep.id_] + additional_deps = [t for t in todo.deps if not t.task in todo.task.deps] + + return j2env.get_template('todo.html').render( + tags=self.t_tags, + todo=todo, + filtered_todos=date_filtered_todos, + filtered_tasks=filtered_tasks, + dep_slots=dep_slots, + suggested_todos=suggested_todos, + additional_deps=additional_deps, + dep_todos=todo.deps) + + def show_task(self, id_): + task = self.tasks[id_] if id_ else self.add_task() + if not id_: + task.default_effort.set(1.0) + filtered_tasks = [t for t in self.tasks.values() + if t != task + and (t not in task.deps)] + + return j2env.get_template('task.html').render( + selected_date=self.selected_date, + tags=self.t_tags, + filtered_tasks=filtered_tasks, + task=task) + + def show_tasks(self, search, sort_order=None): + filtered_tasks = [] + for task in [t for t in self.tasks.values() if (not search) or t.matches(search)]: + filtered_tasks += [task] + reverse = False + sort_column = sort_order + if sort_order and '-' == sort_order[0]: + reverse = True + sort_column = sort_order[1:] + if sort_column == 'title': + filtered_tasks.sort(key=lambda t: t.title.now) + elif sort_column == 'default_effort': + filtered_tasks.sort(key=lambda t: t.default_effort.now) + elif sort_column == 'weight': + filtered_tasks.sort(key=lambda t: t.deps_weight) + if reverse: + filtered_tasks.reverse() + return j2env.get_template('tasks.html').render( + sort=sort_order, + tasks=filtered_tasks, + tags=self.t_tags, + filter_and=self.tag_filter_and, + filter_not=self.tag_filter_not, + 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, as_bool=False): + # boolean = bool == type(default) + param = self.params.get(key, [default])[0] + if as_bool: + if param == '0': + param = False + elif param is not None: + param = True + return param + + def cookie_key_from_params_key(self, prefix, key): + return f'{prefix}:{key}' if prefix else key + + def get_cookied(self, key, default=None, prefix=None, as_bool=False): + cookie_key = self.cookie_key_from_params_key(prefix, key) + param = self.get(key, default, as_bool) + if param == '-': + param = None + if cookie_key in self.cookie_db.keys(): + del self.cookie_db[cookie_key] + if param is None and cookie_key in self.cookie_db.keys(): + param = self.cookie_db[cookie_key] + if param is not None: + self.cookie_db[cookie_key] = param + return param + + def get_cookied_chain(self, key, default=None, prefix=None): + cookie_key = self.cookie_key_from_params_key(prefix, key) + params = self.params.get(key, default) + if params == ['-']: + params = None + if cookie_key in self.cookie_db.keys(): + del self.cookie_db[cookie_key] + if params is None and cookie_key in self.cookie_db.keys(): + params = self.cookie_db[cookie_key] + if params is not None: + self.cookie_db[cookie_key] = params + return params + + + +class PostvarsParser: + + def __init__(self, postvars): + self.postvars = postvars + + def has(self, key): + return key in self.postvars.keys() + + def get(self, key, on_empty=None, float_if_possible=False): + return self.get_at_index(key, 0, on_empty, float_if_possible) + + def get_at_index(self, key, i, on_empty=None, float_if_possible=False): + if self.has(key) and len(self.postvars[key][i]) > 0: + val = self.postvars[key][i] else: - self.today_date = str(datetime.now())[:10] - self.today = Day({}) + val = on_empty + if float_if_possible and val is not None: + return float(val) + else: + return val + + def get_all(self, key, on_empty=None): + if self.has(key) and len(self.postvars[key]) > 0: + return [v for v in self.postvars[key] if len(v) > 0] + return on_empty + + def set(self, key, value): + self.postvars[key] = [value] class TodoHandler(PlomHandler): - + + def config_init(self): + return { + 'cookie_name': 'todo_cookie', + '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', 'cookie_path': default_path} def do_POST(self): 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() + parsed_url = urlparse(self.path) + site = path_split(parsed_url.path)[1] 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: + postvars = PostvarsParser(parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)) + + db = TodoDB() + redir_params = [] + # if we do encounter a filter post, we repost it (and if empty, the emptying command '-') + for param_name, filter_db_name in {('and_tag', 'tag_filter_and'), ('not_tag', 'tag_filter_not')}: + filter_db = getattr(db, filter_db_name) + if postvars.has(param_name): + for target in postvars.get_all(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] + if site in {'calendar', 'todo'}: + redir_params += [('end', postvars.get('end', '-'))] + redir_params += [('start', postvars.get('start', '-'))] + # if site in {'tasks', 'pick_tasks'}: + # redir_params += [('search', postvars.get('search', ''))] + if postvars.has('filter'): + postvars.set('return_to', '') + + if 'tasks' == site: + redir_params += [('search', postvars.get('search', ''))] + + elif 'todo' == site: + todo_id = postvars.get('todo_id') + redir_params += [('id', todo_id)] + old_todo = db.todos[todo_id] if todo_id in db.todos.keys() else None + efforts = {} + latest_date = db.selected_date + for i, date in enumerate(postvars.get_all('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'] - weight = float(postvars['weight'][i]) if postvars['weight'][i] else None - db.today.todos[uuid] = Todo(done, 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: - db.save_today() - if switch_edited_day: - db.reset_today(date) - else: - db.reset_today() + try: + datetime.strptime(date, DATE_FORMAT) + except ValueError: + raise PlomException(f'bad date string') + latest_date = date + efforts[date] = None + if not (old_todo and old_todo.deps): + efforts[date] = postvars.get_at_index('effort', i, on_empty=None, + float_if_possible=True) + if postvars.has('delete'): + has_day_effort = len([e for e in efforts.values() if e is not None]) > 0 + if postvars.has('done')\ + or postvars.get('comment')\ + or postvars.get_all('tag', [])\ + or has_day_effort: + raise PlomException('will not remove todo of preserve-worthy values') + db.delete_todo(todo_id) + postvars.set('return_to', 'calendar') + elif postvars.has('update'): + if postvars.has('delete_effort'): + for date in postvars.get_all('delete_effort'): + db.delete_effort(old_todo, date) + del efforts[date] + deps = [db.todos[id_] for id_ in postvars.get_all('adopt_dep', []) + if id_ in db.todos.keys()] + for dep in deps: + if not todo_id in [t.id_ for t in dep.dependers]: + dep.dependers += [db.todos[todo_id]] + tasks_to_birth = [db.tasks[id_] for id_ in postvars.get_all('birth_dep', [])] + for task in tasks_to_birth: + deps += [db.add_todo(task=task, efforts={latest_date: None})] + db.update_todo(id_=todo_id, + efforts=efforts, + done=postvars.has('done'), + comment=postvars.get('comment', ''), + tags=postvars.get_all('tag', []), + importance=float(postvars.get('importance')), + deps=deps) + + elif 'task' == site: + task_id = postvars.get('task_id') + if postvars.has('delete') and task_id in db.tasks.keys(): + if [t for t in db.todos.values() if task_id == t.task.id_]: + raise PlomException('will not remove Task describing existing Todos') + if postvars.get('title', '')\ + or postvars.get_all('tag', [])\ + or postvars.get_all('dep', [])\ + or postvars.get('comment', ''): + raise PlomException('will not remove Task of preserve-worthy values') + db.delete_task(task_id) + elif postvars.has('update'): + dep_ids = postvars.get_all('dep', []) + for id_ in [id_ for id_ in dep_ids if not id_ in db.tasks.keys()]: + raise PlomException('submitted illegal dep ID') + task = db.update_task( + id_=task_id, + title=postvars.get('title', ''), + default_effort=postvars.get('default_effort', float_if_possible=True), + tags=postvars.get_all('tag', []), + dep_ids=dep_ids, + comment=postvars.get('comment', '')) + if postvars.has('add_as_todo'): + db.add_todo(task=task, efforts={postvars.get('selected_date'): None}) + redir_params += [('id', task_id)] + + elif 'day_todos' == site: + if postvars.has('update'): + db.selected_date = postvars.get('date') + redir_params += [('date', db.selected_date)] + db.selected_day.comment = postvars.get('day_comment', '') + task_id = postvars.get('choose_task', None) + if task_id: + if task_id not in db.tasks.keys(): + raise PlomException('illegal task ID entered') + db.add_todo(task=db.tasks[task_id], efforts={db.selected_date: None}, + adopt_if_possible=(not postvars.has('dont_adopt'))) + for id_ in postvars.get_all('choose_todo', []): + db.todos[id_].efforts[db.selected_date] = None + for i, todo_id in enumerate(postvars.get_all('todo_id', [])): + old_todo = db.todos[todo_id] + done = todo_id in postvars.get_all('done', []) + day_effort_input = postvars.get_at_index('effort', i, '') + day_effort = float(day_effort_input) if len(day_effort_input) > 0 else None + comment = postvars.get_at_index('effort_comment', i, '') + if (day_effort is not None) and (not done) and day_effort < 0 and 0 == len(comment): + if len(old_todo.efforts) > 1: + db.delete_effort(old_todo, db.selected_date) + else: + db.delete_todo(todo_id) + continue + importance = float(postvars.get_at_index('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) + + homepage = postvars.get('return_to') + if not homepage: + encoded_params = urlencode(redir_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.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() 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 date, day in db.old_days.items(): - for task_uuid, todo in day.todos.items(): - todo.title = db.tasks[task_uuid].title_at(date) - page = Template(tmpl).render(db=db) + site = path_split(parsed_url.path)[1] + cookie_db = self.get_cookie_db(config['cookie_name']) + params = ParamsParser(parsed_url.query, cookie_db) + + selected_date = tag_filter_and = tag_filter_not = None + if site in {'day_todos', 'calendar', 'task'}: + selected_date = params.get_cookied('date') + if site in {'day_todos', 'tasks'}: + tag_filter_and = params.get_cookied_chain('and_tag', prefix=site) + tag_filter_not = params.get_cookied_chain('not_tag', prefix=site) + db = TodoDB(selected_date, tag_filter_and, tag_filter_not) + if site in {'todo', 'task'}: + id_ = params.get('id') + if 'reset_cookie' == site: + cookie_db = { # sensible defaults + params.cookie_key_from_params_key('day_todos', 'tree'): True, + params.cookie_key_from_params_key('todo', 'and_tag'): ['default'], + params.cookie_key_from_params_key('todo', 'not_tag'): ['ignore'], + params.cookie_key_from_params_key('todo', 'start'): 'yesterday', + params.cookie_key_from_params_key('todo', 'end'): 'today'} + page = db.show_message('cookie unset!') + elif 'day_todos' == site: + is_tree_shaped = params.get_cookied('tree', prefix=site, as_bool=True) + undone_sort_order = params.get_cookied('undone_sort', prefix=site) + done_sort_order = params.get_cookied('done_sort', prefix=site) + page = db.show_day_todos(undone_sort_order, done_sort_order, is_tree_shaped) + elif site == 'todo': + page = db.show_todo(id_) + elif 'task' == site: + page = db.show_task(id_) + elif 'tasks' == site: + sort_order = params.get_cookied('sort', prefix=site) + search = params.get('search', '') + page = db.show_tasks(search, sort_order) + elif 'add_task' == site: + page = db.show_task(None) + else: # 'calendar' == site + start_date = params.get_cookied('start', prefix=site) + end_date = params.get_cookied('end', prefix=site) + page = db.show_calendar(start_date, end_date) + + 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)