X-Git-Url: https://plomlompom.com/repos/do_day?a=blobdiff_plain;ds=sidebyside;f=todo.py;h=8f73e86b973ea1d92e9f5cd4a08b2d34212bc499;hb=HEAD;hp=8c7029cab8eda5683b668857a220d7faa283b4fe;hpb=3faab835bd9d842cc0a529ba33007b3f85839e12;p=misc diff --git a/todo.py b/todo.py index 8c7029c..8f73e86 100644 --- a/todo.py +++ b/todo.py @@ -1,325 +1,1219 @@ -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) +def today_date(with_time=False): + length = 19 if with_time else 10 + return str(datetime.now())[:length] - @property - def tags_joined(self): - return ';'.join(sorted(list(self.tags))) - 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) +class AttributeWithHistory: - def set_title(self, title): - self._set_with_history(self.title_history, title) + def __init__(self, parent, name, default_if_empty, history=None, then_date='2000-01-01'): + self.parent = parent + self.name = name + self.default = default_if_empty + self.then_date = then_date + self.history = history if history else {} - @property - def title(self): - return self._last_of_history(self.title_history, '') + def set(self, 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(): - if date_key > f'{queried_date} 23:59:59': + def at(self, queried_date): + end_of_queried_day = f'{queried_date} 23:59:59' + sorted_dates = sorted(self.history.keys()) + if self.parent.forked_task and (0 == len(sorted_dates) or sorted_dates[0] > end_of_queried_day): + return getattr(self.parent.forked_task, self.name).at(queried_date) + elif 0 == len(sorted_dates): + return self.default + ret = self.history[sorted_dates[0]] + for date_key, item in self.history.items(): + if date_key > end_of_queried_day: 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()) + if 0 == len(self.history): + if self.parent.forked_task: + return getattr(self.parent.forked_task, self.name).now + return self.default + return 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 + + @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(node, all_deps): + for dep in node.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 + + def loop_check(self): + loop_msg = "can't set dep, would create loop" + def f(node, id_): + for dep in node.deps: + if id_ == dep.id_: + raise PlomException(loop_msg) + f(dep, id_) + f(self, self.id_) + + + + +class Task(TaskLike): + + def __init__(self, + db, + id_, + title_history=None, + tags_history=None, + default_effort_history=None, + dep_ids_history=None, + adoptivity_history=None, + comment='', + forks_id=None): + super().__init__(db, id_, comment) + self.forks_id = forks_id + self.title = AttributeWithHistory(self, 'title', '', title_history, self.db.selected_date) + self.tags = AttributeWithHistory(self, 'tags', set(), tags_history, self.db.selected_date) + self.default_effort = AttributeWithHistory(self, 'default_effort', 0.0, default_effort_history, self.db.selected_date) + self.dep_ids = AttributeWithHistory(self, 'dep_ids', set(), dep_ids_history, self.db.selected_date) + self.fences_adoptions = AttributeWithHistory(self, 'fences_adoptions', False, adoptivity_history, self.db.selected_date) + + @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['adoptivity_history'], + comment=d['comment'], + forks_id=d['forks']) + 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()}, + 'adoptivity_history': self.fences_adoptions.history, + 'comment': self.comment, + 'forks': self.forks_id, + } + + @property + def forked_task(self): + return self.db.tasks[self.forks_id] if self.forks_id else None + + @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) + + @property + def dependers(self): + return [t for t in self.db.tasks.values() if self in t.deps] + + 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) + + @property + def latest_effort_date(self): + todos = [t for t in self.db.todos.values() if t.task.id_ == self.id_] + todos.sort(key=lambda t: t.latest_date) + if len(todos) > 0: + return todos[-1].latest_date + else: + return '' + 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] + if sort_order: + 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: + @property + def visible_in_export(self): + return len(self.comment) + len([t for t in self.linked_todos_as_list if t.visible]) > 0 + + + +class Todo(TaskLike): - def __init__(self, done=False, weight=None): - self.done = done - self.weight = weight + 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 + for k in efforts.keys(): + try: + datetime.strptime(k, DATE_FORMAT) + except ValueError: + raise PlomException(f'Todo creation: bad date string: {k}') + 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 set() + 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'], + set(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': list(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} + + @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 dependers(self): + return [t for t in self.db.todos.values() if self.id_ in t.dep_ids] + + @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 closest_adoptable(self, task_id): + print("DEBUG closest_adoptable", self.id_) + ranked_adoptables = {self.id_: 0} + def collect_downwards(node, ranked_adoptables, n_steps): + print("debug called collect_downwards", node.title, n_steps) + if not node.id_ in ranked_adoptables.keys(): + ranked_adoptables[node.id_] = n_steps + for dep in node.deps: + collect_downwards(dep, ranked_adoptables, n_steps+1) + def collect_upwards(node, adoptables, n_steps): + print("debug called collect_upwards", node.title, n_steps) + collect_downwards(node, ranked_adoptables, n_steps+1) + if not node.task.fences_adoptions.now: + print("debug not blocking", node.dependers) + for depender in node.dependers: + collect_upwards(depender, ranked_adoptables, n_steps+1) + if len(node.dependers) == 0: + print("debug NO DEPENDERS, calling day") + for t in self.db.days[self.latest_date].linked_todos_as_list: + print("debug linked_todos_as_list:", t.title, t.id_) + collect_downwards(t, ranked_adoptables, n_steps) + else: + print("debug BLOCKING") + collect_upwards(self, ranked_adoptables, 0) + # for depender in self.dependers: + # collect_upwards(depender, ranked_adoptables, 0) + del ranked_adoptables[self.id_] + for id_, distance in sorted(ranked_adoptables.items(), key=lambda i:i[1], reverse=True): + if self.db.todos[id_].task.id_ == task_id: + return self.db.todos[id_] + return None + + + 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 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_) + for tag in todo.day_tags: self.t_tags.add(tag) - for date, day_dict in d['old_days'].items(): - self.old_days[date] = Day.from_dict(day_dict) + # 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 fork_task(self, id_): + origin = self.tasks[id_] + now = today_date(with_time=True) + fork_id = str(uuid4()) + fork = Task(self, fork_id, {}, {}, {}, {}, origin.comment, id_) + self.tasks[fork_id] = fork + return fork + + def update_task(self, id_, title, default_effort, tags, fences_adoptions, comment, dep_ids, depender_ids): + 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.fences_adoptions.set(fences_adoptions) + task.comment = comment + task.dep_ids.set(dep_ids) + for depender in task.dependers: + if not depender.id_ in depender_ids: + depender_dep_ids = depender.dep_ids.now + depender_dep_ids.remove(task.id_) + depender.dep_ids.set(depender_dep_ids) + for depender_id in depender_ids: + depender = self.tasks[depender_id] + depender_dep_ids = depender.dep_ids.now + depender_dep_ids.add(task.id_) + depender.dep_ids.set(depender_dep_ids) + task.loop_check() + return task + + def add_todo(self, todo_dict=None, id_=None, task=None, efforts=None, parenthood='', force_new=False, creator=None): + make_children = parenthood != 'childless' + adopt_if_possible = parenthood == 'adoption' + id_ = id_ if id_ else str(uuid4()) + if todo_dict: + todo = Todo.from_dict(self, todo_dict, id_) + self.todos[id_] = todo + elif task and efforts: + todo = Todo(self, id_, task, efforts=efforts) + print("DEBUG calling add_todo for", task.title.now, id_) + print("debug creator:", creator) + self.todos[id_] = todo + if creator: + creator.deps += [todo] + # deps = [] + if make_children and todo.latest_date in self.days.keys(): + 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 not force_new: + if adopt_if_possible: + print("debug trying adoption for", dep_task.title.now) + # adoptable_todos = [t for t in self.days[todo.latest_date].linked_todos_as_list + # if t.task.id_ == dep_task.id_] + # if len(adoptable_todos) > 0: + # dep_todo = adoptable_todos[0] + dep_todo = todo.closest_adoptable(dep_task.id_) + print("debug GOT ADOPTION", dep_todo) + if not dep_todo: + # dep_todo = self.add_todo(task=dep_task, efforts=efforts, force_new) + print("debug no adoption for", dep_task.title.now, id_) + dep_todo = self.add_todo(task=dep_task, efforts=efforts, parenthood=parenthood, creator=todo) + todo.deps += [dep_todo] + # deps += [dep_todo] + # todo.deps = deps + for date in todo.efforts.keys(): + if date in self.days.keys(): # possibly not all Days have been initialized yet + self.days[date].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, depender_ids): + 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.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 + todo.deps = deps + for depender_id in depender_ids: + depender = self.todos[depender_id] + depender.dep_ids.add(todo.id_) + for depender in todo.dependers: + if not depender.id_ in depender_ids: + depender.dep_ids.remove(todo.id_) + todo.loop_check() + + 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 get_message(self, message): + return j2env.get_template('message.html').render(message=message) + + def get_calendar_export(self, start_date_str, end_date_str): + days_to_show = self.init_calendar_items(start_date_str, end_date_str) + return j2env.get_template('calendar_export.html').render(days=days_to_show) + + def get_calendar(self, start_date_str, end_date_str): + days_to_show = self.init_calendar_items(start_date_str, end_date_str) + 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 get_day_todos(self, undone_sort_order=None, done_sort_order=None, is_tree_shaped=False, todo_parenthood=None): + 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, + parenthood=todo_parenthood) + + def get_todo(self, id_, parenthood): + 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, + parentood=parenthood, + dep_todos=todo.deps) + + def get_task(self, id_): + if id_: + if not id_ in self.tasks.keys(): + raise PlomException('no Task for ID') + task = self.tasks[id_] + else: + task = 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 get_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) + elif sort_column == 'latest_effort_date': + filtered_tasks.sort(key=lambda t: t.latest_effort_date) + 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) + + # posts + + def post_todo(self, id_, postvars, todo_parenthood): + if postvars.has('delete') and (not id_ in self.todos.keys()): + raise PlomException('can only do this on Todo that already exists') + old_todo = self.todos[id_] if id_ in self.todos.keys() else None + latest_date = self.selected_date + efforts = {} + for i, date in enumerate(postvars.get_all('effort_date', [])): + if '' == date: + continue + latest_date = date + efforts[date] = postvars.get_at_index('effort', i, float_if_possible=True) + if postvars.has('delete'): + raise PlomException('can only do this on Task that already exists') + 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') + self.delete_todo(id_) + return False + elif postvars.has('update'): + if postvars.has('delete_effort'): + for date in postvars.get_all('delete_effort'): + self.delete_effort(old_todo, date) + del efforts[date] + deps = [self.todos[adopt_id] for adopt_id in postvars.get_all('adopt_dep', []) + if adopt_id in self.todos.keys()] + birth_dep_ids = postvars.get_all('birth_dep', []) + for bad_id in [bad_id for bad_id in birth_dep_ids if not bad_id in self.tasks.keys()]: + raise PlomException('submitted illegal dep ID') + tasks_to_birth = [self.tasks[dep_id] for dep_id in birth_dep_ids] + for task in tasks_to_birth: + deps += [self.add_todo(task=task, + efforts={latest_date: None}, + parenthood=todo_parenthood)] + depender_ids = postvars.get_all('depender', []) + self.update_todo(id_=id_, + efforts=efforts, + done=postvars.has('done'), + comment=postvars.get('comment', ''), + tags=postvars.get_all('tag', []), + importance=postvars.get('importance', float_if_possible=True), + deps=deps, + depender_ids=depender_ids) + return True + + def post_task(self, id_, postvars): + if (postvars.has('delete') or postvars.has('fork')) and (not id_ in self.tasks.keys()): + raise PlomException('can only do this on Task that already exists') + if postvars.has('delete'): + if [t for t in self.todos.values() if 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') + self.delete_task(id_) + return None + elif postvars.has('update'): + dep_ids = postvars.get_all('dep', []) + for bad_id in [bad_id for bad_id in dep_ids if not bad_id in self.tasks.keys()]: + raise PlomException('submitted illegal dep ID') + depender_ids = postvars.get_all('depender', []) + for bad_id in [bad_id_ for bad_id in depender_ids if not bad_id in self.tasks.keys()]: + raise PlomException('submitted illegal dep ID') + task = self.update_task( + id_=id_, + title=postvars.get('title', ''), + default_effort=postvars.get('default_effort', float_if_possible=True), + tags=postvars.get_all('tag', []), + comment=postvars.get('comment', ''), + fences_adoptions=postvars.get('fences_adoptions', False), + dep_ids=dep_ids, + depender_ids=depender_ids) + if postvars.has('add_as_todo'): + self.add_todo(task=task, efforts={postvars.get('new_todo_date'): None}) + elif postvars.has('fork'): + t = self.fork_task(id_) + return t.id_ + return id_ + + def post_day_todos(self, postvars, todo_parenthood): + if not postvars.has('update'): + return + self.selected_date = postvars.get('date') + self.selected_day.comment = postvars.get('day_comment', '') + task_id = postvars.get('choose_task', None) + if task_id: + if task_id not in self.tasks.keys(): + raise PlomException('illegal task ID entered') + self.add_todo(task=self.tasks[task_id], efforts={self.selected_date: None}, + parenthood=todo_parenthood) + for todo_id in postvars.get_all('choose_todo', []): + self.todos[todo_id].efforts[self.selected_date] = None + for i, todo_id in enumerate(postvars.get_all('todo_id', [])): + old_todo = self.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: + self.delete_effort(old_todo, self.selected_date) + else: + self.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 + self.update_todo_for_day( + todo_id, + self.selected_date, + day_effort, + done, + comment, + importance) + + # helpers + + def init_calendar_items(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 days_to_show + + + +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): + 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, cookie_key, params): + if params in [['-'], '-']: + 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 + + 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) + return self._get_cookied(cookie_key, 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) + return self._get_cookied(cookie_key, 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: - 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) + 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 {'day_todos', 'todo'}: + todo_parenthood = postvars.get('parenthood') + redir_params += [('parenthood', todo_parenthood)] + if site in {'todo', 'task'}: + id_ = postvars.get('id') + + if 'tasks' == site: + redir_params += [('search', postvars.get('search', ''))] + elif 'todo' == site: + if db.post_todo(id_, postvars, todo_parenthood): + redir_params += [('id', id_)] else: - db.reset_today() + site = 'calendar' + elif 'task' == site: + ret = db.post_task(id_, postvars) + if ret: + redir_params += [('id', ret)] + else: + site = 'calendar' + elif 'day_todos' == site: + db.post_day_todos(postvars, todo_parenthood) + redir_params += [('date', db.selected_date)] + + 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) + if site in {'day_todos', 'todo'}: + todo_parenthood = params.get_cookied('parenthood', prefix=site) + if site in {'calendar', 'calendar_export', ''}: + start_date = params.get_cookied('start', prefix=site) + end_date = params.get_cookied('end', prefix=site) + if site in {'todo', 'task'}: + id_ = params.get('id') + + db = TodoDB(selected_date, tag_filter_and, tag_filter_not) + 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.get_message('cookie unset!') + elif 'day_todos' == site: + tree_view = 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.get_day_todos(undone_sort_order, done_sort_order, tree_view, todo_parenthood) + elif site == 'todo': + page = db.get_todo(id_, parenthood=todo_parenthood) + elif 'task' == site: + page = db.get_task(id_) + elif 'tasks' == site: + sort_order = params.get_cookied('sort', prefix=site) + search = params.get('search', '') + page = db.get_tasks(search, sort_order) + elif 'add_task' == site: + page = db.get_task(None) + elif 'calendar_export' == site: + page = db.get_calendar_export(start_date, end_date) + else: # 'calendar' == site + page = db.get_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)