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