-
-class MyServer(BaseHTTPRequestHandler):
- header = """<html>
-<meta charset="UTF-8">
-<style>
-body { color: #000000; }
-table { margin-bottom: 2em; }
-th, td { text-align: left }
-input[type=number] { text-align: right; font-family: monospace; }
-.money { font-family: monospace; text-align: right; }
-.comment { font-style: italic; color: #777777; }
-.meta { font-size: 0.75em; color: #777777; }
-.full_line_comment { display: block; white-space: nowrap; width: 0; }
-</style>
-<body>
-<a href="/">ledger</a>
-<a href="/balance">balance</a>
-<a href="/add_free">add free</a>
-<a href="/add_structured">add structured</a>
-<hr />
-"""
- booking_tmpl = jinja2.Template("""
-<p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
-<span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
-/ <a href="/add_free?start={{start}}&end={{end}}">free</a>
-| copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
-/ <a href="/copy_free?start={{start}}&end={{end}}">free</a>
-| <a href="/balance?stop={{nth+1}}">balance after</a>
-]</span>
-<table>
-{% for l in booking_lines %}
-{% if l.acc %}
-<tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
-{% else %}
-<tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
-{% endif %}
-{% endfor %}
-</table></p>
-""")
- add_form_footer = """
-<input type="hidden" name="start" value={{start}} />
-<input type="hidden" name="end" value={{end}} />
-<input type="submit" name="save" value="save!">
-</form>
-"""
- footer = "</body>\n<html>"
-
- 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 = Database()
- add_empty_line = None
- lines = []
- if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
- date = postvars['date'][0]
- description = postvars['description'][0]
- start_comment = postvars['line_0_comment'][0]
- lines = [f'{date} {description} ; {start_comment}']
- 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 HandledException:
- 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)
- elif '/add_free' == parsed_url.path:
- lines = postvars['booking'][0].splitlines()
-
- if ('save' in postvars.keys()) or ('check' in postvars.keys()):
- _, _ = parse_lines(lines)
-
- if 'save' in postvars.keys():
- if start == end == 0:
- db.append(lines)
- redir_url = f'/#last'
- else:
- db.replace(start, end, lines)
- nth = 0
- for i, b in enumerate(db.bookings):
- if b.start_line == start:
- nth = i
- break
- redir_url = f'/#{nth}'
- self.send_code_and_headers(301, [('Location', redir_url)])
- else: # implicit assumption: this only happens on /add_structured flows
- page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
- self.send_HTML(page)
- except HandledException 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 = Database()
- page = self.header
- 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)
- else:
- page += self.ledger_as_html(db)
- page += self.footer
- self.send_HTML(page)
- except HandledException as e:
- self.fail_400(e)
-
- def fail_400(self, e):
- page = f'{self.header}ERROR: {e}{self.footer}'
- self.send_HTML(page, 400)
-
- def send_HTML(self, html, code=200):
- self.send_code_and_headers(code, [('Content-type', 'text/html')])
- self.wfile.write(bytes(html, "utf-8"))
-
- def send_code_and_headers(self, code, headers=[]):
- self.send_response(code)
- for fieldname, content in headers:
- self.send_header(fieldname, content)
- self.end_headers()
-
- 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):