super().__init__(*args, **kwargs)
+class LedgerTextLine:
+
+ def __init__(self, text_line):
+ self.text_line = text_line
+ self.comment = ''
+ split_by_comment = text_line.rstrip().split(sep=';', maxsplit=1)
+ self.non_comment = split_by_comment[0].rstrip()
+ self.empty = len(split_by_comment) == 1 and len(self.non_comment) == 0
+ if self.empty:
+ return
+ if len(split_by_comment) == 2:
+ self.comment = split_by_comment[1].lstrip()
+
+
+
# html_head = """
# <style>
# body { color: #000000; }
def __init__(self):
self.money_dict = {}
- def add_money_dict(self, moneys):
+ def __iadd__(self, moneys):
+ money_dict = moneys
+ if type(moneys) == Wealth:
+ moneys = moneys.money_dict
for currency, amount in moneys.items():
if not currency in self.money_dict.keys():
self.money_dict[currency] = 0
self.money_dict[currency] += amount
+ return self
- def add_wealth(self, moneys):
- self.add_money_dict(moneys.money_dict)
+ @property
+ def sink_empty(self):
+ return len(self.as_sink) == 0
@property
- def as_sink_dict(self):
+ def as_sink(self):
sink = {}
for currency, amount in self.money_dict.items():
if 0 == amount:
self.children = []
def add_wealth(self, moneys):
- self.own_moneys.add_wealth(moneys)
+ self.own_moneys += moneys
@property
def full_name(self):
@property
def full_moneys(self):
full_moneys = Wealth()
- full_moneys.add_wealth(self.own_moneys)
+ full_moneys += self.own_moneys
for child in self.children:
- full_moneys.add_wealth(child.full_moneys)
+ full_moneys += child.full_moneys
return full_moneys
# return account_tree, account_sums
-def parse_lines2(lines, ignore_editable_exceptions=False):
- lines = lines.copy() + [''] # to simulate ending of last booking
+def parse_lines_to_bookings(lines, ignore_editable_exceptions=False):
+ lines = [LedgerTextLine(line) for line in lines]
+ lines += [LedgerTextLine('')] # to simulate ending of last booking
bookings = []
inside_booking = False
booking_lines = []
last_date = ''
for i, line in enumerate(lines):
intro = f'file line {i}'
- stripped_line = line.rstrip()
- if stripped_line == '':
+ if line.empty:
if inside_booking:
booking = Booking(lines=booking_lines, starts_at=booking_start_i)
if last_date > booking.date and not ignore_editable_exceptions:
self.currency = currency
self.comment = comment
if line:
- split_by_comment = line.rstrip().split(sep=';', maxsplit=1)
- if len(split_by_comment) == 0:
+ if line.empty:
raise PlomException('line empty')
- elif len(split_by_comment) == 2:
- self.comment = split_by_comment[1].lstrip()
- non_comment = split_by_comment[0].rstrip()
- toks = non_comment.split()
+ self.comment = line.comment
+ toks = line.non_comment.split()
if (len(toks) not in {1, 3}):
if validate:
raise PlomException(f'number of non-comment tokens not 1 or 3')
if validate:
raise PlomException(f'invalid token for Decimal: {toks[1]}')
else:
- self.amount = toks[1]
+ self.comment = f'unparsed: {toks[1]}; {self.comment}'
self.currency = toks[2]
@property
else:
return f'{self.amount:.2f}'
+ @property
def for_writing(self):
line = f' {self.account}'
if self.amount is not None:
self.intro = f'booking starting at line {self.starts_at}'
self.clean()
if lines:
- self.real_lines = lines
+ self.lines = lines
self.parse_lines()
else:
self.date = date
if len(self.transfer_lines) < 2 and self.validate:
raise PlomException(f'{self.intro}: too few transfer lines')
self.calculate_account_changes()
- self.real_lines = self.for_writing()
+ self.lines = [LedgerTextLine(l) for l in self.for_writing]
@classmethod
def from_postvars(cls, postvars, starts_at='?', validate=True):
self.account_changes = {}
def parse_lines(self):
- self.top_comment = ''
- if len(self.real_lines) < 3 and self.validate:
- raise PlomException(f'{self.intro}: ends with less than 3 lines:' + str(self.real_lines))
- split_by_comment = self.real_lines[0].rstrip().split(sep=";", maxsplit=1)
- if len(split_by_comment) == 0 and self.validate:
+ if len(self.lines) < 3 and self.validate:
+ raise PlomException(f'{self.intro}: ends with less than 3 lines:' + str(self.lines))
+ top_line = self.lines[0]
+ if top_line.empty and self.validate:
raise PlomException('{self.intro}: headline empty')
- elif len(split_by_comment) == 2 and self.validate:
- self.top_comment = split_by_comment[1].lstrip()
- non_comment = split_by_comment[0].rstrip()
- toks = non_comment.split()
+ self.top_comment = top_line.comment
+ toks = top_line.non_comment.split(maxsplit=1)
if len(toks) < 2:
if self.validate:
raise PlomException(f'{self.intro}: headline missing elements: {non_comment}')
self.date = toks[0]
self.description = toks[1]
self.validate_head()
- for i, line in enumerate(self.real_lines[1:]):
+ for i, line in enumerate(self.lines[1:]):
try:
self.transfer_lines += [TransferLine(line, validate=self.validate)]
except PlomException as e:
if not transfer_line.account in self.account_changes.keys():
self.account_changes[transfer_line.account] = Wealth()
money = {transfer_line.currency: transfer_line.amount}
- self.account_changes[transfer_line.account].add_money_dict(money)
- money_changes.add_money_dict(money)
- if sink_account is None and len(money_changes.as_sink_dict) > 0 and self.validate:
- raise PlomException(f'{intro}: does not balance (unused non-empty sink)')
+ self.account_changes[transfer_line.account] += money
+ money_changes += money
+ if sink_account is None and (not money_changes.sink_empty) and self.validate:
+ raise PlomException(f'{intro}: does not balance (undeclared non-empty sink)')
if sink_account is not None:
if not sink_account in self.account_changes.keys():
self.account_changes[sink_account] = Wealth()
- self.account_changes[sink_account].add_money_dict(money_changes.as_sink_dict)
+ self.account_changes[sink_account] += money_changes.as_sink
+
+ @property
+ def for_writing(self):
+ lines = [f'{self.date} {self.description}']
+ if self.top_comment is not None and self.top_comment.rstrip() != '':
+ lines[0] += f' ; {self.top_comment}'
+ for line in self.transfer_lines:
+ lines += [line.for_writing]
+ return lines
+
+ @property
+ def comment_cols(self):
+ return max(20, len(self.top_comment))
def validate_head(self):
if not self.validate:
for i, line in enumerate(self.transfer_lines):
if line.amount is None:
for currency, amount in self.account_changes[line.account].money_dict.items():
- replacement_lines += [TransferLine(None, f'{line.account}', amount, currency).for_writing()]
+ replacement_lines += [TransferLine(None, f'{line.account}', amount, currency).for_writing]
break
- lines = self.real_lines[:i+1] + replacement_lines + self.real_lines[i+2:]
+ lines = self.lines[:i+1] + [LedgerTextLine(l) for l in replacement_lines] + self.lines[i+2:]
self.clean()
- self.real_lines = lines
+ self.lines = lines
self.parse_lines()
- def add_mirror(self):
+ def mirror(self):
new_transfer_lines = []
- for line in self.transfer_lines:
- new_transfer_lines += [TransferLine(None, f'({line.account})', line.amount, line.currency, line.comment)]
+ for transfer_line in self.transfer_lines:
+ uncommented_source = LedgerTextLine(transfer_line.for_writing).non_comment
+ comment = f're: {uncommented_source.lstrip()}'
+ new_account = '?'
+ new_transfer_lines += [TransferLine(None, new_account, -transfer_line.amount, transfer_line.currency, comment)]
for transfer_line in new_transfer_lines:
- self.real_lines += [transfer_line.for_writing()]
+ self.lines += [LedgerTextLine(transfer_line.for_writing)]
+ self.clean()
+ self.parse_lines()
+
+ def replace(self, replace_from, replace_to):
+ lines = []
+ for l in self.for_writing:
+ lines += [l.replace(replace_from, replace_to)]
+ self.lines = [LedgerTextLine(l) for l in lines]
self.clean()
self.parse_lines()
self.transfer_lines += [TransferLine(None, acc_assets, final_minus, '€')]
self.transfer_lines += [TransferLine(None, acc_buffer, -final_minus, '€')]
- def for_writing(self):
- lines = [f'{self.date} {self.description}']
- if self.top_comment is not None and self.top_comment.rstrip() != '':
- lines[0] += f' ; {self.top_comment}'
- for line in self.transfer_lines:
- lines += [line.for_writing()]
- return lines
-
- @property
- def comment_cols(self):
- return max(20, len(self.top_comment))
-
# class Booking:
#
self.prefix = prefix
self.bookings = []
self.comments = []
- self.real_lines = []
+ self.text_lines = []
super().__init__(db_path)
- self.bookings = parse_lines2(self.real_lines, ignore_editable_exceptions)
+ self.bookings = parse_lines_to_bookings(self.text_lines, ignore_editable_exceptions)
def read_db_file(self, f):
- self.real_lines += [l.rstrip() for l in f.readlines()] # TODO is this necessary? (parser already removes lines?)
+ self.text_lines += f.readlines()
+ # self.text_lines += [l.rstrip() for l in f.readlines()] # TODO is this necessary? (parser already removes lines?)
# def get_lines(self, start, end):
- # return self.real_lines[start:end]
+ # return self.text_lines[start:end]
# def write_db(self, text, mode='w'):
# if text[-1] != '\n':
# start_at = 0
# if len(self.bookings) > 0:
# if date >= self.bookings[-1].date_string:
- # start_at = len(self.real_lines)
+ # start_at = len(self.text_lines)
# lines = [''] + lines
# else:
# for b in self.bookings:
# start_at = b.start_line
# break
# lines += [''] # DEBUG is new
- # return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
+ # return self.write_lines_in_total_lines_at(self.text_lines, start_at, lines)
# def update(self, start, end, lines, date):
- # remaining_lines = self.real_lines[:start] + self.real_lines[end:]
+ # remaining_lines = self.text_lines[:start] + self.text_lines[end:]
# n_original_lines = end - start
# start_at = len(remaining_lines)
# for b in self.bookings:
# start_at -= n_original_lines
# elif b.date_string > date:
# break
- # # print("DEBUG update start_at", start_at, "len(remaining_lines)", len(remaining_lines), "len(self.real_lines)", len(self.real_lines), "end", end)
- # if start_at != 0 and end != len(self.real_lines) and start_at == len(remaining_lines):
+ # # print("DEBUG update start_at", start_at, "len(remaining_lines)", len(remaining_lines), "len(self.text_lines)", len(self.text_lines), "end", end)
+ # if start_at != 0 and end != len(self.text_lines) and start_at == len(remaining_lines):
# # Add empty predecessor line if appending.
# lines = [''] + lines
# return self.write_lines_in_total_lines_at(remaining_lines, start_at, lines)
break
else:
place_at = i + 1
- self.bookings = self.bookings[:place_at] + [booking] + self.bookings[place_at:]
+ self.bookings.insert(place_at, booking)
def add_taxes(self, lines, finish=False):
ret = []
# return ret
def ledger_as_html(self):
- for nth, booking in enumerate(self.bookings):
- booking.can_up = nth > 0 and self.bookings[nth - 1].date == booking.date
- booking.can_down = nth < len(self.bookings) - 1 and self.bookings[nth + 1].date == booking.date
+ for index, booking in enumerate(self.bookings):
+ booking.can_up = index > 0 and self.bookings[index - 1].date == booking.date
+ booking.can_down = index < len(self.bookings) - 1 and self.bookings[index + 1].date == booking.date
return j2env.get_template('ledger.html').render(bookings=self.bookings)
# def ledger_as_html(self):
# elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:] if c != ''] #
# return '\n'.join(elements_to_write)
- def balance_as_html(self, until=None):
- bookings = self.bookings[:(until if until is None else int(until)+1)]
+ def balance_as_html(self, until_after=None):
+ bookings = self.bookings[:(until_after if until_after is None else int(until_after)+1)]
account_trunk = Account('', None)
accounts = {account_trunk.full_name: account_trunk}
for booking in bookings:
# content = "\n".join(lines)
# return f"<pre>{content}</pre>"
- def edit(self, index, sent=None, error_msg=None, edit_mode='table'):
+ def edit(self, index, sent=None, error_msg=None, edit_mode='table', copy=False):
accounts = set()
if sent or -1 == index:
content = sent if sent else ([] if 'textarea'==edit_mode else None)
else:
content = self.bookings[index]
+ if copy:
+ content.date = str(datetime.now())[:10]
if 'textarea' == edit_mode and content:
- content = content.for_writing()
+ content = content.for_writing
else:
for booking in self.bookings:
for transfer_line in booking.transfer_lines:
accounts.add(transfer_line.account)
- return j2env.get_template('edit.html').render(content=content, index=index, error_msg=error_msg, edit_mode=edit_mode, accounts=accounts)
+ return j2env.get_template('edit.html').render(content=content, index=index, error_msg=error_msg, edit_mode=edit_mode, accounts=accounts, adding=(copy or -1 == index))
# def add_free(self, start=0, end=0, copy=False):
# tmpl = jinja2.Template(add_form_header + add_free_html + add_form_footer)
# end=end)
# return content
- def move_up(self, nth):
- return self.move(nth, -1)
+ def move_up(self, index):
+ return self.move(index, -1)
- def move_down(self, nth):
- return self.move(nth, +1)
+ def move_down(self, index):
+ return self.move(index, +1)
- def move(self, nth, direction):
- to_move = self.bookings[nth]
- swap_nth = nth+1*(direction)
- to_swap = self.bookings[swap_nth]
- self.bookings[nth] = to_swap
- self.bookings[nth+1*(direction)] = to_move
- return swap_nth
+ def move(self, index, direction):
+ to_move = self.bookings[index]
+ swap_index = index + 1*(direction)
+ to_swap = self.bookings[swap_index]
+ self.bookings[index] = to_swap
+ self.bookings[index + 1*(direction)] = to_move
+ return swap_index
def write_db(self):
lines = []
for i, booking in enumerate(self.bookings):
if i > 0:
lines += ['']
- lines += booking.for_writing()
+ lines += booking.for_writing
self.write_text_to_db('\n'.join(lines) + '\n')
# def move_up(self, start, end):
# # FIXME currently broken due to changed self.write_lines_in_total_lines_at, easy fix would be lines += [""] maybe?
# lines = self.get_lines(start, end)
# if start == 0:
- # total_lines = self.real_lines[end+1:]
+ # total_lines = self.text_lines[end+1:]
# lines = [''] + lines
# start_at += 1
# else:
- # total_lines = self.real_lines[:start-1] + self.real_lines[end:] # -1 because we reduce the original position's two empty limit lines to one in-between line
+ # total_lines = self.text_lines[:start-1] + self.text_lines[end:] # -1 because we reduce the original position's two empty limit lines to one in-between line
# lines += ['']
# self.write_lines_in_total_lines_at(total_lines, start_at, lines)
db = LedgerDB(prefix, ignore_editable_exceptions=True)
index = 0
parsed_url = urlparse(self.path)
- for string in {'save', 'copy', 'check', 'mirror', 'fill sink', 'as textarea', 'as table', 'move up', 'move down', 'add taxes'}:
+ for string in {'update', 'add', 'check', 'mirror', 'fill_sink', 'textarea', 'table', 'move_up', 'move_down', 'add_taxes', 'replace'}:
if string in postvars.keys():
submit_button = string
break
- if prefix + '/ledger' == parsed_url.path:
- if submit_button == 'move up':
- index = db.move_up(int(postvars['move up'][0]))
- elif submit_button == 'move down':
- index = db.move_down(int(postvars['move down'][0]))
+ if f'{prefix}/ledger' == parsed_url.path and submit_button in {'move_up', 'move_down'}:
+ mover = getattr(db, submit_button)
+ index = mover(int(postvars[submit_button][0]))
elif prefix + '/edit' == parsed_url.path:
index = int(postvars['index'][0])
- starts_at = '?' if index == -1 else db.bookings[index].starts_at
edit_mode = postvars['edit_mode'][0]
validate = submit_button in {'save', 'copy', 'check'}
+ starts_at = '?' if index == -1 else db.bookings[index].starts_at
if 'textarea' == edit_mode:
- lines = postvars['booking'][0].rstrip().split('\n')
+ lines = [LedgerTextLine(line) for line in postvars['booking'][0].rstrip().split('\n')]
booking = Booking(lines, starts_at, validate=validate)
else:
booking = Booking.from_postvars(postvars, starts_at, validate)
- if submit_button in {'save', 'copy'}:
- if index != -1 and submit_button != 'copy':
- if booking.date == db.bookings[index].date:
- db.bookings[index] = booking
- booking_is_placed = True
- else:
- db.bookings = db.bookings[:index] + db.bookings[index+1:]
- db.insert_booking_at_date(booking)
+ if submit_button in {'update', 'add'}:
+ if submit_button == 'update':
+ if 'textarea' == edit_mode and 'delete' == ''.join([l.text_line for l in lines]).strip():
+ del db.bookings[index]
+ # if not creating new Booking, and date unchanged, keep it in place
+ elif booking.date == db.bookings[index].date:
+ db.bookings[index] = booking
+ else:
+ del db.bookings[index]
+ db.insert_booking_at_date(booking)
else:
db.insert_booking_at_date(booking)
- else:
+ else: # non-DB-writing calls
error_msg = None
if 'check' == submit_button:
error_msg = 'All looks fine!'
- elif 'mirror' == submit_button:
- booking.add_mirror()
- elif 'fill sink' == submit_button:
- booking.fill_sink()
- elif 'add taxes' == submit_button:
- booking.add_taxes()
- elif submit_button in {'as textarea', 'as table'}:
- edit_mode = submit_button[len('as '):]
+ elif submit_button in {'mirror', 'fill_sink', 'add_taxes'}:
+ getattr(booking, submit_button)()
+ elif 'replace' == submit_button:
+ booking.replace(postvars['replace_from'][0], postvars['replace_to'][0])
+ elif submit_button in {'textarea', 'table'}:
+ edit_mode = submit_button
page = db.edit(index, booking, error_msg=error_msg, edit_mode=edit_mode)
self.send_HTML(page)
return
try:
db = LedgerDB(prefix=prefix)
except EditableException as e:
+ # We catch the EditableException for further editing, and then
+ # re-run the DB initiation without it blocking DB creation.
db = LedgerDB(prefix=prefix, ignore_editable_exceptions=True)
page = db.edit(index=e.booking_index, error_msg=f'ERROR: {e}')
self.send_HTML(page)
return
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
- if parsed_url.path == prefix + '/balance':
- stop = params.get('stop', [None])[0]
+ if parsed_url.path == f'{prefix}/balance':
+ stop = params.get('until_after', [None])[0]
page = db.balance_as_html(stop)
- elif parsed_url.path == prefix + '/edit':
+ elif parsed_url.path == f'{prefix}/edit':
index = params.get('i', [-1])[0]
- page = db.edit(int(index))
+ copy = params.get('copy', [0])[0]
+ page = db.edit(int(index), copy=bool(copy))
else:
page = db.ledger_as_html()
self.send_HTML(page)
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'
server_port = 8082
DATE_FORMAT = '%Y-%m-%d'
class Task:
- def __init__(self, db, title_history=None, tags_history=None, default_effort_history=None, links_history=None):
+ 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):
return default if 0 == len(history) else history[keys[-1]]
@classmethod
- def from_dict(cls, db, d):
- return cls(
+ 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()})
+ {k: set(v) for k, v in d['links_history'].items()},
+ d['comment'])
+ return t
def to_dict(self):
return {
'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 current_default_effort(self):
return self.default_effort_at(self.db.selected_date)
+ 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 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
+ # @property
+ # def id_(self):
+ # for k, v in self.db.tasks.items():
+ # if v == self:
+ # return k
class Day:
- def __init__(self, db, todos=None, comment=''):
+ # def __init__(self, db, todos=None, comment='', date=None):
+ def __init__(self, db, date, comment=''):
+ self.date = date
self.db = db
- self.todos = todos if todos else {}
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, db, d):
- todos = {}
+ def from_dict(cls, db, d, date=None):
+ # todos = {}
comment = d['comment'] if 'comment' in d.keys() else ''
- day = cls(db, todos, comment)
- for uuid, todo_dict in d['todos'].items():
- day.add_todo(uuid, todo_dict)
+ 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, 'todos': {}}
- for task_uuid, todo in self.todos.items():
- d['todos'][task_uuid] = todo.to_dict()
+ 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, id_, dict_source=None):
- self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
- return self.todos[id_]
+ # 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 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.effort
- if include_undone:
- for todo in [todo for todo in self.todos.values() if not todo.done]:
- s += todo.day_effort if todo.day_effort else 0
+ 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
@property
def todos_sum2(self):
return self._todos_sum(True)
- @property
- def date(self):
- for k, v in self.db.days.items():
- if v == self:
- return k
+ # @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, day, done=False, day_effort=None, comment='', day_tags=None, importance=1.0):
- self.day = day
+ # 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_effort = day_effort
+ # 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, day, d):
- return cls(day, d['done'], d['day_effort'], d['comment'], set(d['day_tags']), d['importance'])
+ 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_effort': self.day_effort, 'comment': self.comment, 'day_tags': list(self.day_tags), 'importance': self.importance}
+ # 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
+ # @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 self.day_effort if self.day_effort else self.default_effort
-
- @property
- def task(self):
- for k, v in self.day.todos.items():
- if v == self:
- return self.day.db.tasks[k]
+ return search in self.comment or search in '$'.join(self.tags) or search in self.title
@property
def title(self):
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):
self.days = {}
self.tasks = {}
self.t_tags = set()
+ self.todos = {}
super().__init__(db_path)
def read_db_file(self, f):
d = json.load(f)
- for date, day_dict in d['days'].items():
- self.days[date] = self.add_day(dict_source=day_dict)
- for day in self.days.values():
- for todo in day.todos.values():
- for tag in todo.day_tags:
- self.t_tags.add(tag)
- for uuid, t_dict in d['tasks'].items():
- t = self.add_task(id_=uuid, dict_source=t_dict)
+ 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)
+ # 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):
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 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 = {'tasks': {}, 'days': {}}
+ d = {'tasks': {}, 'days': {}, 'todos': {}}
for uuid, t in self.tasks.items():
d['tasks'][uuid] = t.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()
+ 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.todos) == 0 and len(day.comment) == 0:
+ 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 add_task(self, id_=None, dict_source=None, return_id=False):
- t = Task.from_dict(self, dict_source) if dict_source else Task(self)
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:
return t
- def add_day(self, dict_source=None):
- return Day.from_dict(self, dict_source) if dict_source else Day(self)
+ 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'
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']
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(start_date_str, DATE_FORMAT)
+ 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()
+ 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, task_uuid, selected_date, referer):
- if selected_date not in self.days.keys():
- self.days[selected_date] = self.add_day()
- 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', referer=referer)
+ 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()
+ 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:
tags.add(tag)
return tags
- 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
+ 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_, referer=''):
+ def show_task(self, id_, return_to=''):
task = self.tasks[id_] if id_ else self.add_task()
- return j2env.get_template('task.html').render(db=self, task=task, action=self.prefix+'/task', referer=referer)
+ 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):
+ 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
+ task.links = links
for link in links:
borrowed_links = self.tasks[link].links
borrowed_links.add(id_)
self.tasks[link].links = borrowed_links
-
- def show_tasks(self):
- return j2env.get_template('tasks.html').render(db=self, action=self.prefix+'/tasks')
-
+ 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 write_db(self):
from urllib.parse import urlencode
- app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
+ 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)
parsed_url = urlparse(self.path)
- db = TodoDB(prefix=app_config['prefix'])
- params_to_encode = []
- 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:
- params_to_encode += [(param_name, '-')]
- params_to_encode += [(param_name, f) for f in filter_db]
+ 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 = []
tags_checked += [k[len(prefix):]]
return tags_checked
- if parsed_url.path == app_config['prefix'] + '/calendar':
- params_to_encode += [('start', postvars['start'][0] if len(postvars['start'][0]) > 0 else '-')]
- params_to_encode += [('end', postvars['end'][0] if len(postvars['end'][0]) > 0 else '-')]
-
- elif parsed_url.path == app_config['prefix'] + '/todo':
- task_uuid = postvars['task_uuid'][0]
- date = postvars['date'][0]
- params_to_encode += [('task', task_uuid), ('date', date)]
- 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])
-
- elif parsed_url.path == app_config['prefix'] + '/task':
+ 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
+ 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]
- params_to_encode += [('id', id_)]
+ 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))
-
- elif parsed_url.path == app_config['prefix'] + '/day':
+ 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.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():
- params_to_encode += [('hide_unchosen', int('hide_unchosen' in postvars.keys()))] + [('hide_done', int('hide_done' in postvars.keys()))]
+ redir_params += [('hide_unchosen', int('hide_unchosen' in postvars.keys()))] + [('hide_done', int('hide_done' in postvars.keys()))]
- if 'selected_date' in postvars.keys():
- db.selected_date = postvars['selected_date'][0]
+ 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]
- params_to_encode += [('selected_date', db.selected_date)]
+ redir_params += [('date', db.selected_date)]
# handle todo list updates via task UUIDs
if 't_uuid' in postvars.keys():
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]
- else:
+ 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
continue
db.update_todo_mini(uuid, db.selected_date, day_effort, done, importance)
- if 'referer' in postvars.keys() and len(postvars['referer'][0]) > 0:
- homepage = postvars['referer'][0]
+ if 'return_to' in postvars.keys() and len(postvars['return_to'][0]) > 0:
+ homepage = postvars['return_to'][0]
else:
- encoded_params = urlencode(params_to_encode)
- homepage = f'{parsed_url.path}?{encoded_params}'
+ encoded_params = urlencode(redir_params)
+ # homepage = f'{parsed_url.path}?{encoded_params}'
+ homepage = f'{site}?{encoded_params}'
db.write()
self.redirect(homepage)
self.try_do(self.show_db)
def show_db(self):
- app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
- cookie_db = self.get_cookie_db(app_config['cookie_name'])
+ 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)
-
- def get_param(param_name, boolean=False, chained=False):
- if chained:
- param = params.get(param_name, None)
- 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
+ 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
- referer = params.get('referer', [''])[0]
- if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks'}:
- selected_date = get_param('selected_date')
- if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks', app_config['prefix'] + '/task'}:
- t_filter_and = get_param('t_and', chained=True)
- t_filter_not = get_param('t_not', chained=True)
- if parsed_url.path == app_config['prefix'] + '/day':
- hide_unchosen = get_param('hide_unchosen', boolean=True)
- hide_done = get_param('hide_done', boolean=True)
- db = TodoDB(app_config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done)
- if parsed_url.path == app_config['prefix'] + '/day':
- task_sort = get_param('sort')
- page = db.show_day(task_sort)
- elif parsed_url.path == app_config['prefix'] + '/todo':
- todo_date = params.get('date', [None])[0]
- task_uuid = params.get('task', [None])[0]
- page = db.show_todo(task_uuid, todo_date, referer)
- elif parsed_url.path == app_config['prefix'] + '/task':
- id_ = params.get('id', [None])[0]
- page = db.show_task(id_, referer)
- elif parsed_url.path == app_config['prefix'] + '/tasks':
- page = db.show_tasks()
- elif parsed_url.path == app_config['prefix'] + '/add_task':
+ # 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 parsed_url.path == app_config['prefix'] + '/unset_cookie':
+ 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(app_config['cookie_name'], app_config['cookie_path'])
+ self.unset_cookie(config['cookie_name'], config['cookie_path'])
page = 'cookie unset!'
else:
- start_date = get_param('start')
- end_date = get_param('end')
+ start_date = params.get_cookied('start')
+ end_date = params.get_cookied('end')
page = db.show_calendar(start_date, end_date)
- if parsed_url.path != app_config['prefix'] + '/unset_cookie':
- self.set_cookie(app_config['cookie_name'], app_config['cookie_path'], cookie_db)
+ if 'unset_cookie' != site:
+ self.set_cookie(config['cookie_name'], config['cookie_path'], cookie_db)
self.send_HTML(page)