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:
299 # shrink datetime string right to left character by character,
300 # on each step add the oldest file whose mtime still fits the pattern
301 # (privilege older files to keep existing longer)
304 now = str(datetime.datetime.now())[:datetime_len]
305 while datetime_len > 2:
306 # assume backup_dates starts with oldest dates
307 for i, date in enumerate(backup_dates):
308 if date[:datetime_len] == now:
313 now = now[:datetime_len]
315 # remove redundant backup files
319 source = f'{bak_prefix}{i}'
320 target = f'{bak_prefix}{j}'
321 shutil.move(source, target)
323 for i in range(j, len(backup_dates)):
325 os.remove(f'{bak_prefix}{i}')
326 except FileNotFoundError:
329 # put second backup copy of current state at end of bak list
330 shutil.copy(self.db_file, f'{bak_prefix}{j}')
331 with open(self.db_file, mode) as f:
333 os.remove(self.lock_file)
335 def replace(self, start, end, lines):
336 total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
337 text = '\n'.join(total_lines)
340 def append(self, lines):
341 text = '\n\n' + '\n'.join(lines) + '\n\n'
342 self.write_db(text, 'a')
344 def get_nth_for_booking_of_start_line(self, start_line):
346 for b in self.bookings:
347 if b.start_line == start_line:
352 def add_taxes(self, lines, finish=False):
354 bookings, _ = parse_lines(lines)
355 date = bookings[0].date_string
356 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
357 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
358 acc_kk = 'Expenses:KrankenKasse'
359 acc_est = 'Reserves:Einkommenssteuer'
360 acc_assets = 'Assets'
361 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
362 last_monthbreak_assets = 0
363 last_monthbreak_est = 0
364 last_monthbreak_kk_minimum = 0
365 last_monthbreak_kk_add = 0
369 months_passed = -int(finish)
370 for b in self.bookings:
371 if date == b.date_string:
373 acc_keys = b.account_changes.keys()
374 if acc_buffer in acc_keys:
375 buffer_expenses -= b.account_changes[acc_buffer]['€']
376 if acc_kk_add in acc_keys:
377 kk_expenses += b.account_changes[acc_kk_add]['€']
378 if acc_kk in acc_keys:
379 kk_expenses += b.account_changes[acc_kk]['€']
380 if acc_est in acc_keys:
381 est_expenses += b.account_changes[acc_est]['€']
382 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
385 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
386 last_monthbreak_est = b.account_changes[acc_est]['€']
387 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
388 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
389 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
391 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
392 _, account_sums = bookings_to_account_tree(bookings)
393 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
394 needed_income_before_kk = expenses_so_far
396 left_over = needed_income_before_kk - ESt_this_month
398 too_high = 2 * needed_income_before_kk
399 E0 = decimal.Decimal(10908)
400 E1 = decimal.Decimal(15999)
401 E2 = decimal.Decimal(62809)
402 E3 = decimal.Decimal(277825)
404 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
406 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
408 ESt = decimal.Decimal(0)
411 ESt = (decimal.Decimal(979.18) * y + 1400) * y
414 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
416 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
418 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
419 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
420 left_over = needed_income_before_kk - ESt_this_month
421 if abs(left_over - expenses_so_far) < 0.001:
423 elif left_over < expenses_so_far:
424 too_low = needed_income_before_kk
425 elif left_over > expenses_so_far:
426 too_high = needed_income_before_kk
427 needed_income_before_kk = too_low + (too_high - too_low)/2
428 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
429 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}€']
430 kk_minimum_income = 1131.67
431 if date < '2023-02-01':
432 kk_minimum_income = decimal.Decimal(1096.67)
433 kk_factor = decimal.Decimal(0.189)
434 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
435 elif date < '2023-08-01':
436 kk_factor = decimal.Decimal(0.191)
437 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
439 kk_factor = decimal.Decimal(0.197)
440 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
441 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
442 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
443 hit_kk_minimum_income_limit = False
444 if kk_add_so_far + kk_add < 0:
445 hit_kk_minimum_income_limit = True
446 kk_add_uncorrect = kk_add
447 kk_add = -(kk_add + kk_add_so_far)
448 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
450 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
452 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
453 if hit_kk_minimum_income_limit:
454 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€ = {kk_add_uncorrect:.2f}€ would reduce current {acc_kk_dd} ({kk_add_so_far:.2f}€) below 0']
456 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
457 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
459 diff += kk_minimum_tax
460 final_minus = expenses_so_far - old_needed_income_before_anything + diff
461 ret += [f' {acc_assets} {-diff} €']
462 ret += [f' {acc_assets} {final_minus} €']
463 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
465 ret += [f' {acc_buffer} {-final_minus} €']
467 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
471 class MyServer(BaseHTTPRequestHandler):
473 <meta charset="UTF-8">
475 body { color: #000000; }
476 table { margin-bottom: 2em; }
477 th, td { text-align: left }
478 input[type=number] { text-align: right; font-family: monospace; }
479 .money { font-family: monospace; text-align: right; }
480 .comment { font-style: italic; color: #777777; }
481 .meta { font-size: 0.75em; color: #777777; }
482 .full_line_comment { display: block; white-space: nowrap; width: 0; }
485 <a href="/">ledger</a>
486 <a href="/balance">balance</a>
487 <a href="/add_free">add free</a>
488 <a href="/add_structured">add structured</a>
491 booking_tmpl = jinja2.Template("""
492 <p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
493 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
494 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
495 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
496 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
497 | <a href="/balance?stop={{nth+1}}">balance after</a>
500 {% for l in booking_lines %}
502 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
504 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
509 add_form_header = """<form method="POST" action="{{action|e}}">
510 <input type="submit" name="check" value="check" />
511 <input type="submit" name="revert" value="revert" />
513 add_form_footer = """
514 <input type="hidden" name="start" value={{start}} />
515 <input type="hidden" name="end" value={{end}} />
516 <input type="submit" name="save" value="save!">
519 footer = "</body>\n<html>"
523 parsed_url = urlparse(self.path)
524 length = int(self.headers['content-length'])
525 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
526 start = int(postvars['start'][0])
527 end = int(postvars['end'][0])
529 add_empty_line = None
532 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
533 lines, add_empty_line = self.booking_lines_from_postvars(postvars, db)
534 elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
535 lines = postvars['booking'][0].splitlines()
536 # validate where appropriate
537 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
538 _, _ = parse_lines(lines)
539 # if saving, process where to and where to redirect after
540 if 'save' in postvars.keys():
541 if start == end == 0:
543 redir_url = f'/#last'
545 db.replace(start, end, lines)
546 nth = db.get_nth_for_booking_of_start_line(start)
547 redir_url = f'/#{nth}'
548 self.send_code_and_headers(301, [('Location', redir_url)])
549 # otherwise just re-build editing form
551 if '/add_structured' == parsed_url.path:
552 edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
554 edit_content = self.add_free(db, start, end)
555 self.send_HTML(self.header + edit_content + self.footer)
556 except HandledException as e:
561 parsed_url = urlparse(self.path)
562 params = parse_qs(parsed_url.query)
563 start = int(params.get('start', ['0'])[0])
564 end = int(params.get('end', ['0'])[0])
567 if parsed_url.path == '/balance':
568 stop = params.get('stop', [None])[0]
569 page += self.balance_as_html(db, stop)
570 elif parsed_url.path == '/add_free':
571 page += self.add_free(db, start, end)
572 elif parsed_url.path == '/add_structured':
573 page += self.add_structured(db, start, end)
574 elif parsed_url.path == '/copy_free':
575 page += self.add_free(db, start, end, copy=True)
576 elif parsed_url.path == '/copy_structured':
577 page += self.add_structured(db, start, end, copy=True)
579 page += self.ledger_as_html(db)
582 except HandledException as e:
585 def fail_400(self, e):
586 page = f'{self.header}ERROR: {e}{self.footer}'
587 self.send_HTML(page, 400)
589 def send_HTML(self, html, code=200):
590 self.send_code_and_headers(code, [('Content-type', 'text/html')])
591 self.wfile.write(bytes(html, "utf-8"))
593 def send_code_and_headers(self, code, headers=[]):
594 self.send_response(code)
595 for fieldname, content in headers:
596 self.send_header(fieldname, content)
599 def booking_lines_from_postvars(self, postvars, db):
600 add_empty_line = None
601 date = postvars['date'][0]
602 description = postvars['description'][0]
603 start_comment = postvars['line_0_comment'][0]
604 start_line = f'{date} {description}'
605 if start_comment.rstrip() != '':
606 start_line += f' ; {start_comment}'
608 if 'line_0_add' in postvars.keys():
611 while f'line_{i}_comment' in postvars.keys():
612 if f'line_{i}_delete' in postvars.keys():
615 elif f'line_{i}_delete_after' in postvars.keys():
617 elif f'line_{i}_add' in postvars.keys():
619 account = postvars[f'line_{i}_account'][0]
620 amount = postvars[f'line_{i}_amount'][0]
621 currency = postvars[f'line_{i}_currency'][0]
622 comment = postvars[f'line_{i}_comment'][0]
624 new_main = f' {account} {amount}'
625 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
627 if len(amount.rstrip()) > 0:
628 new_main += f' {currency}'
631 if comment.rstrip() != '':
632 new_line += f' ; {comment}'
634 if 'add_sink' in postvars.keys():
635 temp_lines = lines.copy() + ['_']
637 temp_bookings, _ = parse_lines(temp_lines)
638 for currency in temp_bookings[0].sink:
639 amount = temp_bookings[0].sink[currency]
640 lines += [f'Assets {amount:.2f} {currency}']
641 except HandledException:
643 if 'add_taxes' in postvars.keys():
644 lines += db.add_taxes(lines, finish=False)
645 elif 'add_taxes2' in postvars.keys():
646 lines += db.add_taxes(lines, finish=True)
647 return lines, add_empty_line
649 def balance_as_html(self, db, until=None):
650 bookings = db.bookings[:until if until is None else int(until)]
652 account_tree, account_sums = bookings_to_account_tree(bookings)
653 def print_subtree(lines, indent, node, subtree, path):
654 line = f"{indent}{node}"
655 n_tabs = 5 - (len(line) // 8)
656 line += n_tabs * "\t"
657 if "€" in account_sums[path + node].keys():
658 amount = account_sums[path + node]["€"]
659 line += f"{amount:9.2f} €\t"
662 for currency, amount in account_sums[path + node].items():
663 if currency != '€' and amount > 0:
664 line += f"{amount:5.2f} {currency}\t"
667 for k, v in sorted(subtree.items()):
668 print_subtree(lines, indent, k, v, path + node + ":")
669 for k, v in sorted(account_tree.items()):
670 print_subtree(lines, "", k, v, "")
671 content = "\n".join(lines)
672 return f"<pre>{content}</pre>"
674 def ledger_as_html(self, db):
675 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
676 elements_to_write = []
678 for nth, booking in enumerate(db.bookings):
679 booking_end = last_i = booking.start_line + len(booking.lines)
681 i = booking.start_line ##
682 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
683 for booking_line in booking.lines[1:]:
685 comment = db.comments[i] ##
686 if booking_line == '':
687 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
689 account = booking_line[0]
691 if booking_line[1] is not None:
692 money = f'{booking_line[1]} {booking_line[2]}'
693 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
694 elements_to_write += [self.booking_tmpl.render(
696 start=booking.start_line,
698 date=booking.date_string,
699 desc=booking.description,
700 head_comment=db.comments[booking.start_line],
701 booking_lines = booking_lines)]
702 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != ''] #
703 return '\n'.join(elements_to_write)
705 def add_free(self, db, start=0, end=0, copy=False):
706 tmpl = jinja2.Template(self.add_form_header + """<br />
707 <textarea name="booking" rows=10 cols=80>
708 {% for line in lines %}{{ line }}
711 """ + self.add_form_footer)
712 lines = db.get_lines(start, end)
715 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
717 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
718 tmpl = jinja2.Template(self.add_form_header + """
719 <input type="submit" name="add_taxes" value="add taxes" />
720 <input type="submit" name="add_taxes2" value="add taxes2" />
721 <input type="submit" name="add_sink" value="add sink" />
723 <input name="date" value="{{date|e}}" size=9 />
724 <input name="description" value="{{desc|e}}" list="descriptions" />
725 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
726 <input type="submit" name="line_0_add" value="[+]" />
728 {% for line in booking_lines %}
729 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
730 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
731 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
732 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
733 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
734 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
735 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
738 {% for name, items in datalist_sets.items() %}
739 <datalist id="{{name}}">
740 {% for item in items %}
741 <option value="{{item|e}}">{{item|e}}</option>
745 """ + self.add_form_footer)
746 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
747 bookings, comments = parse_lines(lines, validate_bookings=False)
748 if len(bookings) > 1:
749 raise HandledException('can only structurally edit single Booking')
750 if add_empty_line is not None:
751 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
752 booking = bookings[0]
753 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
754 action = 'add_structured'
755 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
756 for b in db.bookings:
757 datalist_sets['descriptions'].add(b.description)
758 for account, moneys in b.account_changes.items():
759 datalist_sets['accounts'].add(account)
760 for currency in moneys.keys():
761 datalist_sets['currencies'].add(currency)
763 today = str(datetime.datetime.now())[:10]
767 desc = head_comment = ''
768 if len(bookings) == 0:
769 for i in range(1, 3):
770 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
773 booking = bookings[0]
774 desc = booking.description
775 date = today if copy else booking.date_string
776 head_comment=comments[0]
777 last_line = len(comments)
778 for i in range(1, len(comments)):
779 account = amount = currency = ''
780 if i < len(booking.lines) and booking.lines[i] != '':
781 account = booking.lines[i][0]
782 amount = booking.lines[i][1]
783 currency = booking.lines[i][2]
788 'curr': currency if currency else '€',
789 'comment': comments[i],
790 'comm_cols': len(comments[i])}]
791 content += tmpl.render(
795 head_comment=head_comment,
796 booking_lines=booking_lines,
797 datalist_sets=datalist_sets,
803 if __name__ == "__main__":
804 webServer = HTTPServer((hostName, serverPort), MyServer)
805 print(f"Server started http://{hostName}:{serverPort}")
807 webServer.serve_forever()
808 except KeyboardInterrupt:
810 webServer.server_close()
811 print("Server stopped.")