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