home · contact · privacy
4a6a071833311493636a7f36b870e32d722dd45d
[misc] / ledger.py
1 from http.server import BaseHTTPRequestHandler, HTTPServer
2 import os
3 import html
4 import jinja2
5 import decimal
6 import datetime
7 from urllib.parse import parse_qs, urlparse
8 hostName = "localhost"
9 serverPort = 8082
10
11
12 class HandledException(Exception):
13     pass
14
15
16 def apply_booking_to_account_balances(account_sums, account, currency, amount):
17     if not account in account_sums:
18         account_sums[account] = {currency: amount}
19     elif not currency in account_sums[account].keys():
20         account_sums[account][currency] = amount
21     else:
22         account_sums[account][currency] += amount
23
24
25 def bookings_to_account_tree(bookings):
26     account_sums = {}
27     for booking in bookings:
28         for account, changes in booking.account_changes.items():
29             for currency, amount in changes.items():
30                 apply_booking_to_account_balances(account_sums, account, currency, amount)
31     account_tree = {}
32     def collect_branches(account_name, path):
33         node = account_tree
34         path_copy = path[:]
35         while len(path_copy) > 0:
36             step = path_copy.pop(0)
37             node = node[step]
38         toks = account_name.split(":", maxsplit=1)
39         parent = toks[0]
40         if parent in node.keys():
41             child = node[parent]
42         else:
43             child = {}
44             node[parent] = child
45         if len(toks) == 2:
46             k, v = collect_branches(toks[1], path + [parent])
47             if k not in child.keys():
48                 child[k] = v
49             else:
50                 child[k].update(v)
51         return parent, child
52     for account_name in sorted(account_sums.keys()):
53         k, v = collect_branches(account_name, [])
54         if k not in account_tree.keys():
55             account_tree[k] = v
56         else:
57             account_tree[k].update(v)
58     def collect_totals(parent_path, tree_node):
59         for k, v in tree_node.items():
60             child_path = parent_path + ":" + k
61             for currency, amount in collect_totals(child_path, v).items():
62                 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
63         return account_sums[parent_path]
64     for account_name in account_tree.keys():
65         account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
66     return account_tree, account_sums
67
68
69 def parse_lines(lines, validate_bookings=True):
70     inside_booking = False
71     date_string, description = None, None
72     booking_lines = []
73     start_line = 0
74     bookings = []
75     comments = []
76     lines = lines.copy() + [''] # to ensure a booking-ending last line
77     last_date = ''
78     for i, line in enumerate(lines):
79         prefix = f"line {i}"
80         # we start with the case of an utterly empty line
81         comments += [""]
82         stripped_line = line.rstrip()
83         if stripped_line == '':
84             if inside_booking:
85                 # assume we finished a booking, finalize, and commit to DB
86                 if len(booking_lines) < 2:
87                     raise HandledException(f"{prefix} booking ends to early")
88                 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
89                 bookings += [booking]
90             # expect new booking to follow so re-zeroall booking data
91             inside_booking = False
92             date_string, description = None, None
93             booking_lines = []
94             continue
95         # if non-empty line, first get comment if any, and commit to DB
96         split_by_comment = stripped_line.split(sep=";", maxsplit=1)
97         if len(split_by_comment) == 2:
98             comments[i] = split_by_comment[1].lstrip()
99         # 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
100         non_comment = split_by_comment[0].rstrip()
101         if non_comment.rstrip() == '':
102              if inside_booking:
103                  booking_lines += ['']
104              continue
105         # if we're starting a booking, parse by first-line pattern
106         if not inside_booking:
107             start_line = i
108             toks = non_comment.split(maxsplit=1)
109             date_string = toks[0]
110             try:
111                 datetime.datetime.strptime(date_string, '%Y-%m-%d')
112             except ValueError:
113                 raise HandledException(f"{prefix} bad date string: {date_string}")
114             if last_date > date_string:
115                 raise HandledException(f"{prefix} out-of-order-date")
116             last_date = date_string
117             try:
118                 description = toks[1]
119             except IndexError:
120                 raise HandledException(f"{prefix} bad description: {description}")
121             inside_booking = True
122             booking_lines += [non_comment]
123             continue
124         # otherwise, read as transfer data
125         toks = non_comment.split()  # ignore specification's allowance of single spaces in names
126         if len(toks) > 3:
127             raise HandledException(f"{prefix} too many booking line tokens: {toks}")
128         amount, currency = None, None
129         account_name = toks[0]
130         if account_name[0] == '[' and account_name[-1] == ']':
131             # ignore specification's differentiation of "virtual" accounts
132             account_name = account_name[1:-1]
133         decimal_chars = ".-0123456789"
134         if len(toks) == 3:
135             i_currency = 1
136             try:
137                 amount = decimal.Decimal(toks[1])
138                 i_currency = 2
139             except decimal.InvalidOperation:
140                 try:
141                     amount = decimal.Decimal(toks[2])
142                 except decimal.InvalidOperation:
143                     raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
144             currency = toks[i_currency]
145             if currency[0] in decimal_chars:
146                 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
147         elif len(toks) == 2:
148             value = toks[1]
149             inside_amount = False
150             inside_currency = False
151             amount_string = ""
152             currency = ""
153             dots_counted = 0
154             for i, c in enumerate(value):
155                 if i == 0:
156                     if c in decimal_chars:
157                         inside_amount = True
158                     else:
159                         inside_currency = True
160                 if inside_currency:
161                     if c in decimal_chars and len(amount_string) == 0:
162                         inside_currency = False
163                         inside_amount = True
164                     else:
165                         currency += c
166                         continue
167                 if inside_amount:
168                     if c not in decimal_chars:
169                         if len(currency) > 0:
170                             raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
171                         inside_currency = True
172                         inside_amount = False
173                         currency += c
174                         continue
175                     if c == '-' and len(amount_string) > 1:
176                         raise HandledException(f"{prefix} amount has non-start '-': {value}")
177                     if c == '.':
178                         if dots_counted > 1:
179                             raise HandledException(f"{prefix} amount has multiple dots: {value}")
180                         dots_counted += 1
181                     amount_string += c
182             if len(currency) == 0:
183                 raise HandledException(f"{prefix} currency missing: {value}")
184             if len(amount_string) > 0:
185                 amount = decimal.Decimal(amount_string)
186         booking_lines += [(account_name, amount, currency)]
187     if inside_booking:
188         raise HandledException(f"{prefix} last booking unfinished")
189     return bookings, comments
190
191
192 class Booking:
193
194     def __init__(self, date_string, description, booking_lines, start_line, process=True):
195         self.date_string = date_string
196         self.description = description
197         self.lines = booking_lines
198         self.start_line = start_line
199         if process:
200             self.validate_booking_lines()
201             self.sink = {}
202             self.account_changes = self.parse_booking_lines_to_account_changes()
203
204     def validate_booking_lines(self):
205         prefix = f"booking at line {self.start_line}"
206         sums = {}
207         empty_values = 0
208         for line in self.lines[1:]:
209             if line == '':
210                 continue
211             _, amount, currency = line
212             if amount is None:
213                 if empty_values > 0:
214                     raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
215                 empty_values += 1
216                 continue
217             if currency not in sums:
218                 sums[currency] = 0
219             sums[currency] += amount
220         if empty_values == 0:
221             for k, v in sums.items():
222                 if v != 0:
223                     raise HandledException(f"{prefix} does not add up to zero / {k} {v}")
224         else:
225             sinkable = False
226             for k, v in sums.items():
227                 if v != 0:
228                     sinkable = True
229             if not sinkable:
230                 raise HandledException(f"{prefix} has empty value that cannot be filled")
231
232     def parse_booking_lines_to_account_changes(self):
233         account_changes = {}
234         debt = {}
235         sink_account = None
236         for line in self.lines[1:]:
237             if line == '':
238                 continue
239             account, amount, currency = line
240             if amount is None:
241                 sink_account = account
242                 continue
243             apply_booking_to_account_balances(account_changes, account, currency, amount)
244             if currency not in debt:
245                 debt[currency] = amount
246             else:
247                 debt[currency] += amount
248         if sink_account:
249             for currency, amount in debt.items():
250                 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
251                 self.sink[currency] = -amount
252         return account_changes
253
254
255
256 class Database:
257
258     def __init__(self):
259         db_name = "_ledger"
260         self.db_file = db_name + ".json"
261         self.lock_file = db_name+ ".lock"
262         self.bookings = []
263         self.comments = []
264         self.real_lines = []
265         if os.path.exists(self.db_file):
266             with open(self.db_file, "r") as f:
267                 self.real_lines += [l.rstrip() for l in f.readlines()]
268         ret = parse_lines(self.real_lines)
269         self.bookings += ret[0]
270         self.comments += ret[1]
271
272     def get_lines(self, start, end):
273         return self.real_lines[start:end]
274
275     def write_db(self, text, mode='w'):
276         import shutil
277         if os.path.exists(self.lock_file):
278             raise HandledException('Sorry, lock file!')
279         f = open(self.lock_file, 'w+')
280         f.close()
281
282         # always back up most recent to .bak
283         bakpath = f'{self.db_file}.bak'
284         shutil.copy(self.db_file, bakpath)
285
286         # collect modification times of numbered .bak files
287         bak_prefix = f'{bakpath}.'
288         backup_dates = []
289         i = 0
290         bak_as = f'{bak_prefix}{i}'
291         while os.path.exists(bak_as):
292             mod_time = os.path.getmtime(bak_as)
293             backup_dates += [str(datetime.datetime.fromtimestamp(mod_time))]
294             i += 1
295             bak_as = f'{bak_prefix}{i}'
296
297         # collect what numbered .bak files to save:
298         # shrink datetime string right to left character by character,
299         # on each step add the oldest file whose mtime still fits the pattern
300         # (privilege older files to keep existing longer)
301         to_save = []
302         datetime_len = 19
303         now = str(datetime.datetime.now())[:datetime_len]
304         while datetime_len > 2:
305             # assume backup_dates starts with oldest dates
306             for i, date in enumerate(backup_dates):
307                 if date[:datetime_len] == now:
308                     if i not in to_save:
309                         to_save += [i] 
310                         break
311             datetime_len -= 1 
312             now = now[:datetime_len]
313
314         # remove redundant backup files 
315         j = 0
316         for i in to_save:
317             if i != j:
318                 source = f'{bak_prefix}{i}'
319                 target = f'{bak_prefix}{j}'
320                 shutil.move(source, target)
321             j += 1
322         for i in range(j, len(backup_dates)):
323             try:
324                 os.remove(f'{bak_prefix}{i}')
325             except FileNotFoundError:
326                 pass
327
328         # put second backup copy of current state at end of bak list 
329         shutil.copy(self.db_file, f'{bak_prefix}{j}')
330         with open(self.db_file, mode) as f:
331             f.write(text);
332         os.remove(self.lock_file)
333
334     def insert_at_date(self, lines, date):
335         start_at = len(self.real_lines)
336         for b in self.bookings:
337             if b.date_string == date:
338                 start_at = b.start_line 
339                 break
340             elif b.date_string > date:
341                 break
342         if start_at == len(self.real_lines):
343             lines = [''] + lines
344         return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
345
346     def update(self, start, end, lines, date):
347         total_lines = self.real_lines[:start] + self.real_lines[end:]
348         n_original_lines = end - start
349         start_at = len(total_lines)
350         for b in self.bookings:
351             if b.date_string == date:
352                 if start_at == len(total_lines) or b.start_line == start:
353                     start_at = b.start_line 
354                     if b.start_line > start:
355                         start_at -= n_original_lines
356             elif b.date_string > date:
357                 break
358         if start_at == len(total_lines):
359             lines = [''] + lines
360         return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
361
362     def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
363         total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
364         _, _ = parse_lines(lines)
365         text = '\n'.join(total_lines)
366         self.write_db(text)
367         return start_at
368
369     def get_nth_for_booking_of_start_line(self, start_line):
370         nth = 0
371         for b in self.bookings:
372             if b.start_line >= start_line:
373                 break
374             nth += 1
375         return nth
376
377     def add_taxes(self, lines, finish=False):
378         ret = []
379         bookings, _ = parse_lines(lines)
380         date = bookings[0].date_string
381         acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
382         acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
383         acc_kk = 'Expenses:KrankenKasse'
384         acc_est = 'Reserves:Einkommenssteuer'
385         acc_assets = 'Assets'
386         acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
387         last_monthbreak_assets = 0
388         last_monthbreak_est = 0
389         last_monthbreak_kk_minimum = 0
390         last_monthbreak_kk_add = 0
391         buffer_expenses = 0
392         kk_expenses = 0
393         est_expenses = 0
394         months_passed = -int(finish) 
395         for b in self.bookings:
396             if date == b.date_string:
397                 break
398             acc_keys = b.account_changes.keys()
399             if acc_buffer in acc_keys:
400                 buffer_expenses -= b.account_changes[acc_buffer]['€']
401             if acc_kk_add in acc_keys:
402                 kk_expenses += b.account_changes[acc_kk_add]['€']
403             if acc_kk in acc_keys:
404                 kk_expenses += b.account_changes[acc_kk]['€']
405             if acc_est in acc_keys:
406                 est_expenses += b.account_changes[acc_est]['€']
407             if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
408                 months_passed += 1
409                 if finish:
410                     last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
411                     last_monthbreak_est = b.account_changes[acc_est]['€']
412                     last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
413                     last_monthbreak_assets = b.account_changes[acc_buffer]['€']
414         old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
415         if finish:
416             ret += [f'  {acc_est}  {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
417         _, account_sums = bookings_to_account_tree(bookings)
418         expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
419         needed_income_before_kk = expenses_so_far
420         ESt_this_month = 0
421         left_over = needed_income_before_kk - ESt_this_month
422         too_low = 0
423         too_high = 2 * needed_income_before_kk
424         E0 = decimal.Decimal(10908)
425         E1 = decimal.Decimal(15999)
426         E2 = decimal.Decimal(62809)
427         E3 = decimal.Decimal(277825)
428         while True:
429             zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
430             if finish:
431                 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
432             if zvE < E0:
433                 ESt = decimal.Decimal(0)
434             elif zvE < E1:
435                 y = (zvE - E0)/10000
436                 ESt = (decimal.Decimal(979.18) * y + 1400) * y
437             elif zvE < E2:
438                 y = (zvE - E1)/10000
439                 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
440             elif zvE < E3:
441                 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809))  + decimal.Decimal(16405.54)
442             else:
443                 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
444             ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
445             left_over = needed_income_before_kk - ESt_this_month
446             if abs(left_over - expenses_so_far) < 0.001:
447                 break
448             elif left_over < expenses_so_far:
449                 too_low = needed_income_before_kk
450             elif left_over > expenses_so_far:
451                 too_high = needed_income_before_kk
452             needed_income_before_kk = too_low + (too_high - too_low)/2
453         ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
454         ret += [f'  {acc_est}  {ESt_this_month}€ ; expenses so far: {expenses_so_far:.2f}€; zvE: {zvE:.2f}€; ESt total: {ESt:.2f}€; needed before Krankenkasse: {needed_income_before_kk:.2f}€']
455         kk_minimum_income = 1131.67
456         if date < '2023-02-01':
457             kk_minimum_income = decimal.Decimal(1096.67)
458             kk_factor = decimal.Decimal(0.189)
459             kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
460         elif date < '2023-08-01':
461             kk_factor = decimal.Decimal(0.191)
462             kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
463         else:
464             kk_factor = decimal.Decimal(0.197)
465             kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
466         kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
467         kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
468         hit_kk_minimum_income_limit = False
469         if kk_add_so_far + kk_add < 0:
470             hit_kk_minimum_income_limit = True 
471             kk_add_uncorrect = kk_add
472             kk_add = -(kk_add + kk_add_so_far) 
473         kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
474         if finish:
475             ret += [f'  {acc_kk_add}  {-last_monthbreak_kk_add}€  ; for old assumption of needed income']
476         else:
477             ret += [f'  {acc_kk_minimum}  {kk_minimum_tax}€  ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
478         if hit_kk_minimum_income_limit:
479             ret += [f'  {acc_kk_add}  {kk_add}€  ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€ = {kk_add_uncorrect:.2f}€ would reduce current {acc_kk_dd} ({kk_add_so_far:.2f}€) below 0']
480         else:
481             ret += [f'  {acc_kk_add}  {kk_add}€  ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
482         diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
483         if not finish:
484             diff += kk_minimum_tax
485         final_minus = expenses_so_far - old_needed_income_before_anything + diff
486         ret += [f'  {acc_assets}  {-diff} €']
487         ret += [f'  {acc_assets}  {final_minus} €']
488         year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus 
489         if finish:
490             ret += [f'  {acc_buffer}  {-final_minus} €']
491         else:
492             ret += [f'  {acc_buffer}  {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
493         return ret
494
495
496 class MyServer(BaseHTTPRequestHandler):
497     header = """<html>
498 <meta charset="UTF-8">
499 <style>
500 body { color: #000000; }
501 table { margin-bottom: 2em; }
502 th, td { text-align: left }
503 input[type=number] { text-align: right; font-family: monospace; }
504 .money { font-family: monospace; text-align: right; }
505 .comment { font-style: italic; color: #777777; }
506 .meta { font-size: 0.75em; color: #777777; }
507 .full_line_comment { display: block; white-space: nowrap; width: 0; }
508 </style>
509 <body>
510 <a href="/">ledger</a>
511 <a href="/balance">balance</a>
512 <a href="/add_free">add free</a>
513 <a href="/add_structured">add structured</a>
514 <hr />
515 """
516     booking_tmpl = jinja2.Template("""
517 <p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
518 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
519 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
520 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
521 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
522 | move {% if move_up %}<a href="/move_up?start={{start}}&end={{end}}">up</a>{% else %}up{% endif %}/{% if move_down %}<a href="/move_down?start={{start}}&end={{end}}">down</a>{% else %}down{% endif %}
523 | <a href="/balance?stop={{nth+1}}">balance after</a>
524 ]</span>
525 <table>
526 {% for l in booking_lines %}
527 {% if l.acc %}
528 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
529 {% else %}
530 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
531 {% endif %}
532 {% endfor %}
533 </table></p>
534 """)
535     add_form_header = """<form method="POST" action="{{action|e}}">
536 <input type="submit" name="check" value="check" />
537 <input type="submit" name="revert" value="revert" />
538 """
539     add_form_footer = """
540 <input type="hidden" name="start" value={{start}} />
541 <input type="hidden" name="end" value={{end}} />
542 <input type="submit" name="save" value="save!">
543 </form>
544 """
545     footer = "</body>\n<html>"
546
547     def do_POST(self):
548         try:
549             parsed_url = urlparse(self.path)
550             length = int(self.headers['content-length'])
551             postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
552             start = int(postvars['start'][0])
553             end = int(postvars['end'][0])
554             db = Database()
555             add_empty_line = None
556             lines = []
557             # get inputs
558             if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
559                 lines, add_empty_line = self.booking_lines_from_postvars(postvars, db) 
560             elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
561                 lines = postvars['booking'][0].splitlines()
562             # validate where appropriate
563             if ('save' in postvars.keys()) or ('check' in postvars.keys()):
564                 _, _ = parse_lines(lines)
565             # if saving, process where to and where to redirect after
566             if 'save' in postvars.keys():
567                 last_date = str(datetime.datetime.now())[:10]
568                 if len(db.bookings) > 0:
569                     last_date = db.bookings[-1].date_string
570                 target_date = last_date[:] 
571                 first_line_tokens = lines[0].split() if len(lines) > 0 else ''
572                 first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
573                 try:
574                     datetime.datetime.strptime(first_token, '%Y-%m-%d')
575                     target_date = first_token
576                 except ValueError:
577                      pass
578                 if start == end == 0:
579                         start = db.insert_at_date(lines, target_date)
580                         nth = db.get_nth_for_booking_of_start_line(start) 
581                 else:
582                     new_start = db.update(start, end, lines, target_date)
583                     nth = db.get_nth_for_booking_of_start_line(new_start)
584                     if new_start > start: 
585                         nth -= 1 
586                 redir_url = f'/#{nth}'
587                 self.send_code_and_headers(302, [('Location', redir_url)])
588             # otherwise just re-build editing form
589             else:
590                 if '/add_structured' == parsed_url.path: 
591                     edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
592                 else:
593                     edit_content = self.add_free(db, start, end)
594                 self.send_HTML(self.header + edit_content + self.footer)
595         except HandledException as e:
596             self.fail_400(e)
597
598     def do_GET(self):
599         try:
600             parsed_url = urlparse(self.path)
601             params = parse_qs(parsed_url.query)
602             start = int(params.get('start', ['0'])[0])
603             end = int(params.get('end', ['0'])[0])
604             db = Database()
605             page = self.header
606             if parsed_url.path == '/balance':
607                 stop = params.get('stop', [None])[0]
608                 page += self.balance_as_html(db, stop)
609             elif parsed_url.path == '/add_free':
610                 page += self.add_free(db, start, end)
611             elif parsed_url.path == '/add_structured':
612                 page += self.add_structured(db, start, end)
613             elif parsed_url.path == '/copy_free':
614                 page += self.add_free(db, start, end, copy=True)
615             elif parsed_url.path == '/copy_structured':
616                 page += self.add_structured(db, start, end, copy=True)
617             elif parsed_url.path == '/move_up':
618                 nth = self.move_up(db, start, end)
619                 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
620                 return
621             elif parsed_url.path == '/move_down':
622                 nth = self.move_down(db, start, end)
623                 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
624                 return
625             else:
626                 page += self.ledger_as_html(db)
627             page += self.footer
628             self.send_HTML(page)
629         except HandledException as e:
630             self.fail_400(e)
631
632     def fail_400(self, e):
633         page = f'{self.header}ERROR: {e}{self.footer}'
634         self.send_HTML(page, 400)
635
636     def send_HTML(self, html, code=200):
637         self.send_code_and_headers(code, [('Content-type', 'text/html')])
638         self.wfile.write(bytes(html, "utf-8"))
639
640     def send_code_and_headers(self, code, headers=[]):
641         self.send_response(code)
642         for fieldname, content in headers:
643             self.send_header(fieldname, content)
644         self.end_headers()
645
646     def booking_lines_from_postvars(self, postvars, db):
647         add_empty_line = None
648         date = postvars['date'][0]
649         description = postvars['description'][0]
650         start_comment = postvars['line_0_comment'][0]
651         start_line = f'{date} {description}'
652         if start_comment.rstrip() != '':
653             start_line += f' ; {start_comment}' 
654         lines = [start_line]
655         if 'line_0_add' in postvars.keys():
656             add_empty_line = 0
657         i = j = 1
658         while f'line_{i}_comment' in postvars.keys():
659             if f'line_{i}_delete' in postvars.keys():
660                 i += 1
661                 continue
662             elif f'line_{i}_delete_after' in postvars.keys():
663                 break 
664             elif f'line_{i}_add' in postvars.keys():
665                 add_empty_line = j
666             account = postvars[f'line_{i}_account'][0]
667             amount = postvars[f'line_{i}_amount'][0]
668             currency = postvars[f'line_{i}_currency'][0]
669             comment = postvars[f'line_{i}_comment'][0]
670             i += 1
671             new_main = f'  {account}  {amount}'
672             if '' == new_main.rstrip() == comment.rstrip():  # don't write empty lines, ignore currency if nothing else set
673                 continue
674             if len(amount.rstrip()) > 0:
675                 new_main += f' {currency}'
676             j += 1
677             new_line = new_main
678             if comment.rstrip() != '':
679                 new_line += f'  ; {comment}'
680             lines += [new_line]
681         if 'add_sink' in postvars.keys():
682             temp_lines = lines.copy() + ['_']
683             try:
684                 temp_bookings, _ = parse_lines(temp_lines)
685                 for currency in temp_bookings[0].sink:
686                     amount = temp_bookings[0].sink[currency]
687                     lines += [f'Assets  {amount:.2f} {currency}']
688             except HandledException:
689                 pass
690         if 'add_taxes' in postvars.keys():
691             lines += db.add_taxes(lines, finish=False)
692         elif 'add_taxes2' in postvars.keys():
693             lines += db.add_taxes(lines, finish=True)
694         return lines, add_empty_line
695
696     def balance_as_html(self, db, until=None):
697         bookings = db.bookings[:until if until is None else int(until)]
698         lines = []
699         account_tree, account_sums = bookings_to_account_tree(bookings)
700         def print_subtree(lines, indent, node, subtree, path):
701             line = f"{indent}{node}"
702             n_tabs = 5 - (len(line) // 8)
703             line += n_tabs * "\t"
704             if "€" in account_sums[path + node].keys():
705                 amount = account_sums[path + node]["€"]
706                 line += f"{amount:9.2f} €\t"
707             else:
708                 line += f"\t\t"
709             for currency, amount in account_sums[path + node].items():
710                 if currency != '€' and amount > 0:
711                     line += f"{amount:5.2f} {currency}\t"
712             lines += [line]
713             indent += "  "
714             for k, v in sorted(subtree.items()):
715                 print_subtree(lines, indent, k, v, path + node + ":")
716         for k, v in sorted(account_tree.items()):
717             print_subtree(lines, "", k, v, "")
718         content = "\n".join(lines)
719         return f"<pre>{content}</pre>"
720
721     def ledger_as_html(self, db):
722         single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')  ##
723         elements_to_write = []
724         last_i = i = 0  ##
725         for nth, booking in enumerate(db.bookings):
726             move_up = nth > 0 and db.bookings[nth - 1].date_string == booking.date_string
727             move_down = nth < len(db.bookings) - 1 and db.bookings[nth + 1].date_string == booking.date_string
728             booking_end = last_i = booking.start_line + len(booking.lines)
729             booking_lines = []
730             i = booking.start_line  ##
731             elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']  ##
732             for booking_line in booking.lines[1:]:
733                  i += 1  ##
734                  comment = db.comments[i]  ##
735                  if booking_line == '':
736                      booking_lines += [{'acc': None, 'money': None, 'comment': comment}]  ##
737                      continue
738                  account = booking_line[0]
739                  money = ''
740                  if booking_line[1] is not None:
741                      money = f'{booking_line[1]} {booking_line[2]}'
742                  booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]  ##
743             elements_to_write += [self.booking_tmpl.render(
744                 nth=nth,
745                 start=booking.start_line,
746                 end=booking_end,
747                 date=booking.date_string,
748                 desc=booking.description,
749                 head_comment=db.comments[booking.start_line],
750                 move_up=move_up,
751                 move_down=move_down,
752                 booking_lines = booking_lines)]
753         elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']  #
754         return '\n'.join(elements_to_write)
755
756     def add_free(self, db, start=0, end=0, copy=False):
757         tmpl = jinja2.Template(self.add_form_header + """<br />
758 <textarea name="booking" rows=10 cols=80>
759 {% for line in lines %}{{ line }}
760 {% endfor %}
761 </textarea>
762 """ + self.add_form_footer)
763         lines = db.get_lines(start, end)
764         if copy:
765             start = end = 0
766         return tmpl.render(action='add_free', start=start, end=end, lines=lines)
767
768     def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
769         tmpl = jinja2.Template(self.add_form_header + """
770 <input type="submit" name="add_taxes" value="add taxes" />
771 <input type="submit" name="add_taxes2" value="add taxes2" />
772 <input type="submit" name="add_sink" value="add sink" />
773 <br />
774 <input name="date" value="{{date|e}}" size=9 />
775 <input name="description" value="{{desc|e}}" list="descriptions" />
776 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
777 <input type="submit" name="line_0_add" value="[+]" />
778 <br />
779 {% for line in booking_lines %}
780 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
781 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
782 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
783 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
784 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
785 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
786 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
787 <br />
788 {% endfor %}
789 {% for name, items in datalist_sets.items() %}
790 <datalist id="{{name}}">
791 {% for item in items %}
792   <option value="{{item|e}}">{{item|e}}</option>
793 {% endfor %}
794 </datalist>
795 {% endfor %}
796 """ + self.add_form_footer)
797         lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
798         bookings, comments = parse_lines(lines, validate_bookings=False)
799         if len(bookings) > 1:
800             raise HandledException('can only structurally edit single Booking')
801         if add_empty_line is not None:
802             comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
803             booking = bookings[0]
804             booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
805         action = 'add_structured'
806         datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
807         for b in db.bookings:
808             datalist_sets['descriptions'].add(b.description)
809             for account, moneys in b.account_changes.items():
810                 datalist_sets['accounts'].add(account)
811                 for currency in moneys.keys():
812                     datalist_sets['currencies'].add(currency)
813         content = ''
814         today = str(datetime.datetime.now())[:10]
815         booking_lines = []
816         if copy:
817             start = end = 0
818         desc = head_comment = ''
819         if len(bookings) == 0:
820             for i in range(1, 3):
821                 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
822             date=today
823         else:
824             booking = bookings[0]
825             desc = booking.description
826             date = today if copy else booking.date_string
827             head_comment=comments[0]
828             last_line = len(comments)
829             for i in range(1, len(comments)):
830                 account = amount = currency = ''
831                 if i < len(booking.lines) and booking.lines[i] != '':
832                     account = booking.lines[i][0]
833                     amount = booking.lines[i][1]
834                     currency = booking.lines[i][2]
835                 booking_lines += [{
836                         'i': i,
837                         'acc': account,
838                         'amt': amount,
839                         'curr': currency if currency else '€',
840                         'comment': comments[i],
841                         'comm_cols': len(comments[i])}]
842         content += tmpl.render(
843                 action=action,
844                 date=date,
845                 desc=desc,
846                 head_comment=head_comment,
847                 booking_lines=booking_lines,
848                 datalist_sets=datalist_sets,
849                 start=start,
850                 end=end)
851         return content
852
853     def move_up(self, db, start, end):
854         prev_booking = None
855         for redir_nth, b in enumerate(db.bookings):
856             if b.start_line >= start:
857                 break
858             prev_booking = b
859         start_at = prev_booking.start_line 
860         self.make_move(db, start, end, start_at)
861         return redir_nth - 1
862
863     def move_down(self, db, start, end):
864         next_booking = None
865         for redir_nth, b in enumerate(db.bookings):
866             if b.start_line > start:
867                 next_booking = b
868                 break
869         start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1 
870         self.make_move(db, start, end, start_at)
871         return redir_nth
872
873     def make_move(self, db, start, end, start_at):
874         lines = db.get_lines(start, end)
875         total_lines = db.real_lines[:start] + db.real_lines[end:]
876         db.write_lines_in_total_lines_at(total_lines, start_at, lines)
877
878
879 if __name__ == "__main__":  
880     webServer = HTTPServer((hostName, serverPort), MyServer)
881     print(f"Server started http://{hostName}:{serverPort}")
882     try:
883         webServer.serve_forever()
884     except KeyboardInterrupt:
885         pass
886     webServer.server_close()
887     print("Server stopped.")