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