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:
426 db.replace(start, end, lines)
427 self.send_response(301)
429 self.send_header('Location', redir_url)
432 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
433 self.send_response(200)
434 self.send_header("Content-type", "text/html")
436 self.wfile.write(bytes(page, "utf-8"))
437 except HandledException as e:
438 self.send_response(400)
439 self.send_header("Content-type", "text/html")
441 page = f'{self.header}ERROR: {e}{self.footer}'
442 self.wfile.write(bytes(page, "utf-8"))
445 self.send_response(200)
446 self.send_header("Content-type", "text/html")
449 parsed_url = urlparse(self.path)
450 page = self.header + ''
451 params = parse_qs(parsed_url.query)
452 start = int(params.get('start', ['0'])[0])
453 end = int(params.get('end', ['0'])[0])
454 if parsed_url.path == '/balance':
455 page += self.balance_as_html(db)
456 elif parsed_url.path == '/add_free':
457 page += self.add_free(db, start, end)
458 elif parsed_url.path == '/add_structured':
459 page += self.add_structured(db, start, end)
460 elif parsed_url.path == '/copy_free':
461 page += self.add_free(db, start, end, copy=True)
462 elif parsed_url.path == '/copy_structured':
463 page += self.add_structured(db, start, end, copy=True)
464 elif parsed_url.path == '/ledger2':
465 page += self.ledger2_as_html(db)
467 page += self.ledger_as_html(db)
469 self.wfile.write(bytes(page, "utf-8"))
471 def balance_as_html(self, db):
473 account_tree, account_sums = bookings_to_account_tree(db.bookings)
474 def print_subtree(lines, indent, node, subtree, path):
475 line = f"{indent}{node}"
476 n_tabs = 5 - (len(line) // 8)
477 line += n_tabs * "\t"
478 if "€" in account_sums[path + node].keys():
479 amount = account_sums[path + node]["€"]
480 line += f"{amount:9.2f} €\t"
483 for currency, amount in account_sums[path + node].items():
484 if currency != '€' and amount > 0:
485 line += f"{amount:5.2f} {currency}\t"
488 for k, v in sorted(subtree.items()):
489 print_subtree(lines, indent, k, v, path + node + ":")
490 for k, v in sorted(account_tree.items()):
491 print_subtree(lines, "", k, v, "")
492 content = "\n".join(lines)
493 return f"<pre>{content}</pre>"
495 def ledger2_as_html(self, db):
496 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
497 booking_tmpl = jinja2.Template("""
498 <p>{{date}} {{desc}} <span class="comment">{{head_comment|e}}</span>
499 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
500 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
501 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
502 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
504 {% for l in booking_lines %}
505 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="money">{{l.balance|e}}</td></tr>
509 elements_to_write = []
511 for booking in db.bookings:
512 i = booking.start_line
513 booking_end = booking.start_line + len(booking.lines)
515 for booking_line in booking.lines[1:]:
516 if booking_line == '':
518 account = booking_line[0]
519 account_toks = account.split(':')
521 for tok in account_toks:
523 if not path in account_sums.keys():
524 account_sums[path] = {}
528 if booking_line[1] is not None:
529 moneys += [(booking_line[1], booking_line[2])]
530 money = f'{moneys[0][0]} {moneys[0][1]}'
532 for currency, amount in booking.sink.items():
533 moneys += {(amount, currency)}
536 money += f'{m[0]} {m[1]} '
539 for amount, currency in moneys:
541 for tok in account_toks:
543 if not currency in account_sums[path].keys():
544 account_sums[path][currency] = 0
545 account_sums[path][currency] += amount
547 balance += f'{account_sums[account][currency]} {currency}'
548 booking_lines += [{'acc': booking_line[0], 'money':money, 'balance':balance}]
549 elements_to_write += [booking_tmpl.render(
550 start=booking.start_line,
552 date=booking.date_string,
553 desc=booking.description,
554 head_comment=db.comments[booking.start_line],
555 booking_lines = booking_lines)]
556 return '\n'.join(elements_to_write)
558 def ledger_as_html(self, db):
559 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
560 booking_tmpl = jinja2.Template("""
561 <p>{{date}} {{desc}} <span class="comment">{{head_comment|e}}</span>
562 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
563 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
564 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
565 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
567 {% for l in booking_lines %}
569 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
571 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
576 elements_to_write = []
578 for booking in db.bookings:
579 i = booking.start_line
580 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']
581 booking_end = last_i = booking.start_line + len(booking.lines)
583 for booking_line in booking.lines[1:]:
585 comment = db.comments[i]
586 if booking_line == '':
587 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
589 account = booking_line[0]
591 if booking_line[1] is not None:
592 money = f'{booking_line[1]} {booking_line[2]}'
593 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]
594 elements_to_write += [booking_tmpl.render(
595 start=booking.start_line,
597 date=booking.date_string,
598 desc=booking.description,
599 head_comment=db.comments[booking.start_line],
600 booking_lines = booking_lines)]
601 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
602 return '\n'.join(elements_to_write)
604 def add_free(self, db, start=0, end=0, copy=False):
605 tmpl = jinja2.Template("""
606 <form method="POST" action="{{action}}">
607 <textarea name="booking" rows=10 cols=80>
608 {% for line in lines %}{{ line }}
611 <input type="hidden" name="start" value={{start}} />
612 <input type="hidden" name="end" value={{end}} />
613 <input type="submit" name="save" value="save!">
616 lines = db.get_lines(start, end)
619 return tmpl.render(start=start, end=end, lines=lines)
621 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
622 tmpl = jinja2.Template("""
623 <form method="POST" action="{{action|e}}">
624 <input type="submit" name="check" value="check" />
625 <input type="submit" name="revert" value="revert" />
626 <input type="submit" name="add_taxes" value="add taxes" />
628 <input name="date" value="{{date|e}}" size=9 />
629 <input name="description" value="{{desc|e}}" list="descriptions" />
630 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
631 <input type="submit" name="line_0_add" value="[+]" />
633 {% for line in booking_lines %}
634 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
635 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
636 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
637 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
638 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
639 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
642 {% for name, items in datalist_sets.items() %}
643 <datalist id="{{name}}">
644 {% for item in items %}
645 <option value="{{item|e}}">{{item|e}}</option>
649 <input type="hidden" name="start" value={{start}} />
650 <input type="hidden" name="end" value={{end}} />
651 <input type="submit" name="save" value="save!">
655 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
656 bookings, comments = parse_lines(lines)
657 if len(bookings) > 1:
658 raise HandledException('can only edit single Booking')
659 if add_empty_line is not None:
660 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
661 booking = bookings[0]
662 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
663 action = 'add_structured'
664 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
665 for b in db.bookings:
666 datalist_sets['descriptions'].add(b.description)
667 for account, moneys in b.account_changes.items():
668 datalist_sets['accounts'].add(account)
669 for currency in moneys.keys():
670 datalist_sets['currencies'].add(currency)
672 today = str(datetime.datetime.now())[:10]
676 desc = head_comment = ''
677 if len(bookings) == 0:
678 for i in range(1, 3):
679 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
682 booking = bookings[0]
683 desc = booking.description
684 date = today if copy else booking.date_string
685 head_comment=comments[0]
686 last_line = len(comments)
687 for i in range(1, len(comments)):
688 account = amount = currency = ''
689 if i < len(booking.lines) and booking.lines[i] != '':
690 account = booking.lines[i][0]
691 amount = booking.lines[i][1]
692 currency = booking.lines[i][2]
697 'curr': currency if currency else '',
698 'comment': comments[i],
699 'comm_cols': len(comments[i])}]
700 content += tmpl.render(
704 head_comment=head_comment,
705 booking_lines=booking_lines,
706 datalist_sets=datalist_sets,
712 if __name__ == "__main__":
713 webServer = HTTPServer((hostName, serverPort), MyServer)
714 print(f"Server started http://{hostName}:{serverPort}")
716 webServer.serve_forever()
717 except KeyboardInterrupt:
719 webServer.server_close()
720 print("Server stopped.")