-
-class LedgerServer(PlomServer):
-
- def pre_init(self):
- self.html_head += [html_head]
-
- def do_POST(self):
- try:
- parsed_url = urlparse(self.path)
- length = int(self.headers['content-length'])
- postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
- start = int(postvars['start'][0])
- end = int(postvars['end'][0])
- db = LedgerDB()
- add_empty_line = None
- lines = []
- # get inputs
- if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
- lines, add_empty_line = self.booking_lines_from_postvars(postvars, db)
- elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
- lines = postvars['booking'][0].splitlines()
- # validate where appropriate
- if ('save' in postvars.keys()) or ('check' in postvars.keys()):
- _, _ = parse_lines(lines)
- # if saving, process where to and where to redirect after
- if 'save' in postvars.keys():
- last_date = str(datetime.now())[:10]
- if len(db.bookings) > 0:
- last_date = db.bookings[-1].date_string
- target_date = last_date[:]
- first_line_tokens = lines[0].split() if len(lines) > 0 else ''
- first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
- try:
- datetime.strptime(first_token, '%Y-%m-%d')
- target_date = first_token
- except ValueError:
- pass
- if start == end == 0:
- start = db.insert_at_date(lines, target_date)
- nth = db.get_nth_for_booking_of_start_line(start)
- else:
- new_start = db.update(start, end, lines, target_date)
- nth = db.get_nth_for_booking_of_start_line(new_start)
- if new_start > start:
- nth -= 1
- self.redirect( f'/#{nth}')
- # otherwise just re-build editing form
- else:
- if '/add_structured' == parsed_url.path:
- edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
- else:
- edit_content = self.add_free(db, start, end)
- self.send_HTML(edit_content)
- except PlomException as e:
- self.fail_400(e)
-
- def do_GET(self):
- try:
- parsed_url = urlparse(self.path)
- params = parse_qs(parsed_url.query)
- start = int(params.get('start', ['0'])[0])
- end = int(params.get('end', ['0'])[0])
- db = LedgerDB()
- if parsed_url.path == '/balance':
- stop = params.get('stop', [None])[0]
- page = self.balance_as_html(db, stop)
- elif parsed_url.path == '/add_free':
- page = self.add_free(db, start, end)
- elif parsed_url.path == '/add_structured':
- page = self.add_structured(db, start, end)
- elif parsed_url.path == '/copy_free':
- page = self.add_free(db, start, end, copy=True)
- elif parsed_url.path == '/copy_structured':
- page = self.add_structured(db, start, end, copy=True)
- elif parsed_url.path == '/move_up':
- nth = self.move_up(db, start, end)
- self.redirect(f'/#{nth}')
- return
- elif parsed_url.path == '/move_down':
- nth = self.move_down(db, start, end)
- self.redirect(f'/#{nth}')
- return
- else:
- page = self.ledger_as_html(db)
- self.send_HTML(page)
- except PlomException as e:
- self.fail_400(e)
-
- def booking_lines_from_postvars(self, postvars, db):
- add_empty_line = None
- date = postvars['date'][0]
- description = postvars['description'][0]
- start_comment = postvars['line_0_comment'][0]
- start_line = f'{date} {description}'
- if start_comment.rstrip() != '':
- start_line += f' ; {start_comment}'
- lines = [start_line]
- if 'line_0_add' in postvars.keys():
- add_empty_line = 0
- i = j = 1
- while f'line_{i}_comment' in postvars.keys():
- if f'line_{i}_delete' in postvars.keys():
- i += 1
- continue
- elif f'line_{i}_delete_after' in postvars.keys():
- break
- elif f'line_{i}_add' in postvars.keys():
- add_empty_line = j
- account = postvars[f'line_{i}_account'][0]
- amount = postvars[f'line_{i}_amount'][0]
- currency = postvars[f'line_{i}_currency'][0]
- comment = postvars[f'line_{i}_comment'][0]
- i += 1
- new_main = f' {account} {amount}'
- if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
- continue
- if len(amount.rstrip()) > 0:
- new_main += f' {currency}'
- j += 1
- new_line = new_main
- if comment.rstrip() != '':
- new_line += f' ; {comment}'
- lines += [new_line]
- if 'add_sink' in postvars.keys():
- temp_lines = lines.copy() + ['_']
- try:
- temp_bookings, _ = parse_lines(temp_lines)
- for currency in temp_bookings[0].sink:
- amount = temp_bookings[0].sink[currency]
- lines += [f'Assets {amount:.2f} {currency}']
- except PlomException:
- pass
- if 'add_taxes' in postvars.keys():
- lines += db.add_taxes(lines, finish=False)
- elif 'add_taxes2' in postvars.keys():
- lines += db.add_taxes(lines, finish=True)
- return lines, add_empty_line
-
- def balance_as_html(self, db, until=None):
- bookings = db.bookings[:until if until is None else int(until)]
- lines = []
- account_tree, account_sums = bookings_to_account_tree(bookings)
- def print_subtree(lines, indent, node, subtree, path):
- line = f"{indent}{node}"
- n_tabs = 5 - (len(line) // 8)
- line += n_tabs * "\t"
- if "€" in account_sums[path + node].keys():
- amount = account_sums[path + node]["€"]
- line += f"{amount:9.2f} €\t"
- else:
- line += f"\t\t"
- for currency, amount in account_sums[path + node].items():
- if currency != '€' and amount > 0:
- line += f"{amount:5.2f} {currency}\t"
- lines += [line]
- indent += " "
- for k, v in sorted(subtree.items()):
- print_subtree(lines, indent, k, v, path + node + ":")
- for k, v in sorted(account_tree.items()):
- print_subtree(lines, "", k, v, "")
- content = "\n".join(lines)
- return f"<pre>{content}</pre>"
-
- def ledger_as_html(self, db):