1 from http.server import BaseHTTPRequestHandler, HTTPServer
7 from urllib.parse import parse_qs, urlparse
12 class HandledException(Exception):
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
22 account_sums[account][currency] += amount
25 def bookings_to_account_tree(bookings):
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)
32 def collect_branches(account_name, path):
35 while len(path_copy) > 0:
36 step = path_copy.pop(0)
38 toks = account_name.split(":", maxsplit=1)
40 if parent in node.keys():
46 k, v = collect_branches(toks[1], path + [parent])
47 if k not in child.keys():
52 for account_name in sorted(account_sums.keys()):
53 k, v = collect_branches(account_name, [])
54 if k not in account_tree.keys():
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
69 def parse_lines(lines, validate_bookings=True):
71 inside_booking = False
72 date_string, description = None, None
77 lines = lines.copy() + [''] # to ensure a booking-ending last line
79 for i, line in enumerate(lines):
81 # we start with the case of an utterly empty line
83 stripped_line = line.rstrip()
84 if stripped_line == '':
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)
91 # expect new booking to follow so re-zeroall booking data
92 inside_booking = False
93 date_string, description = None, None
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() == '':
104 booking_lines += ['']
106 # if we're starting a booking, parse by first-line pattern
107 if not inside_booking:
109 toks = non_comment.split(maxsplit=1)
110 date_string = toks[0]
112 datetime.datetime.strptime(date_string, '%Y-%m-%d')
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
119 description = toks[1]
121 raise HandledException(f"{prefix} bad description: {description}")
122 inside_booking = True
123 booking_lines += [non_comment]
125 # otherwise, read as transfer data
126 toks = non_comment.split() # ignore specification's allowance of single spaces in names
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"
138 amount = decimal.Decimal(toks[1])
140 except decimal.InvalidOperation:
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}")
150 inside_amount = False
151 inside_currency = False
155 for i, c in enumerate(value):
157 if c in decimal_chars:
160 inside_currency = True
162 if c in decimal_chars and len(amount_string) == 0:
163 inside_currency = False
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
176 if c == '-' and len(amount_string) > 1:
177 raise HandledException(f"{prefix} amount has non-start '-': {value}")
180 raise HandledException(f"{prefix} amount has multiple dots: {value}")
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)]
189 raise HandledException(f"{prefix} last booking unfinished")
190 return bookings, comments
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
201 self.validate_booking_lines()
203 self.account_changes = self.parse_booking_lines_to_account_changes()
205 def validate_booking_lines(self):
206 prefix = f"booking at line {self.start_line}"
209 for line in self.lines[1:]:
212 _, amount, currency = line
215 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
218 if currency not in sums:
220 sums[currency] += amount
221 if empty_values == 0:
222 for k, v in sums.items():
224 raise HandledException(f"{prefix} does not add up to zero / {k} {v}")
227 for k, v in sums.items():
231 raise HandledException(f"{prefix} has empty value that cannot be filled")
233 def parse_booking_lines_to_account_changes(self):
237 for line in self.lines[1:]:
240 account, amount, currency = line
242 sink_account = account
244 apply_booking_to_account_balances(account_changes, account, currency, amount)
245 if currency not in debt:
246 debt[currency] = amount
248 debt[currency] += amount
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
261 self.db_file = db_name + ".json"
262 self.lock_file = db_name+ ".lock"
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]
273 def get_lines(self, start, end):
274 return self.real_lines[start:end]
276 def write_db(self, text, mode='w'):
278 if os.path.exists(self.lock_file):
279 raise HandledException('Sorry, lock file!')
280 f = open(self.lock_file, 'w+')
283 # always back up most recent to .bak
284 bakpath = f'{self.db_file}.bak'
285 shutil.copy(self.db_file, bakpath)
287 # collect modification times of numbered .bak files
288 bak_prefix = f'{bakpath}.'
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))]
296 bak_as = f'{bak_prefix}{i}'
298 # collect what numbered .bak files to save
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:
309 now = now[:datetime_len]
311 # remove redundant backup files
313 for i in reversed(to_save):
315 source = f'{bak_prefix}{i}'
316 target = f'{bak_prefix}{j}'
317 shutil.move(source, target)
319 for i in range(j, len(backup_dates)):
321 os.remove(f'{bak_prefix}{i}')
322 except FileNotFoundError:
326 shutil.copy(self.db_file, f'{bak_prefix}{j}')
327 with open(self.db_file, mode) as f:
329 os.remove(self.lock_file)
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)
336 def append(self, lines):
337 text = '\n\n' + '\n'.join(lines) + '\n\n'
338 self.write_db(text, 'a')
340 def add_taxes(self, lines, finish=False):
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
357 months_passed = -int(finish)
358 for b in self.bookings:
359 if date == b.date_string:
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:
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
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
384 left_over = needed_income_before_kk - ESt_this_month
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)
392 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
394 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
396 ESt = decimal.Decimal(0)
399 ESt = (decimal.Decimal(979.18) * y + 1400) * y
402 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
404 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
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:
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'))
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'))
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}€)']
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
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}']
447 class MyServer(BaseHTTPRequestHandler):
449 <meta charset="UTF-8">
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; }
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>
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>
476 {% for l in booking_lines %}
478 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
480 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
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!">
491 footer = "</body>\n<html>"
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])
502 add_empty_line = None
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():
512 while f'line_{i}_comment' in postvars.keys():
513 if f'line_{i}_delete' in postvars.keys():
516 elif f'line_{i}_delete_after' in postvars.keys():
518 elif f'line_{i}_add' in postvars.keys():
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]
525 new_main = f' {account} {amount}'
526 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
528 if len(amount.rstrip()) > 0:
529 new_main += f' {currency}'
532 if comment.rstrip() != '':
533 new_line += f' ; {comment}'
535 if 'add_sink' in postvars.keys():
536 temp_lines = lines.copy() + ['_']
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:
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()
551 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
552 _, _ = parse_lines(lines)
554 if 'save' in postvars.keys():
555 if start == end == 0:
557 redir_url = f'/#last'
559 db.replace(start, end, lines)
561 for i, b in enumerate(db.bookings):
562 if b.start_line == start:
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
570 except HandledException as e:
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])
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)
593 page += self.ledger_as_html(db)
596 except HandledException as e:
599 def fail_400(self, e):
600 page = f'{self.header}ERROR: {e}{self.footer}'
601 self.send_HTML(page, 400)
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"))
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)
613 def balance_as_html(self, db, until=None):
614 bookings = db.bookings[:until if until is None else int(until)]
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"
626 for currency, amount in account_sums[path + node].items():
627 if currency != '€' and amount > 0:
628 line += f"{amount:5.2f} {currency}\t"
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>"
638 def ledger_as_html(self, db):
639 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
640 elements_to_write = []
642 for nth, booking in enumerate(db.bookings):
643 booking_end = last_i = booking.start_line + len(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:]:
649 comment = db.comments[i] ##
650 if booking_line == '':
651 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
653 account = booking_line[0]
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(
660 start=booking.start_line,
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)
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 }}
676 """ + self.add_form_footer)
677 lines = db.get_lines(start, end)
680 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
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" />
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="[+]" />
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>
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>
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)
731 today = str(datetime.datetime.now())[:10]
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': ''}]
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]
756 'curr': currency if currency else '€',
757 'comment': comments[i],
758 'comm_cols': len(comments[i])}]
759 content += tmpl.render(
763 head_comment=head_comment,
764 booking_lines=booking_lines,
765 datalist_sets=datalist_sets,
771 if __name__ == "__main__":
772 webServer = HTTPServer((hostName, serverPort), MyServer)
773 print(f"Server started http://{hostName}:{serverPort}")
775 webServer.serve_forever()
776 except KeyboardInterrupt:
778 webServer.server_close()
779 print("Server stopped.")