1 from http.server import BaseHTTPRequestHandler, HTTPServer
7 from urllib.parse import parse_qs, urlparse
12 class HandledException(Exception):
16 def handled_error_exit(msg):
17 print(f"ERROR: {msg}")
21 def apply_booking_to_account_balances(account_sums, account, currency, amount):
22 if not account in account_sums:
23 account_sums[account] = {currency: amount}
24 elif not currency in account_sums[account].keys():
25 account_sums[account][currency] = amount
27 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
39 E0 = decimal.Decimal(10908)
40 E1 = decimal.Decimal(15999)
41 E2 = decimal.Decimal(62809)
42 E3 = decimal.Decimal(277825)
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.001:
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 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
67 line_income_tax = f' Reserves:Einkommenssteuer {ESt_this_month}€ ; expenses so far: {expenses_so_far:.2f}€; zvE: {zvE:.2f}€; ESt total: {ESt:.2f}€; needed before Krankenkasse: {needed_income_before_krankenkasse:.2f}€'
68 kk_minimum_income = decimal.Decimal(1096.67)
69 kk_factor = decimal.Decimal(0.189)
70 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
71 # kk_minimum_income = 1131.67
72 # kk_factor = decimal.Decimal(0.191)
73 # kk_minimum_tax = decimal.Decimal(216.15)
74 # kk_factor = decimal.Decimal(0.197)
75 # kk_minimum_tax = decimal.Decimal(222.94)
76 kk_add = max(0, kk_factor * needed_income_before_krankenkasse - kk_minimum_tax)
77 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
78 line_kk_minimum = f' Reserves:Month:Krankenkassendefaultbeitrag {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}'
79 line_kk_add = f' Reserves:Month:Krankenkassenbeitragswachstum {kk_add}€ ; max(0, {kk_factor:.3f} * {needed_income_before_krankenkasse:.2f}€ - {kk_minimum_tax}€)'
80 final_minus = expenses_so_far + ESt_this_month + kk_minimum_tax + kk_add
81 line_finish = f' Assets -{ESt_this_month + kk_minimum_tax + kk_add} € ; -{final_minus}€'
82 return [line_income_tax, line_kk_minimum, line_kk_add, line_finish]
85 def bookings_to_account_tree(bookings):
87 for booking in bookings:
88 for account, changes in booking.account_changes.items():
89 for currency, amount in changes.items():
90 apply_booking_to_account_balances(account_sums, account, currency, amount)
92 def collect_branches(account_name, path):
95 while len(path_copy) > 0:
96 step = path_copy.pop(0)
98 toks = account_name.split(":", maxsplit=1)
100 if parent in node.keys():
106 k, v = collect_branches(toks[1], path + [parent])
107 if k not in child.keys():
112 for account_name in sorted(account_sums.keys()):
113 k, v = collect_branches(account_name, [])
114 if k not in account_tree.keys():
117 account_tree[k].update(v)
118 def collect_totals(parent_path, tree_node):
119 for k, v in tree_node.items():
120 child_path = parent_path + ":" + k
121 for currency, amount in collect_totals(child_path, v).items():
122 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
123 return account_sums[parent_path]
124 for account_name in account_tree.keys():
125 account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
126 return account_tree, account_sums
129 def parse_lines(lines):
131 inside_booking = False
132 date_string, description = None, None
137 lines = lines.copy() + [''] # to ensure a booking-ending last line
138 for i, line in enumerate(lines):
140 # we start with the case of an utterly empty line
142 stripped_line = line.rstrip()
143 if stripped_line == '':
145 # assume we finished a booking, finalize, and commit to DB
146 if len(booking_lines) < 2:
147 raise HandledException(f"{prefix} booking ends to early")
148 booking = Booking(date_string, description, booking_lines, start_line)
149 bookings += [booking]
150 # expect new booking to follow so re-zeroall booking data
151 inside_booking = False
152 date_string, description = None, None
155 # if non-empty line, first get comment if any, and commit to DB
156 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
157 if len(split_by_comment) == 2:
158 comments[i] = split_by_comment[1].lstrip()
159 # 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
160 non_comment = split_by_comment[0].rstrip()
161 if non_comment.rstrip() == '':
163 booking_lines += ['']
165 # if we're starting a booking, parse by first-line pattern
166 if not inside_booking:
168 toks = non_comment.split(maxsplit=1)
169 date_string = toks[0]
171 datetime.datetime.strptime(date_string, '%Y-%m-%d')
173 raise HandledException(f"{prefix} bad date string: {date_string}")
175 description = toks[1]
177 raise HandledException(f"{prefix} bad description: {description}")
178 inside_booking = True
179 booking_lines += [non_comment]
181 # otherwise, read as transfer data
182 toks = non_comment.split() # ignore specification's allowance of single spaces in names
184 raise HandledException(f"{prefix} too many booking line tokens: {toks}")
185 amount, currency = None, None
186 account_name = toks[0]
187 if account_name[0] == '[' and account_name[-1] == ']':
188 # ignore specification's differentiation of "virtual" accounts
189 account_name = account_name[1:-1]
190 decimal_chars = ".-0123456789"
194 amount = decimal.Decimal(toks[1])
196 except decimal.InvalidOperation:
198 amount = decimal.Decimal(toks[2])
199 except decimal.InvalidOperation:
200 raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
201 currency = toks[i_currency]
202 if currency[0] in decimal_chars:
203 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
206 inside_amount = False
207 inside_currency = False
211 for i, c in enumerate(value):
213 if c in decimal_chars:
216 inside_currency = True
218 if c in decimal_chars and len(amount_string) == 0:
219 inside_currency = False
225 if c not in decimal_chars:
226 if len(currency) > 0:
227 raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
228 inside_currency = True
229 inside_amount = False
232 if c == '-' and len(amount_string) > 1:
233 raise HandledException(f"{prefix} amount has non-start '-': {value}")
236 raise HandledException(f"{prefix} amount has multiple dots: {value}")
239 if len(amount_string) == 0:
240 raise HandledException(f"{prefix} amount missing: {value}")
241 if len(currency) == 0:
242 raise HandledException(f"{prefix} currency missing: {value}")
243 amount = decimal.Decimal(amount_string)
244 booking_lines += [(account_name, amount, currency)]
246 raise HandledException(f"{prefix} last booking unfinished")
247 return bookings, comments
252 def __init__(self, date_string, description, booking_lines, start_line):
253 self.date_string = date_string
254 self.description = description
255 self.lines = booking_lines
256 self.start_line = start_line
257 self.validate_booking_lines()
259 self.account_changes = self.parse_booking_lines_to_account_changes()
261 def validate_booking_lines(self):
262 prefix = f"booking at line {self.start_line}"
265 for line in self.lines[1:]:
268 _, amount, currency = line
271 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
274 if currency not in sums:
276 sums[currency] += amount
277 if empty_values == 0:
278 for k, v in sums.items():
280 raise HandledException(f"{prefix} does not add up to zero")
283 for k, v in sums.items():
287 raise HandledException(f"{prefix} has empty value that cannot be filled")
289 def parse_booking_lines_to_account_changes(self):
293 for line in self.lines[1:]:
296 account, amount, currency = line
298 sink_account = account
300 apply_booking_to_account_balances(account_changes, account, currency, amount)
301 if currency not in debt:
302 debt[currency] = amount
304 debt[currency] += amount
306 for currency, amount in debt.items():
307 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
308 self.sink[currency] = -amount
309 return account_changes
317 self.db_file = db_name + ".json"
318 self.lock_file = db_name+ ".lock"
322 if os.path.exists(self.db_file):
323 with open(self.db_file, "r") as f:
324 self.real_lines += [l.rstrip() for l in f.readlines()]
325 ret = parse_lines(self.real_lines)
326 self.bookings += ret[0]
327 self.comments += ret[1]
329 def get_lines(self, start, end):
330 return self.real_lines[start:end]
332 def replace(self, start, end, lines):
334 if os.path.exists(self.lock_file):
335 raise HandledException('Sorry, lock file!')
336 if os.path.exists(self.db_file):
337 shutil.copy(self.db_file, self.db_file + ".bak")
338 f = open(self.lock_file, 'w+')
340 total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
341 text = '\n'.join(total_lines)
342 with open(self.db_file, 'w') as f:
344 os.remove(self.lock_file)
346 def append(self, lines):
348 if os.path.exists(self.lock_file):
349 raise HandledException('Sorry, lock file!')
350 if os.path.exists(self.db_file):
351 shutil.copy(self.db_file, self.db_file + ".bak")
352 f = open(self.lock_file, 'w+')
354 with open(self.db_file, 'a') as f:
355 f.write('\n\n' + '\n'.join(lines) + '\n\n');
356 os.remove(self.lock_file)
359 class MyServer(BaseHTTPRequestHandler):
361 <meta charset="UTF-8">
363 body { color: #000000; }
364 table { margin-bottom: 2em; }
365 th, td { text-align: left }
366 input[type=number] { text-align: right; font-family: monospace; }
367 .money { font-family: monospace; text-align: right; }
368 .comment { font-style: italic; color: #777777; }
369 .full_line_comment { display: block; white-space: nowrap; width: 0; }
372 <a href="/ledger">ledger</a>
373 <a href="/balance">balance</a>
374 <a href="/add_free">add free</a>
375 <a href="/add_structured">add structured</a>
378 footer = "</body>\n<html>"
382 length = int(self.headers['content-length'])
383 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
384 parsed_url = urlparse(self.path)
386 add_empty_line = None
387 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
388 date = postvars['date'][0]
389 description = postvars['description'][0]
390 start_comment = postvars['line_0_comment'][0]
391 lines = [f'{date} {description} ; {start_comment}']
392 if 'line_0_add' in postvars.keys():
395 while f'line_{i}_comment' in postvars.keys():
396 if f'line_{i}_delete' in postvars.keys():
399 if f'line_{i}_add' in postvars.keys():
401 account = postvars[f'line_{i}_account'][0]
402 amount = postvars[f'line_{i}_amount'][0]
403 currency = postvars[f'line_{i}_currency'][0]
404 comment = postvars[f'line_{i}_comment'][0]
406 new_main = f'{account} {amount} {currency}'
407 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines
411 if comment.rstrip() != '':
412 new_line += f' ; {comment}'
414 if 'add_taxes' in postvars.keys():
415 lines += add_taxes(lines)
416 elif '/add_free' == parsed_url.path:
417 lines = postvars['booking'][0].splitlines()
418 start = int(postvars['start'][0])
419 end = int(postvars['end'][0])
421 _, _ = parse_lines(lines)
422 if 'save' in postvars.keys():
423 if start == end == 0:
425 redir_url = f'/#last'
427 db.replace(start, end, lines)
428 redir_url = f'/#{start}'
429 self.send_response(301)
430 self.send_header('Location', redir_url)
433 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
434 self.send_response(200)
435 self.send_header("Content-type", "text/html")
437 self.wfile.write(bytes(page, "utf-8"))
438 except HandledException as e:
439 self.send_response(400)
440 self.send_header("Content-type", "text/html")
442 page = f'{self.header}ERROR: {e}{self.footer}'
443 self.wfile.write(bytes(page, "utf-8"))
446 self.send_response(200)
447 self.send_header("Content-type", "text/html")
450 parsed_url = urlparse(self.path)
451 page = self.header + ''
452 params = parse_qs(parsed_url.query)
453 start = int(params.get('start', ['0'])[0])
454 end = int(params.get('end', ['0'])[0])
455 if parsed_url.path == '/balance':
456 page += self.balance_as_html(db)
457 elif parsed_url.path == '/add_free':
458 page += self.add_free(db, start, end)
459 elif parsed_url.path == '/add_structured':
460 page += self.add_structured(db, start, end)
461 elif parsed_url.path == '/copy_free':
462 page += self.add_free(db, start, end, copy=True)
463 elif parsed_url.path == '/copy_structured':
464 page += self.add_structured(db, start, end, copy=True)
465 elif parsed_url.path == '/ledger2':
466 page += self.ledger2_as_html(db)
468 page += self.ledger_as_html(db)
470 self.wfile.write(bytes(page, "utf-8"))
472 def balance_as_html(self, db):
474 account_tree, account_sums = bookings_to_account_tree(db.bookings)
475 def print_subtree(lines, indent, node, subtree, path):
476 line = f"{indent}{node}"
477 n_tabs = 5 - (len(line) // 8)
478 line += n_tabs * "\t"
479 if "€" in account_sums[path + node].keys():
480 amount = account_sums[path + node]["€"]
481 line += f"{amount:9.2f} €\t"
484 for currency, amount in account_sums[path + node].items():
485 if currency != '€' and amount > 0:
486 line += f"{amount:5.2f} {currency}\t"
489 for k, v in sorted(subtree.items()):
490 print_subtree(lines, indent, k, v, path + node + ":")
491 for k, v in sorted(account_tree.items()):
492 print_subtree(lines, "", k, v, "")
493 content = "\n".join(lines)
494 return f"<pre>{content}</pre>"
496 def ledger2_as_html(self, db):
497 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
498 booking_tmpl = jinja2.Template("""
499 <p id="{{start}}"><a href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span>
500 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
501 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
502 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
503 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
505 {% for l in booking_lines %}
506 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="money">{{l.balance|e}}</td></tr>
510 elements_to_write = []
512 for booking in db.bookings:
513 i = booking.start_line
514 booking_end = booking.start_line + len(booking.lines)
516 for booking_line in booking.lines[1:]:
517 if booking_line == '':
519 account = booking_line[0]
520 account_toks = account.split(':')
522 for tok in account_toks:
524 if not path in account_sums.keys():
525 account_sums[path] = {}
529 if booking_line[1] is not None:
530 moneys += [(booking_line[1], booking_line[2])]
531 money = f'{moneys[0][0]} {moneys[0][1]}'
533 for currency, amount in booking.sink.items():
534 moneys += {(amount, currency)}
537 money += f'{m[0]} {m[1]} '
540 for amount, currency in moneys:
542 for tok in account_toks:
544 if not currency in account_sums[path].keys():
545 account_sums[path][currency] = 0
546 account_sums[path][currency] += amount
548 balance += f'{account_sums[account][currency]} {currency}'
549 booking_lines += [{'acc': booking_line[0], 'money':money, 'balance':balance}]
550 elements_to_write += [booking_tmpl.render(
551 start=booking.start_line,
553 date=booking.date_string,
554 desc=booking.description,
555 head_comment=db.comments[booking.start_line],
556 booking_lines = booking_lines)]
557 return '\n'.join(elements_to_write)
559 def ledger_as_html(self, db):
560 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
561 booking_tmpl = jinja2.Template("""
562 <p id="{{start}}"><a {% if last %}id="last"{% endif %} href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span>
563 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
564 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
565 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
566 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
568 {% for l in booking_lines %}
570 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
572 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
577 elements_to_write = []
579 last_start = db.bookings[-1].start_line
580 for booking in db.bookings:
581 i = booking.start_line
582 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']
583 booking_end = last_i = booking.start_line + len(booking.lines)
585 for booking_line in booking.lines[1:]:
587 comment = db.comments[i]
588 if booking_line == '':
589 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
591 account = booking_line[0]
593 if booking_line[1] is not None:
594 money = f'{booking_line[1]} {booking_line[2]}'
595 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]
596 elements_to_write += [booking_tmpl.render(
597 last=booking.start_line == last_start,
598 start=booking.start_line,
600 date=booking.date_string,
601 desc=booking.description,
602 head_comment=db.comments[booking.start_line],
603 booking_lines = booking_lines)]
604 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
605 return '\n'.join(elements_to_write)
607 def add_free(self, db, start=0, end=0, copy=False):
608 tmpl = jinja2.Template("""
609 <form method="POST" action="{{action|e}}">
610 <textarea name="booking" rows=10 cols=80>
611 {% for line in lines %}{{ line }}
614 <input type="hidden" name="start" value={{start}} />
615 <input type="hidden" name="end" value={{end}} />
616 <input type="submit" name="save" value="save!">
619 lines = db.get_lines(start, end)
622 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
624 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
625 tmpl = jinja2.Template("""
626 <form method="POST" action="{{action|e}}">
627 <input type="submit" name="check" value="check" />
628 <input type="submit" name="revert" value="revert" />
629 <input type="submit" name="add_taxes" value="add taxes" />
631 <input name="date" value="{{date|e}}" size=9 />
632 <input name="description" value="{{desc|e}}" list="descriptions" />
633 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
634 <input type="submit" name="line_0_add" value="[+]" />
636 {% for line in booking_lines %}
637 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
638 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
639 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
640 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
641 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
642 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
645 {% for name, items in datalist_sets.items() %}
646 <datalist id="{{name}}">
647 {% for item in items %}
648 <option value="{{item|e}}">{{item|e}}</option>
652 <input type="hidden" name="start" value={{start}} />
653 <input type="hidden" name="end" value={{end}} />
654 <input type="submit" name="save" value="save!">
658 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
659 bookings, comments = parse_lines(lines)
660 if len(bookings) > 1:
661 raise HandledException('can only edit single Booking')
662 if add_empty_line is not None:
663 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
664 booking = bookings[0]
665 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
666 action = 'add_structured'
667 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
668 for b in db.bookings:
669 datalist_sets['descriptions'].add(b.description)
670 for account, moneys in b.account_changes.items():
671 datalist_sets['accounts'].add(account)
672 for currency in moneys.keys():
673 datalist_sets['currencies'].add(currency)
675 today = str(datetime.datetime.now())[:10]
679 desc = head_comment = ''
680 if len(bookings) == 0:
681 for i in range(1, 3):
682 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
685 booking = bookings[0]
686 desc = booking.description
687 date = today if copy else booking.date_string
688 head_comment=comments[0]
689 last_line = len(comments)
690 for i in range(1, len(comments)):
691 account = amount = currency = ''
692 if i < len(booking.lines) and booking.lines[i] != '':
693 account = booking.lines[i][0]
694 amount = booking.lines[i][1]
695 currency = booking.lines[i][2]
700 'curr': currency if currency else '',
701 'comment': comments[i],
702 'comm_cols': len(comments[i])}]
703 content += tmpl.render(
707 head_comment=head_comment,
708 booking_lines=booking_lines,
709 datalist_sets=datalist_sets,
715 if __name__ == "__main__":
716 webServer = HTTPServer((hostName, serverPort), MyServer)
717 print(f"Server started http://{hostName}:{serverPort}")
719 webServer.serve_forever()
720 except KeyboardInterrupt:
722 webServer.server_close()
723 print("Server stopped.")