1 from http.server import BaseHTTPRequestHandler, HTTPServer
6 from urllib.parse import parse_qs, urlparse
11 class HandledException(Exception):
15 def handled_error_exit(msg):
16 print(f"ERROR: {msg}")
20 def apply_booking_to_account_balances(account_sums, account, currency, amount):
21 if not account in account_sums:
22 account_sums[account] = {currency: amount}
23 elif not currency in account_sums[account].keys():
24 account_sums[account][currency] = amount
26 account_sums[account][currency] += amount
31 bookings, _ = parse_lines(lines)
32 _, account_sums = bookings_to_account_tree(bookings)
33 expenses_so_far = -1 * account_sums['Assets']['€']
34 needed_income_before_krankenkasse = expenses_so_far
36 left_over = needed_income_before_krankenkasse - ESt_this_month
38 too_high = 2 * needed_income_before_krankenkasse
44 zvE = 12 * needed_income_before_krankenkasse
46 ESt = decimal.Decimal(0)
49 ESt = (decimal.Decimal(979.18) * y + 1400) * y
52 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
54 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
56 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
57 ESt_this_month = ESt / 12
58 left_over = needed_income_before_krankenkasse - ESt_this_month
59 if abs(left_over - expenses_so_far) < 0.1:
61 elif left_over < expenses_so_far:
62 too_low = needed_income_before_krankenkasse
63 elif left_over > expenses_so_far:
64 too_high = needed_income_before_krankenkasse
65 needed_income_before_krankenkasse = too_low + (too_high - too_low)/2
66 line_income_tax = f' Reserves:Einkommenssteuer {ESt_this_month:.2f}€ ; expenses so far: {expenses_so_far:.2f}€; zvE: {zvE:.2f}€; ESt total: {ESt:.2f}€; needed before Krankenkasse: {needed_income_before_krankenkasse:.2f}€'
67 kk_minimum_income = 1096.67
68 kk_factor = decimal.Decimal(0.189)
69 kk_minimum_tax = decimal.Decimal(207.27)
70 # kk_minimum_income = 1131.67
71 # kk_factor = decimal.Decimal(0.191)
72 # kk_minimum_tax = decimal.Decimal(216.15)
73 # kk_factor = decimal.Decimal(0.197)
74 # kk_minimum_tax = decimal.Decimal(222.94)
75 kk_add = max(0, kk_factor * needed_income_before_krankenkasse - kk_minimum_tax)
76 line_kk_minimum = f' Reserves:Month:Krankenkassendefaultbeitrag {kk_minimum_tax:.2f}€ ; assed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}'
77 line_kk_add = f' Reserves:Month:Krankenkassenbeitragswachstum {kk_add:.2f}€ ; max(0, {kk_factor:.3f} * {needed_income_before_krankenkasse:.2f}€ - {kk_minimum_tax:.2f}€)'
78 final_minus = expenses_so_far + ESt_this_month + kk_minimum_tax + kk_add
79 line_finish = f' Assets -{final_minus:.2f}€'
80 return [line_income_tax, line_kk_minimum, line_kk_add, line_finish]
83 def bookings_to_account_tree(bookings):
85 for booking in bookings:
86 for account, changes in booking.account_changes.items():
87 for currency, amount in changes.items():
88 apply_booking_to_account_balances(account_sums, account, currency, amount)
90 def collect_branches(account_name, path):
93 while len(path_copy) > 0:
94 step = path_copy.pop(0)
96 toks = account_name.split(":", maxsplit=1)
98 if parent in node.keys():
104 k, v = collect_branches(toks[1], path + [parent])
105 if k not in child.keys():
110 for account_name in sorted(account_sums.keys()):
111 k, v = collect_branches(account_name, [])
112 if k not in account_tree.keys():
115 account_tree[k].update(v)
116 def collect_totals(parent_path, tree_node):
117 for k, v in tree_node.items():
118 child_path = parent_path + ":" + k
119 for currency, amount in collect_totals(child_path, v).items():
120 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
121 return account_sums[parent_path]
122 for account_name in account_tree.keys():
123 account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
124 return account_tree, account_sums
127 def parse_lines(lines):
130 inside_booking = False
131 date_string, description = None, None
136 lines = lines.copy() + [''] # to ensure a booking-ending last line
137 for i, line in enumerate(lines):
139 # we start with the case of an utterly empty line
141 stripped_line = line.rstrip()
142 if stripped_line == '':
144 # assume we finished a booking, finalize, and commit to DB
145 if len(booking_lines) < 2:
146 raise HandledException(f"{prefix} booking ends to early")
147 booking = Booking(date_string, description, booking_lines, start_line)
148 bookings += [booking]
149 # expect new booking to follow so re-zeroall booking data
150 inside_booking = False
151 date_string, description = None, None
154 # if non-empty line, first get comment if any, and commit to DB
155 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
156 if len(split_by_comment) == 2:
157 comments[i] = split_by_comment[1].lstrip()
158 # if pre-comment empty: if inside_booking, this must be a comment-only line so we keep it for later ledger-output to capture those comments; otherwise, no more to process for this line
159 non_comment = split_by_comment[0].rstrip()
160 if non_comment.rstrip() == '':
162 booking_lines += ['']
164 # if we're starting a booking, parse by first-line pattern
165 if not inside_booking:
167 toks = non_comment.split(maxsplit=1)
168 date_string = toks[0]
170 datetime.datetime.strptime(date_string, '%Y-%m-%d')
172 raise HandledException(f"{prefix} bad date string: {date_string}")
174 description = toks[1]
176 raise HandledException(f"{prefix} bad description: {description}")
177 inside_booking = True
178 booking_lines += [non_comment]
180 # otherwise, read as transfer data
181 toks = non_comment.split() # ignore specification's allowance of single spaces in names
183 raise HandledException(f"{prefix} too many booking line tokens: {toks}")
184 amount, currency = None, None
185 account_name = toks[0]
186 if account_name[0] == '[' and account_name[-1] == ']':
187 # ignore specification's differentiation of "virtual" accounts
188 account_name = account_name[1:-1]
189 decimal_chars = ".-0123456789"
193 amount = decimal.Decimal(toks[1])
195 except decimal.InvalidOperation:
197 amount = decimal.Decimal(toks[2])
198 except decimal.InvalidOperation:
199 raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
200 currency = toks[i_currency]
201 if currency[0] in decimal_chars:
202 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
205 inside_amount = False
206 inside_currency = False
210 for i, c in enumerate(value):
212 if c in decimal_chars:
215 inside_currency = True
217 if c in decimal_chars and len(amount_string) == 0:
218 inside_currency = False
224 if c not in decimal_chars:
225 if len(currency) > 0:
226 raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
227 inside_currency = True
228 inside_amount = False
231 if c == '-' and len(amount_string) > 1:
232 raise HandledException(f"{prefix} amount has non-start '-': {value}")
235 raise HandledException(f"{prefix} amount has multiple dots: {value}")
238 if len(amount_string) == 0:
239 raise HandledException(f"{prefix} amount missing: {value}")
240 if len(currency) == 0:
241 raise HandledException(f"{prefix} currency missing: {value}")
242 amount = decimal.Decimal(amount_string)
243 booking_lines += [(account_name, amount, currency)]
245 raise HandledException(f"{prefix} last booking unfinished")
246 return bookings, comments
251 def __init__(self, date_string, description, booking_lines, start_line):
252 self.date_string = date_string
253 self.description = description
254 self.lines = booking_lines
255 self.start_line = start_line
256 self.validate_booking_lines()
257 self.account_changes = self.parse_booking_lines_to_account_changes()
259 def validate_booking_lines(self):
260 prefix = f"booking at line {self.start_line}"
263 for line in self.lines[1:]:
266 _, amount, currency = line
269 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
272 if currency not in sums:
274 sums[currency] += amount
275 if empty_values == 0:
276 for k, v in sums.items():
278 raise HandledException(f"{prefix} does not sum up to zero")
281 for k, v in sums.items():
285 raise HandledException(f"{prefix} has empty value that cannot be filled")
287 def parse_booking_lines_to_account_changes(self):
291 for line in self.lines[1:]:
294 account, amount, currency = line
296 sink_account = account
298 apply_booking_to_account_balances(account_changes, account, currency, amount)
299 if currency not in debt:
300 debt[currency] = amount
302 debt[currency] += amount
304 for currency, amount in debt.items():
305 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
306 return account_changes
314 self.db_file = db_name + ".json"
315 self.lock_file = db_name+ ".lock"
319 if os.path.exists(self.db_file):
320 with open(self.db_file, "r") as f:
321 self.real_lines += [l.rstrip() for l in f.readlines()]
322 ret = parse_lines(self.real_lines)
323 self.bookings += ret[0]
324 self.comments += ret[1]
326 def get_lines(self, start, end):
327 return self.real_lines[start:end]
329 def replace(self, start, end, lines):
331 if os.path.exists(self.lock_file):
332 raise HandledException('Sorry, lock file!')
333 if os.path.exists(self.db_file):
334 shutil.copy(self.db_file, self.db_file + ".bak")
335 f = open(self.lock_file, 'w+')
337 total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
338 text = '\n'.join(total_lines)
339 # text = '\n'.join(self.real_lines[:start]) + '\n'.join(lines) + '\n'.join(self.real_lines[end:])
340 with open(self.db_file, 'w') as f:
342 os.remove(self.lock_file)
344 def append(self, lines):
346 if os.path.exists(self.lock_file):
347 raise HandledException('Sorry, lock file!')
348 if os.path.exists(self.db_file):
349 shutil.copy(self.db_file, self.db_file + ".bak")
350 f = open(self.lock_file, 'w+')
352 with open(self.db_file, 'a') as f:
353 f.write('\n\n' + '\n'.join(lines) + '\n\n');
354 os.remove(self.lock_file)
357 class MyServer(BaseHTTPRequestHandler):
359 <meta charset="UTF-8">
361 body { color: #000000; }
362 table { margin-bottom: 2em; }
363 th, td { text-align: left }
364 input[type=number] { text-align: right; font-family: monospace; }
365 .money { font-family: monospace; text-align: right; }
366 .comment { font-style: italic; color: #777777; }
367 .full_line_comment { display: block; white-space: nowrap; width: 0; }
370 <a href="/ledger">ledger</a>
371 <a href="/balance">balance</a>
372 <a href="/add_free">add free</a>
373 <a href="/add_structured">add structured</a>
376 footer = "</body>\n<html>"
380 length = int(self.headers['content-length'])
381 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
382 parsed_url = urlparse(self.path)
384 add_empty_line = None
385 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
386 date = postvars['date'][0]
387 description = postvars['description'][0]
388 start_comment = postvars['line_0_comment'][0]
389 lines = [f'{date} {description} ; {start_comment}']
390 if 'line_0_add' in postvars.keys():
393 while f'line_{i}_comment' in postvars.keys():
394 if f'line_{i}_delete' in postvars.keys():
397 if f'line_{i}_add' in postvars.keys():
399 account = postvars[f'line_{i}_account'][0]
400 amount = postvars[f'line_{i}_amount'][0]
401 currency = postvars[f'line_{i}_currency'][0]
402 comment = postvars[f'line_{i}_comment'][0]
404 new_main = f'{account} {amount} {currency}'
405 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines
409 if comment.rstrip() != '':
410 new_line += f' ; {comment}'
412 if 'add_taxes' in postvars.keys():
413 lines += add_taxes(lines)
414 elif '/add_free' == parsed_url.path:
415 lines = postvars['booking'][0].splitlines()
416 lines += [''] # to ensure Booking-ending last line
417 start = int(postvars['start'][0])
418 end = int(postvars['end'][0])
420 _, _ = parse_lines(lines)
421 if 'save' in postvars.keys():
422 if start == end == 0:
425 db.replace(start, end, lines)
426 self.send_response(301)
428 self.send_header('Location', redir_url)
431 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
432 self.send_response(200)
433 self.send_header("Content-type", "text/html")
435 self.wfile.write(bytes(page, "utf-8"))
436 except HandledException as e:
437 self.send_response(400)
438 self.send_header("Content-type", "text/html")
440 page = f'{self.header}ERROR: {e}{self.footer}'
441 self.wfile.write(bytes(page, "utf-8"))
444 self.send_response(200)
445 self.send_header("Content-type", "text/html")
448 parsed_url = urlparse(self.path)
449 page = self.header + ''
450 params = parse_qs(parsed_url.query)
451 start = int(params.get('start', ['0'])[0])
452 end = int(params.get('end', ['0'])[0])
453 if parsed_url.path == '/balance':
454 page += self.balance_as_html(db)
455 elif parsed_url.path == '/add_free':
456 page += self.add_free(db, start, end)
457 elif parsed_url.path == '/add_structured':
458 page += self.add_structured(db, start, end)
459 elif parsed_url.path == '/copy_free':
460 page += self.add_free(db, start, end, copy=True)
461 elif parsed_url.path == '/copy_structured':
462 page += self.add_structured(db, start, end, copy=True)
464 page += self.ledger_as_html(db)
466 self.wfile.write(bytes(page, "utf-8"))
468 def balance_as_html(self, db):
470 account_tree, account_sums = bookings_to_account_tree(db.bookings)
471 def print_subtree(lines, indent, node, subtree, path):
472 line = f"{indent}{node}"
473 n_tabs = 5 - (len(line) // 8)
474 line += n_tabs * "\t"
475 if "€" in account_sums[path + node].keys():
476 amount = account_sums[path + node]["€"]
477 line += f"{amount:9.2f} €\t"
480 for currency, amount in account_sums[path + node].items():
481 if currency != '€' and amount > 0:
482 line += f"{amount:5.2f} {currency}\t"
485 for k, v in sorted(subtree.items()):
486 print_subtree(lines, indent, k, v, path + node + ":")
487 for k, v in sorted(account_tree.items()):
488 print_subtree(lines, "", k, v, "")
489 content = "\n".join(lines)
490 return f"<pre>{content}</pre>"
492 def ledger_as_html(self, db):
493 single_c_tmpl = jinja2.Template('<span class="comment">{{c}}</span><br />')
494 booking_tmpl = jinja2.Template("""
495 <p>{{date}} {{desc}} <span class="comment">{{head_comment}}</span>
496 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
497 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
498 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
499 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
501 {% for l in booking_lines %}
503 <tr><td>{{l.acc}}</td><td class="money">{{l.money}}</td><td class="comment">{{l.comment}}</td></tr>
505 <tr><td><div class="comment full_line_comment">{{l.comment}}</div></td></tr>
510 elements_to_write = []
512 for booking in db.bookings:
513 i = booking.start_line
514 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']
515 booking_end = last_i = booking.start_line + len(booking.lines)
517 for booking_line in booking.lines[1:]:
519 comment = db.comments[i]
520 if booking_line == '':
521 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
525 money = f'{booking_line[1]} {booking_line[2]}'
526 account = booking_line[0]
527 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]
528 elements_to_write += [booking_tmpl.render(
529 start=booking.start_line,
531 date=booking.date_string,
532 desc=booking.description,
533 head_comment=db.comments[booking.start_line],
534 booking_lines = booking_lines)]
535 return '\n'.join(elements_to_write)
537 def add_free(self, db, start=0, end=0, copy=False):
538 tmpl = jinja2.Template("""
539 <form method="POST" action="{{action}}">
540 <textarea name="booking" rows=10 cols=80>
541 {% for line in lines %}{{ line }}
544 <input type="hidden" name="start" value={{start}} />
545 <input type="hidden" name="end" value={{end}} />
546 <input type="submit" name="save" value="save!">
549 lines = db.get_lines(start, end)
552 return tmpl.render(start=start, end=end, lines=lines)
554 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
555 tmpl = jinja2.Template("""
556 <form method="POST" action="{{action}}">
557 <input type="submit" name="check" value="check" />
558 <input type="submit" name="revert" value="revert" />
559 <input type="submit" name="add_taxes" value="add taxes" />
561 <input name="date" value="{{date}}" size=9 />
562 <input name="description" value="{{desc}}" list="descriptions" />
563 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment}}</textarea>
564 <input type="submit" name="line_0_add" value="[+]" />
566 {% for line in booking_lines %}
567 <input name="line_{{line.i}}_account" value="{{line.acc}}" size=40 list="accounts" />
568 <input type="number" name="line_{{line.i}}_amount" value="{{line.amt}}" size=10 />
569 <input name="line_{{line.i}}_currency" value="{{line.curr}}" size=3 list="currencies" />
570 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment}}</textarea>
571 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
572 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
575 {% for name, items in datalist_sets.items() %}
576 <datalist id="{{name}}">
577 {% for item in items %}
578 <option value="{{item}}">{{item}}</option>
582 <input type="hidden" name="start" value={{start}} />
583 <input type="hidden" name="end" value={{end}} />
584 <input type="submit" name="save" value="save!">
588 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
589 bookings, comments = parse_lines(lines)
590 if len(bookings) > 1:
591 raise HandledException('can only edit single Booking')
592 if add_empty_line is not None:
593 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
594 booking = bookings[0]
595 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
596 action = 'add_structured'
597 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
598 for b in db.bookings:
599 datalist_sets['descriptions'].add(b.description)
600 for account, moneys in b.account_changes.items():
601 datalist_sets['accounts'].add(account)
602 for currency in moneys.keys():
603 datalist_sets['currencies'].add(currency)
605 today = str(datetime.datetime.now())[:10]
609 desc = head_comment = ''
610 if len(bookings) == 0:
611 for i in range(1, 3):
612 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
615 booking = bookings[0]
616 desc = booking.description
617 date = today if copy else booking.date_string
618 head_comment=comments[0]
619 last_line = len(comments)
620 for i in range(1, len(comments)):
621 account = amount = currency = ''
622 if i < len(booking.lines) and booking.lines[i] != '':
623 account = booking.lines[i][0]
624 amount = booking.lines[i][1]
625 currency = booking.lines[i][2]
630 'curr': currency if currency else '',
631 'comment': comments[i],
632 'comm_cols': len(comments[i])}]
633 content += tmpl.render(
637 head_comment=head_comment,
638 booking_lines=booking_lines,
639 datalist_sets=datalist_sets,
645 if __name__ == "__main__":
646 webServer = HTTPServer((hostName, serverPort), MyServer)
647 print(f"Server started http://{hostName}:{serverPort}")
649 webServer.serve_forever()
650 except KeyboardInterrupt:
652 webServer.server_close()
653 print("Server stopped.")