home · contact · privacy
6e0a482bffa4b66a57202d84027c1f718dfca933
[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 .meta { font-size: 0.75em; color: #777777; }
419 .full_line_comment { display: block; white-space: nowrap; width: 0; }
420 </style>
421 <body>
422 <a href="/ledger1">ledger1</a>
423 <a href="/ledger2">ledger2</a>
424 <a href="/balance">balance</a>
425 <a href="/add_free">add free</a>
426 <a href="/add_structured">add structured</a>
427 <hr />
428 """
429     booking_tmpl = jinja2.Template("""
430 <p id="{{start}}"><a href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
431 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
432 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
433 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
434 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
435 | balance <a href="/balance?stop={{date}}&plus={{steps_after_date}}">before</a> or <a href="/balance?stop={{date}}&plus={{steps_after_date + 1}}">after</a>
436 ]</span>
437 <table>
438 {% for l in booking_lines %}
439 {% if l.acc %}
440 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
441 {% else %}
442 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
443 {% endif %}
444 {% endfor %}
445 </table></p>
446 """)
447     footer = "</body>\n<html>"
448
449     def do_POST(self):
450         db = Database()
451         length = int(self.headers['content-length'])
452         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
453         parsed_url = urlparse(self.path)
454         lines = []
455         add_empty_line = None
456         start = int(postvars['start'][0])
457         end = int(postvars['end'][0])
458         if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
459             date = postvars['date'][0]
460             description = postvars['description'][0]
461             start_comment = postvars['line_0_comment'][0]
462             lines = [f'{date} {description} ; {start_comment}']
463             if 'line_0_add' in postvars.keys():
464                 add_empty_line = 0
465             i = j = 1
466             while f'line_{i}_comment' in postvars.keys():
467                 if f'line_{i}_delete' in postvars.keys():
468                     i += 1
469                     continue
470                 elif f'line_{i}_delete_after' in postvars.keys():
471                     break 
472                 elif f'line_{i}_add' in postvars.keys():
473                     add_empty_line = j
474                 account = postvars[f'line_{i}_account'][0]
475                 amount = postvars[f'line_{i}_amount'][0]
476                 currency = postvars[f'line_{i}_currency'][0]
477                 comment = postvars[f'line_{i}_comment'][0]
478                 i += 1
479                 new_main = f'{account} {amount} {currency}'
480                 if '' == new_main.rstrip() == comment.rstrip():  # don't write empty lines
481                     continue
482                 j += 1
483                 new_line = new_main
484                 if comment.rstrip() != '':
485                     new_line += f' ; {comment}'
486                 lines += [new_line]
487             if 'add_taxes' in postvars.keys():
488                 lines += db.add_taxes(lines, finish=False)
489             elif 'add_taxes2' in postvars.keys():
490                 lines += db.add_taxes(lines, finish=True)
491         elif '/add_free' == parsed_url.path:
492             lines = postvars['booking'][0].splitlines()
493         try:
494             if ('save' in postvars.keys()) or ('check' in postvars.keys()):
495                 _, _ = parse_lines(lines)
496             if 'save' in postvars.keys():
497                 if start == end == 0:
498                     db.append(lines)
499                     redir_url = f'/#last'
500                 else:
501                     db.replace(start, end, lines)
502                     redir_url = f'/#{start}'
503                 self.send_response(301)
504                 self.send_header('Location', redir_url)
505                 self.end_headers()
506             else:
507                 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
508                 self.send_response(200)
509                 self.send_header("Content-type", "text/html")
510                 self.end_headers()
511                 self.wfile.write(bytes(page, "utf-8"))
512         except HandledException as e:
513             self.send_response(400)
514             self.send_header("Content-type", "text/html")
515             self.end_headers()
516             page = f'{self.header}ERROR: {e}{self.footer}'
517             self.wfile.write(bytes(page, "utf-8"))
518
519     def do_GET(self):
520         self.send_response(200)
521         self.send_header("Content-type", "text/html")
522         self.end_headers()
523         db = Database()
524         parsed_url = urlparse(self.path)
525         page = self.header + ''
526         params = parse_qs(parsed_url.query)
527         start = int(params.get('start', ['0'])[0])
528         end = int(params.get('end', ['0'])[0])
529         if parsed_url.path == '/balance':
530             stop_date = params.get('stop', [None])[0]
531             plus = int(params.get('plus', [0])[0])
532             page += self.balance_as_html(db, stop_date, plus)
533         elif parsed_url.path == '/add_free':
534             page += self.add_free(db, start, end)
535         elif parsed_url.path == '/add_structured':
536             page += self.add_structured(db, start, end)
537         elif parsed_url.path == '/copy_free':
538             page += self.add_free(db, start, end, copy=True)
539         elif parsed_url.path == '/copy_structured':
540             page += self.add_structured(db, start, end, copy=True)
541         elif parsed_url.path == '/ledger2':
542             page += self.ledger2_as_html(db)
543         else:
544             page += self.ledger_as_html(db)
545         page += self.footer
546         self.wfile.write(bytes(page, "utf-8"))
547
548     def balance_as_html(self, db, stop_date=None, plus=0):
549         lines = []
550         bookings = db.bookings
551         if stop_date:
552             bookings = []
553             i = -1
554             for b in db.bookings:
555                 if b.date_string == stop_date:
556                     if -1 == i:
557                         i = 0
558                 if i >= plus:
559                     break
560                 if i > -1:
561                     i += 1
562                 bookings += [b]
563         account_tree, account_sums = bookings_to_account_tree(bookings)
564         def print_subtree(lines, indent, node, subtree, path):
565             line = f"{indent}{node}"
566             n_tabs = 5 - (len(line) // 8)
567             line += n_tabs * "\t"
568             if "€" in account_sums[path + node].keys():
569                 amount = account_sums[path + node]["€"]
570                 line += f"{amount:9.2f} €\t"
571             else:
572                 line += f"\t\t"
573             for currency, amount in account_sums[path + node].items():
574                 if currency != '€' and amount > 0:
575                     line += f"{amount:5.2f} {currency}\t"
576             lines += [line]
577             indent += "  "
578             for k, v in sorted(subtree.items()):
579                 print_subtree(lines, indent, k, v, path + node + ":")
580         for k, v in sorted(account_tree.items()):
581             print_subtree(lines, "", k, v, "")
582         content = "\n".join(lines)
583         return f"<pre>{content}</pre>"
584
585     def ledger_as_html(self, db):
586         elements_to_write = []
587         account_sums = {}  ##
588         nth_of_same_date = 0
589         same_date = ''
590         for booking in db.bookings:
591             if booking.date_string == same_date:
592                 nth_of_same_date += 1
593             else:
594                 same_date = booking.date_string
595                 nth_of_same_date = 0
596             booking_end = booking.start_line + len(booking.lines)
597             booking_lines = []
598             for booking_line in booking.lines[1:]:
599                 if booking_line == '':
600                     continue
601                 account = booking_line[0]  ##
602                 account_toks = account.split(':')  ##
603                 path = ''  ##
604                 for tok in account_toks: ##
605                     path += tok  ##
606                     if not path in account_sums.keys():  ##
607                         account_sums[path] = {}  ##
608                     path += ':'  ##
609                 moneys = []  ##
610                 money = ''
611                 if booking_line[1] is not None:
612                     moneys += [(booking_line[1], booking_line[2])]  ##
613                     money = f'{moneys[0][0]} {moneys[0][1]}'
614                 else:  ##
615                     for currency, amount in booking.sink.items():  ##
616                         moneys += {(amount, currency)}  ##
617                     money = '['  ##
618                     for m in moneys:  ##
619                         money += f'{m[0]} {m[1]} ' ##
620                     money += ']'  ##
621                 balance = ''  ##
622                 for amount, currency in moneys:  ##
623                     path = ''  ##
624                     for tok in account_toks:  ##
625                         path += tok  ##
626                         if not currency in account_sums[path].keys():  ##
627                             account_sums[path][currency] = 0  ##
628                         account_sums[path][currency] += amount  ##
629                         path += ':'   ##
630                     balance += f'{account_sums[account][currency]} {currency}'  ##
631                 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':balance}]  ##
632             elements_to_write += [self.booking_tmpl.render(
633                 start=booking.start_line,
634                 end=booking_end,
635                 date=booking.date_string,
636                 desc=booking.description,
637                 head_comment=db.comments[booking.start_line],
638                 steps_after_date=nth_of_same_date,
639                 booking_lines = booking_lines)]
640         return '\n'.join(elements_to_write)
641
642     def ledger2_as_html(self, db):
643         single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
644         elements_to_write = []
645         last_i = i = 0  ##
646         nth_of_same_date = 0
647         same_date = ''
648         for booking in db.bookings:
649             if booking.date_string == same_date:
650                 nth_of_same_date += 1
651             else:
652                 same_date = booking.date_string
653                 nth_of_same_date = 0
654             i = booking.start_line  ##
655             elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']  ##
656             booking_end = last_i = booking.start_line + len(booking.lines)
657             booking_lines = []
658             for booking_line in booking.lines[1:]:
659                  i += 1
660                  comment = db.comments[i]
661                  if booking_line == '':
662                      booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
663                      continue
664                  account = booking_line[0]
665                  money = ''
666                  if booking_line[1] is not None:
667                      money = f'{booking_line[1]} {booking_line[2]}'
668                  booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]  ##
669             elements_to_write += [self.booking_tmpl.render(
670                 start=booking.start_line,
671                 end=booking_end,
672                 date=booking.date_string,
673                 desc=booking.description,
674                 head_comment=db.comments[booking.start_line],
675                 steps_after_date=nth_of_same_date,
676                 booking_lines = booking_lines)]
677         elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
678         return '\n'.join(elements_to_write)
679
680     def add_free(self, db, start=0, end=0, copy=False):
681         tmpl = jinja2.Template("""
682 <form method="POST" action="{{action|e}}">
683 <textarea name="booking" rows=10 cols=80>
684 {% for line in lines %}{{ line }}
685 {% endfor %}
686 </textarea>
687 <input type="hidden" name="start" value={{start}} />
688 <input type="hidden" name="end" value={{end}} />
689 <input type="submit" name="save" value="save!">
690 </form>
691 """)
692         lines = db.get_lines(start, end)
693         if copy:
694             start = end = 0
695         return tmpl.render(action='add_free', start=start, end=end, lines=lines)
696
697     def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
698         tmpl = jinja2.Template("""
699 <form method="POST" action="{{action|e}}">
700 <input type="submit" name="check" value="check" />
701 <input type="submit" name="revert" value="revert" />
702 <input type="submit" name="add_taxes" value="add taxes" />
703 <input type="submit" name="add_taxes2" value="add taxes2" />
704 <br />
705 <input name="date" value="{{date|e}}" size=9 />
706 <input name="description" value="{{desc|e}}" list="descriptions" />
707 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
708 <input type="submit" name="line_0_add" value="[+]" />
709 <br />
710 {% for line in booking_lines %}
711 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
712 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
713 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
714 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
715 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
716 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
717 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
718 <br />
719 {% endfor %}
720 {% for name, items in datalist_sets.items() %}
721 <datalist id="{{name}}">
722 {% for item in items %}
723   <option value="{{item|e}}">{{item|e}}</option>
724 {% endfor %}
725 </datalist>
726 {% endfor %}
727 <input type="hidden" name="start" value={{start}} />
728 <input type="hidden" name="end" value={{end}} />
729 <input type="submit" name="save" value="save!">
730 </form>
731 """)
732         import datetime
733         lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
734         bookings, comments = parse_lines(lines, validate_bookings=False)
735         if len(bookings) > 1:
736             raise HandledException('can only edit single Booking')
737         if add_empty_line is not None:
738             comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
739             booking = bookings[0]
740             booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
741         action = 'add_structured'
742         datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
743         for b in db.bookings:
744             datalist_sets['descriptions'].add(b.description)
745             for account, moneys in b.account_changes.items():
746                 datalist_sets['accounts'].add(account)
747                 for currency in moneys.keys():
748                     datalist_sets['currencies'].add(currency)
749         content = ''
750         today = str(datetime.datetime.now())[:10]
751         booking_lines = []
752         if copy:
753             start = end = 0
754         desc = head_comment = ''
755         if len(bookings) == 0:
756             for i in range(1, 3):
757                 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
758             date=today
759         else:
760             booking = bookings[0]
761             desc = booking.description
762             date = today if copy else booking.date_string
763             head_comment=comments[0]
764             last_line = len(comments)
765             for i in range(1, len(comments)):
766                 account = amount = currency = ''
767                 if i < len(booking.lines) and booking.lines[i] != '':
768                     account = booking.lines[i][0]
769                     amount = booking.lines[i][1]
770                     currency = booking.lines[i][2]
771                 booking_lines += [{
772                         'i': i,
773                         'acc': account,
774                         'amt': amount,
775                         'curr': currency if currency else '',
776                         'comment': comments[i],
777                         'comm_cols': len(comments[i])}]
778         content += tmpl.render(
779                 action=action,
780                 date=date,
781                 desc=desc,
782                 head_comment=head_comment,
783                 booking_lines=booking_lines,
784                 datalist_sets=datalist_sets,
785                 start=start,
786                 end=end)
787         return content
788
789
790 if __name__ == "__main__":  
791     webServer = HTTPServer((hostName, serverPort), MyServer)
792     print(f"Server started http://{hostName}:{serverPort}")
793     try:
794         webServer.serve_forever()
795     except KeyboardInterrupt:
796         pass
797     webServer.server_close()
798     print("Server stopped.")