home · contact · privacy
Improve accounting scripts.
authorChristian Heller <c.heller@plomlompom.de>
Sun, 14 Jan 2024 02:25:15 +0000 (03:25 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Sun, 14 Jan 2024 02:25:15 +0000 (03:25 +0100)
ledger.py
todo.py
todo_templates/base.html
todo_templates/calendar.html
todo_templates/day.html
todo_templates/task.html
todo_templates/tasks.html
todo_templates/todo.html

index aa295d28203d7279137d9b143b5c236e98c92e31..a26ca0f345f5dfdaf02eb8cff45330991eb14d7d 100755 (executable)
--- a/ledger.py
+++ b/ledger.py
@@ -15,6 +15,21 @@ class EditableException(PlomException):
         super().__init__(*args, **kwargs)
     
 
         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; }
 # html_head = """
 # <style>
 # body { color: #000000; }
@@ -108,17 +123,22 @@ class Wealth:
     def __init__(self):
         self.money_dict = {}
 
     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
         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
 
     @property
-    def as_sink_dict(self):
+    def as_sink(self):
         sink = {} 
         for currency, amount in self.money_dict.items():
             if 0 == amount:
         sink = {} 
         for currency, amount in self.money_dict.items():
             if 0 == amount:
@@ -138,7 +158,7 @@ class Account:
         self.children = []
 
     def add_wealth(self, moneys):
         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_name(self):
@@ -150,9 +170,9 @@ class Account:
     @property
     def full_moneys(self):
         full_moneys = Wealth() 
     @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:
         for child in self.children:
-            full_moneys.add_wealth(child.full_moneys)
+            full_moneys += child.full_moneys
         return full_moneys
 
 
         return full_moneys
 
 
@@ -209,8 +229,9 @@ class Account:
 #     return account_tree, account_sums
 
 
 #     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 = []
     bookings = []
     inside_booking = False
     booking_lines = []
@@ -218,8 +239,7 @@ def parse_lines2(lines, ignore_editable_exceptions=False):
     last_date = '' 
     for i, line in enumerate(lines):
         intro = f'file line {i}'
     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:
             if inside_booking:
                 booking = Booking(lines=booking_lines, starts_at=booking_start_i)
                 if last_date > booking.date and not ignore_editable_exceptions:
@@ -369,13 +389,10 @@ class TransferLine:
         self.currency = currency 
         self.comment = comment 
         if line:
         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')
                 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 (len(toks) not in {1, 3}):
                 if validate:
                     raise PlomException(f'number of non-comment tokens not 1 or 3')
@@ -391,7 +408,7 @@ class TransferLine:
                     if validate:
                         raise PlomException(f'invalid token for Decimal: {toks[1]}')
                     else:
                     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
                 self.currency = toks[2]
 
     @property
@@ -403,6 +420,7 @@ class TransferLine:
         else:
             return f'{self.amount:.2f}'
 
         else:
             return f'{self.amount:.2f}'
 
+    @property
     def for_writing(self):
         line = f'  {self.account}'
         if self.amount is not None:
     def for_writing(self):
         line = f'  {self.account}'
         if self.amount is not None:
@@ -424,7 +442,7 @@ class Booking:
         self.intro = f'booking starting at line {self.starts_at}'
         self.clean()
         if lines:
         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
             self.parse_lines()
         else:
             self.date = date
@@ -435,7 +453,7 @@ class Booking:
             if len(self.transfer_lines) < 2 and self.validate:
                 raise PlomException(f'{self.intro}: too few transfer lines')
             self.calculate_account_changes()
             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):
 
     @classmethod
     def from_postvars(cls, postvars, starts_at='?', validate=True):
@@ -457,16 +475,13 @@ class Booking:
         self.account_changes = {}
 
     def parse_lines(self):
         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')
             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}')
         if len(toks) < 2:
             if self.validate:
                 raise PlomException(f'{self.intro}: headline missing elements: {non_comment}')
@@ -477,7 +492,7 @@ class Booking:
         self.date = toks[0]
         self.description = toks[1]
         self.validate_head()
         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:
             try:
                 self.transfer_lines += [TransferLine(line, validate=self.validate)]
             except PlomException as e:
@@ -497,14 +512,27 @@ class Booking:
                 if not transfer_line.account in self.account_changes.keys():
                     self.account_changes[transfer_line.account] = Wealth()
                 money = {transfer_line.currency: transfer_line.amount}
                 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()
         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:
 
     def validate_head(self):
         if not self.validate:
@@ -523,19 +551,30 @@ class Booking:
         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():
         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
                 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.clean()
-        self.real_lines = lines
+        self.lines = lines
         self.parse_lines()
 
         self.parse_lines()
 
-    def add_mirror(self):
+    def mirror(self):
         new_transfer_lines = []
         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:
         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.clean()
         self.parse_lines()
 
@@ -614,18 +653,6 @@ class Booking:
         self.transfer_lines += [TransferLine(None, acc_assets, final_minus, '€')]
         self.transfer_lines += [TransferLine(None, acc_buffer, -final_minus, '€')]
 
         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:
 # 
 
 # class Booking:
 # 
@@ -697,15 +724,16 @@ class LedgerDB(PlomDB):
         self.prefix = prefix 
         self.bookings = []
         self.comments = []
         self.prefix = prefix 
         self.bookings = []
         self.comments = []
-        self.real_lines = []
+        self.text_lines = []
         super().__init__(db_path)
         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):
 
     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):
 
     # 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':
 
     # def write_db(self, text, mode='w'):
     #     if text[-1] != '\n':
@@ -716,7 +744,7 @@ class LedgerDB(PlomDB):
     #     start_at = 0 
     #     if len(self.bookings) > 0:
     #         if date >= self.bookings[-1].date_string:
     #     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:
     #             lines = [''] + lines
     #         else:
     #             for b in self.bookings:
@@ -726,10 +754,10 @@ class LedgerDB(PlomDB):
     #                     start_at = b.start_line 
     #                     break
     #             lines += ['']  # DEBUG is new
     #                     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):
 
     # 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:
     #     n_original_lines = end - start
     #     start_at = len(remaining_lines)
     #     for b in self.bookings:
@@ -740,8 +768,8 @@ class LedgerDB(PlomDB):
     #                     start_at -= n_original_lines
     #         elif b.date_string > date:
     #             break
     #                     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)
     #         # Add empty predecessor line if appending.
     #         lines = [''] + lines
     #     return self.write_lines_in_total_lines_at(remaining_lines, start_at, lines)
@@ -773,7 +801,7 @@ class LedgerDB(PlomDB):
                     break
                 else:
                     place_at = i + 1
                     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 = []
 
     def add_taxes(self, lines, finish=False):
         ret = []
@@ -902,9 +930,9 @@ class LedgerDB(PlomDB):
     #     return ret
 
     def ledger_as_html(self):
     #     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):
         return j2env.get_template('ledger.html').render(bookings=self.bookings)
 
     # def ledger_as_html(self):
@@ -944,8 +972,8 @@ class LedgerDB(PlomDB):
     #     elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:] if c != '']  #
     #     return '\n'.join(elements_to_write)
 
     #     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:
         account_trunk = Account('', None)
         accounts = {account_trunk.full_name: account_trunk}
         for booking in bookings:
@@ -998,19 +1026,21 @@ class LedgerDB(PlomDB):
     #     content = "\n".join(lines)
     #     return f"<pre>{content}</pre>"
 
     #     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]
         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:
         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)
         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) 
 
     # def add_free(self, start=0, end=0, copy=False):
     #     tmpl = jinja2.Template(add_form_header + add_free_html + add_form_footer) 
@@ -1076,26 +1106,26 @@ class LedgerDB(PlomDB):
     #             end=end)
     #     return content
 
     #             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 += ['']
 
     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):
         self.write_text_to_db('\n'.join(lines) + '\n')
 
     # def move_up(self, start, end):
@@ -1124,11 +1154,11 @@ class LedgerDB(PlomDB):
     #     # 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:
     #     # 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: 
     #         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)
 
     #         lines += ['']
     #     self.write_lines_in_total_lines_at(total_lines, start_at, lines)
 
@@ -1208,47 +1238,45 @@ class LedgerHandler(PlomHandler):
         db = LedgerDB(prefix, ignore_editable_exceptions=True)
         index = 0
         parsed_url = urlparse(self.path)
         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 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])
         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'}
             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:
             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)
                 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: 
                     db.insert_booking_at_date(booking)
-            else:
+            else:  # non-DB-writing calls
                 error_msg = None
                 if 'check' == submit_button:
                     error_msg = 'All looks fine!'
                 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
                 page = db.edit(index, booking, error_msg=error_msg, edit_mode=edit_mode)
                 self.send_HTML(page)
                 return
@@ -1315,18 +1343,21 @@ class LedgerHandler(PlomHandler):
         try:
             db = LedgerDB(prefix=prefix)
         except EditableException as e:
         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)
             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)
             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]
             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)
         else:
             page = db.ledger_as_html()
         self.send_HTML(page)
diff --git a/todo.py b/todo.py
index 29c1226e2d4938605bb0a2b48749ce051340c6f3..e0bedaf37888e179f717654683419dee8020c8a0 100644 (file)
--- a/todo.py
+++ b/todo.py
@@ -5,6 +5,7 @@ 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 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'
 db_path = '/home/plom/org/todo_new.json'
 server_port = 8082
 DATE_FORMAT = '%Y-%m-%d'
@@ -12,12 +13,14 @@ j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates'))
 
 class Task:
 
 
 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.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):
         self.visible = True
 
     def _set_with_history(self, history, value):
@@ -30,13 +33,16 @@ class Task:
         return default if 0 == len(history) else history[keys[-1]]
 
     @classmethod
         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,
                db,
+               id_,
                d['title_history'],
                {k: set(v) for k, v in d['tags_history'].items()},
                d['default_effort_history'],
                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 {
 
     def to_dict(self):
         return {
@@ -44,6 +50,7 @@ class Task:
             '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()},
             '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
         }
 
     @property
@@ -66,6 +73,12 @@ class Task:
     def current_default_effort(self):
         return self.default_effort_at(self.db.selected_date)
 
     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, '')
     @property
     def title(self):
         return self._last_of_history(self.title_history, '')
@@ -102,47 +115,98 @@ class Task:
     def links(self, links):
         self._set_with_history(self.links_history, set(links))
 
     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:
 
 
 
 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.db = db
-        self.todos = todos if todos else {}
         self.comment = comment
         self.archived = True
         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
 
     @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 ''
         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):
         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
 
         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
 
     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
         return s
 
     @property
@@ -153,46 +217,77 @@ class Day:
     def todos_sum2(self):
         return self._todos_sum(True)
 
     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:
 
 
 
 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.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
         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):
 
     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 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:
         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):
 
     @property
     def title(self):
@@ -205,6 +300,42 @@ class Todo:
     def internals_empty(self):
         return len(self.comment) == 0 and len(self.day_tags) == 0
 
     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):
 
 
 class TodoDB(PlomDB):
 
@@ -218,20 +349,31 @@ class TodoDB(PlomDB):
         self.days = {}
         self.tasks = {}
         self.t_tags = set()
         self.days = {}
         self.tasks = {}
         self.t_tags = set()
+        self.todos = {}
         super().__init__(db_path)
 
     def read_db_file(self, f):
         d = json.load(f)
         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)
             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):
         self.set_visibilities()
 
     def set_visibilities(self):
@@ -239,46 +381,70 @@ class TodoDB(PlomDB):
             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())
             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):
 
     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 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
 
         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():
     @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():
         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):
                 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())
         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
 
         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' 
 
     def show_day(self, task_sort=None):
         task_sort = task_sort if task_sort else 'title' 
@@ -318,6 +484,38 @@ class TodoDB(PlomDB):
         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)
 
         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']
     def show_calendar(self, start_date_str, end_date_str):
         self.t_filter_and = ['calendar']
         self.t_filter_not = ['deleted']
@@ -338,29 +536,32 @@ class TodoDB(PlomDB):
             if end_date_str in {'today', 'yesterday'}:
                 end_date_obj = todays_date_obj if end_date_str == 'today' else yesterdays_date_obj
             else:
             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():
         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)
 
             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():
 
     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:
         if task_uuid in self.days[date].todos.keys():
             todo = self.days[date].todos[task_uuid]
         else:
@@ -378,31 +579,129 @@ class TodoDB(PlomDB):
             tags.add(tag)
         return tags
 
             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.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()
         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 = 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 
         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):
 
 
 class TodoHandler(PlomHandler):
@@ -426,21 +725,23 @@ class TodoHandler(PlomHandler):
 
     def write_db(self):
         from urllib.parse import urlencode
 
     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)
         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 = []
 
         def collect_checked(prefix, postvars):
             tags_checked = []
@@ -449,32 +750,105 @@ class TodoHandler(PlomHandler):
                     tags_checked += [k[len(prefix):]]
             return 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]
             id_ = postvars['id'][0]
-            params_to_encode += [('id', id_)]
+            redir_params += [('id', id_)]
             if 'title' in postvars.keys():
             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():
             # 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]
                 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():
 
                 # handle todo list updates via task UUIDs
                 if 't_uuid' in postvars.keys():
@@ -487,7 +861,7 @@ class TodoHandler(PlomHandler):
                             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]
                             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
                             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
@@ -496,11 +870,12 @@ class TodoHandler(PlomHandler):
                                 continue
                             db.update_todo_mini(uuid, db.selected_date, day_effort, done, importance)
 
                                 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:
         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)
 
         db.write()
         self.redirect(homepage)
 
@@ -509,69 +884,86 @@ class TodoHandler(PlomHandler):
         self.try_do(self.show_db)
 
     def show_db(self):
         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)
         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
 
         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)
             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:
             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:
                 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)
             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)
 
 
         self.send_HTML(page)
 
 
index 882c727c3c47b733502f11ac6a5990907c762ae7..80a90fb4da267e71d8e9cece8de1683958f46d04 100644 (file)
@@ -5,11 +5,13 @@ input { font-family: monospace; padding: 0em; margin: 0em; }
 {% endblock %}
 </style>
 <body>
 {% endblock %}
 </style>
 <body>
-tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day:
-<a href="{{db.prefix}}/day?hide_unchosen=0&hide_done=0">choose tasks</a>
-<a href="{{db.prefix}}/day?hide_unchosen=1&hide_done=1">do tasks</a>
-| <a href="{{db.prefix}}/calendar">calendar</a>
-| <a href="{{db.prefix}}/unset_cookie">unset cookie</a>
+tasks: <a href="tasks">list</a> <a href="add_task">add</a> | day:
+<a href="day?hide_unchosen=0&hide_done=0">choose tasks</a>
+<a href="day?hide_unchosen=1&hide_done=1">do tasks</a>
+<a href="do_day">do day</a>
+| <a href="calendar">calendar</a>
+| <a href="unset_cookie">unset cookie</a>
+| <a href="new_day">NEW</a>
 <hr />
 {% block content %}
 {% endblock %}
 <hr />
 {% block content %}
 {% endblock %}
index 5d49b5abc488df8e4a83ef94544d408ddeb08b33..1bfb88347cc4a75e27614f1c621400de003e5819 100644 (file)
@@ -1,7 +1,8 @@
 {% extends 'base.html' %}
 {% block css %}
 {% extends 'base.html' %}
 {% block css %}
+tr td { background-color: white; }
 tr.week_row td { height: 0.1em; background-color: black; }
 tr.week_row td { height: 0.1em; background-color: black; }
-tr.day_row td { background-color: #f2f2f2 }
+tr.day_row td { background-color: #cccccc }
 td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
 {% endblock %}
 {% block content %}
 td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
 {% endblock %}
 {% block content %}
@@ -14,11 +15,13 @@ to: <input name="end" {% if end_date %}value="{{ end_date }}"{% endif %} placeho
 <table>
 {% for date, day in days.items() | sort() %}
 {% if day.weekday == 'Mo' %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
 <table>
 {% for date, day in days.items() | sort() %}
 {% if day.weekday == 'Mo' %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
-<tr class="day_row"><td colspan=3><a href="{{db.prefix}}/day?selected_date={{date}}&hide_unchosen=1">{{ day.weekday }} {{ date }}</a> |{{ '%04.1f' % day.todos_sum|round(2) }}| {{ day.comment|e }}</td></tr>
-{% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
+<tr class="day_row"><td colspan=3><a href="do_day?date={{date}}&hide_unchosen=1">{{ day.weekday }} {{ date }}</a> |{{ '%04.1f' % day.todos_sum|round(2) }}| {{ day.comment|e }}</td></tr>
+{% for todo in day.linked_todos_as_list %}
+
 {% if todo.visible %}
 {% if todo.visible %}
-<tr><td class="checkbox">{% if todo.done %}✓{% else %}&nbsp;&nbsp;{% endif %}</td><td><a href="{{db.prefix}}/todo?task={{ todo.task.id_ }}&date={{ date }}">{%if "cancelled" in todo.tags%}<s>{% endif %}{% if "deadline" in todo.tags %}DEADLINE: {% endif %}{{ todo.title|e }}{%if "cancelled" in todo.tags%}</s>{% endif %}</a></td><td>{{ todo.comment|e }}</td></tr>
+<tr><td class="checkbox">{% if todo.done and not "cancelled" in todo.tags%}✓{% else %}&nbsp;&nbsp;{% endif %}</td><td><a href="{{db.prefix}}/todo?id={{todo.id_}}">{% if "cancelled" in todo.tags %}<s>{% endif %}{% if "deadline" in todo.tags %}DEADLINE: {% endif %}{{ todo.title|e }}{%if "cancelled" in todo.tags%}</s>{% endif %}</a></td><td>{{ todo.comment|e }}</td></tr>
 {% endif %}
 {% endif %}
+
 {% endfor %}
 {% endfor %}
 </table>
 {% endfor %}
 {% endfor %}
 </table>
index 6231aea24b5b75f2e4a22d8af44d37373b4f9509..05b5fd7d2b46afb12f3b9d4113c898ea42132f85 100644 (file)
@@ -1,7 +1,7 @@
 {% extends 'base.html' %}
 {% block css %}
 table.alternating tr:nth-child(even) {
 {% extends 'base.html' %}
 {% block css %}
 table.alternating tr:nth-child(even) {
-    background-color: #e2e2e2;
+    background-color: #cccccc;
 }
 table.alternating tr:nth-child(odd) {
     background-color: #ffffff;
 }
 table.alternating tr:nth-child(odd) {
     background-color: #ffffff;
index b0ed3e8b115f9f195ef1eb1fb5fff7e3e8c7f553..e752b2718a7e47e516366ae7c82fddbf510e9b2d 100644 (file)
@@ -14,6 +14,8 @@ textarea { width: 100% };
 <input type="hidden" name="referer" value="{{ referer }}" />
 <table>
 <tr><th>title</th><td class="input"><input name="title" type="text" value="{{ task.title|e }}" /><details><summary>history</summary><ul>{% for k,v in task.title_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
 <input type="hidden" name="referer" value="{{ referer }}" />
 <table>
 <tr><th>title</th><td class="input"><input name="title" type="text" value="{{ task.title|e }}" /><details><summary>history</summary><ul>{% for k,v in task.title_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
+<tr><th></th><td><input type="checkbox" name="as_todo" {% if selected %}checked{% endif%}> selected for {{db.selected_date}}</td></tr>
+<tr><th>comment</th><td class="input"><textarea name="comment">{{task.comment|e}}</textarea></td></tr>
 <tr><th>default effort</th><td class="input"><input type="number" name="default_effort" value="{{ task.default_effort }}" step=0.1 size=8 required /><details><summary>history</summary><ul>{% for k,v in task.default_effort_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
 <tr><th>tags</th>
 <td>
 <tr><th>default effort</th><td class="input"><input type="number" name="default_effort" value="{{ task.default_effort }}" step=0.1 size=8 required /><details><summary>history</summary><ul>{% for k,v in task.default_effort_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
 <tr><th>tags</th>
 <td>
index 7d245dc9aba46139f8889c61eb6895eb988de9e1..7943b8231eb233630ac3871f0687186960ba8a89 100644 (file)
@@ -1,12 +1,13 @@
 {% extends 'base.html' %}
 {% block css %}
 table.alternating tr:nth-child(even) {
 {% extends 'base.html' %}
 {% block css %}
 table.alternating tr:nth-child(even) {
-    background-color: #e2e2e2;
+    background-color: #cccccc;
 }
 table.alternating tr:nth-child(odd) {
     background-color: #ffffff;
 }
 td.number { text-align: right; }
 }
 table.alternating tr:nth-child(odd) {
     background-color: #ffffff;
 }
 td.number { text-align: right; }
+tr.expanded { color: #888888; }
 {% endblock %}
 {% block content %}
 <form action="{{action|e}}" method="POST">
 {% endblock %}
 {% block content %}
 <form action="{{action|e}}" method="POST">
@@ -14,14 +15,35 @@ td.number { text-align: right; }
 </form>
 <table class="alternating">
 <tr><th>default<br />effort</th><th>task</th><th>tags</th></tr>
 </form>
 <table class="alternating">
 <tr><th>default<br />effort</th><th>task</th><th>tags</th></tr>
+
 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
 {% if t.visible %}
 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
 {% if t.visible %}
+
 <tr>
 <td class="number">{{ t.default_effort }}</a></td>
 <tr>
 <td class="number">{{ t.default_effort }}</a></td>
-<td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
+<td>
+{% if uuid == expand_uuid %}
+<a href="{{db.prefix}}/tasks">[-]</a>
+{% elif t.links|count > 0 %}
+<a href="{{db.prefix}}/tasks?expand_uuid={{uuid}}">[+]</a>
+{% endif %}
+<a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
+<td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tasks?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
+</tr>
+
+{% if uuid == expand_uuid %}
+{% for uuid, t in expanded_tasks.items() %}
+<tr class="expanded">
+<td class="number">{{ t.default_effort }}</a></td>
+<td>&nbsp; [+] <a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tasks?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tasks?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
+</tr>
+{% endfor %}
+{% endif %}
+
 {% endif %}
 {% endfor %}
 {% endif %}
 {% endfor %}
+
 </table>
 {% endblock %}
 
 </table>
 {% endblock %}
 
index af48a478186816d3857538ff19ff3f5a0c674e83..09aaf452bb260db264624f58b8460113b43695ad 100644 (file)
@@ -8,16 +8,32 @@ input[type="text"] { width: 100% }
 textarea { width: 100% };
 {% endblock %}
 {% block content %}
 textarea { width: 100% };
 {% endblock %}
 {% block content %}
-<form action="{{action|e}}" method="POST">
+<form action="todo" method="POST">
 <h3>edit todo</h3>
 <h3>edit todo</h3>
-<input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
-<input type="hidden" name="date" value="{{ todo.day.date }}" />
-<input type="hidden" name="referer" value="{{ referer }}" />
+<input type="hidden" name="todo_id" value="{{todo.id_}}" />
+<input type="hidden" name="return_to" value="{{return_to}}" />
 <table>
 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
 <tr><th>default effort</th><td>{{ todo.default_effort }}</td></tr>
 <table>
 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
 <tr><th>default effort</th><td>{{ todo.default_effort }}</td></tr>
-<tr><th>day</th><td>{{ todo.day.date }}</td></tr>
-<tr><th>day effort</th><td class="input"><input type="number" name="day_effort" step=0.1 size=8 value="{{ todo.day_effort }}" /></td></tr>
+<tr>
+<th>efforts</th>
+<td>
+<table>
+<tr><th>date</th><th>effort</th><th>delete</th>
+{% for date, effort in todo.efforts.items() %}
+<tr>
+<td><input name="effort_date" size=10 value="{{date}}"></td>
+<td><input type="number" name="effort" step=0.1 size=8 value="{{effort}}" placeholder="{{todo.default_effort}}" /></td>
+<td><input type="checkbox" name="delete_effort" value="{{date}}" />
+</tr>
+{% endfor %}
+<tr>
+<td><input name="effort_date" size=10 value=""></td>
+<td><input type="number" name="effort" step=0.1 size=8 value="" placeholder="{{todo.default_effort}}" /></td>
+</tr>
+</table>
+</td>
+</tr>
 <tr><th>importance</th><td class="input"><input type="number" name="importance" step=0.1 size=8 value="{{ todo.importance }}" /></td></tr>
 <tr><th>comment</th><td class="input"><textarea name="comment">{{todo.comment|e}}</textarea></td></tr>
 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
 <tr><th>importance</th><td class="input"><input type="number" name="importance" step=0.1 size=8 value="{{ todo.importance }}" /></td></tr>
 <tr><th>comment</th><td class="input"><textarea name="comment">{{todo.comment|e}}</textarea></td></tr>
 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
@@ -31,5 +47,8 @@ add: <input name="joined_day_tags" type="text" value="" >
 </tr>
 </table>
 <input type="submit" value="update" />
 </tr>
 </table>
 <input type="submit" value="update" />
+<div style="text-align: right">
+<input type="submit" name="delete" value="delete" />
+</div>
 </form>
 {% endblock %}
 </form>
 {% endblock %}