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