1 from http.server import BaseHTTPRequestHandler, HTTPServer
8 from urllib.parse import parse_qs, urlparse
13 class HandledException(Exception):
17 def handled_error_exit(msg):
18 print(f"ERROR: {msg}")
22 def apply_booking_to_account_balances(account_sums, account, currency, amount):
23 if not account in account_sums:
24 account_sums[account] = {currency: amount}
25 elif not currency in account_sums[account].keys():
26 account_sums[account][currency] = amount
28 account_sums[account][currency] += amount
31 def bookings_to_account_tree(bookings):
33 for booking in bookings:
34 for account, changes in booking.account_changes.items():
35 for currency, amount in changes.items():
36 apply_booking_to_account_balances(account_sums, account, currency, amount)
38 def collect_branches(account_name, path):
41 while len(path_copy) > 0:
42 step = path_copy.pop(0)
44 toks = account_name.split(":", maxsplit=1)
46 if parent in node.keys():
52 k, v = collect_branches(toks[1], path + [parent])
53 if k not in child.keys():
58 for account_name in sorted(account_sums.keys()):
59 k, v = collect_branches(account_name, [])
60 if k not in account_tree.keys():
63 account_tree[k].update(v)
64 def collect_totals(parent_path, tree_node):
65 for k, v in tree_node.items():
66 child_path = parent_path + ":" + k
67 for currency, amount in collect_totals(child_path, v).items():
68 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
69 return account_sums[parent_path]
70 for account_name in account_tree.keys():
71 account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
72 return account_tree, account_sums
75 def parse_lines(lines, validate_bookings=True):
77 inside_booking = False
78 date_string, description = None, None
83 lines = lines.copy() + [''] # to ensure a booking-ending last line
85 for i, line in enumerate(lines):
87 # we start with the case of an utterly empty line
89 stripped_line = line.rstrip()
90 if stripped_line == '':
92 # assume we finished a booking, finalize, and commit to DB
93 if len(booking_lines) < 2:
94 raise HandledException(f"{prefix} booking ends to early")
95 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
97 # expect new booking to follow so re-zeroall booking data
98 inside_booking = False
99 date_string, description = None, None
102 # if non-empty line, first get comment if any, and commit to DB
103 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
104 if len(split_by_comment) == 2:
105 comments[i] = split_by_comment[1].lstrip()
106 # 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
107 non_comment = split_by_comment[0].rstrip()
108 if non_comment.rstrip() == '':
110 booking_lines += ['']
112 # if we're starting a booking, parse by first-line pattern
113 if not inside_booking:
115 toks = non_comment.split(maxsplit=1)
116 date_string = toks[0]
118 datetime.datetime.strptime(date_string, '%Y-%m-%d')
120 raise HandledException(f"{prefix} bad date string: {date_string}")
121 if last_date > date_string:
122 raise HandledException(f"{prefix} out-of-order-date")
123 last_date = date_string
125 description = toks[1]
127 raise HandledException(f"{prefix} bad description: {description}")
128 inside_booking = True
129 booking_lines += [non_comment]
131 # otherwise, read as transfer data
132 toks = non_comment.split() # ignore specification's allowance of single spaces in names
134 raise HandledException(f"{prefix} too many booking line tokens: {toks}")
135 amount, currency = None, None
136 account_name = toks[0]
137 if account_name[0] == '[' and account_name[-1] == ']':
138 # ignore specification's differentiation of "virtual" accounts
139 account_name = account_name[1:-1]
140 decimal_chars = ".-0123456789"
144 amount = decimal.Decimal(toks[1])
146 except decimal.InvalidOperation:
148 amount = decimal.Decimal(toks[2])
149 except decimal.InvalidOperation:
150 raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
151 currency = toks[i_currency]
152 if currency[0] in decimal_chars:
153 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
156 inside_amount = False
157 inside_currency = False
161 for i, c in enumerate(value):
163 if c in decimal_chars:
166 inside_currency = True
168 if c in decimal_chars and len(amount_string) == 0:
169 inside_currency = False
175 if c not in decimal_chars:
176 if len(currency) > 0:
177 raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
178 inside_currency = True
179 inside_amount = False
182 if c == '-' and len(amount_string) > 1:
183 raise HandledException(f"{prefix} amount has non-start '-': {value}")
186 raise HandledException(f"{prefix} amount has multiple dots: {value}")
189 if len(currency) == 0:
190 raise HandledException(f"{prefix} currency missing: {value}")
191 if len(amount_string) > 0:
192 amount = decimal.Decimal(amount_string)
193 booking_lines += [(account_name, amount, currency)]
195 raise HandledException(f"{prefix} last booking unfinished")
196 return bookings, comments
201 def __init__(self, date_string, description, booking_lines, start_line, process=True):
202 self.date_string = date_string
203 self.description = description
204 self.lines = booking_lines
205 self.start_line = start_line
207 self.validate_booking_lines()
209 self.account_changes = self.parse_booking_lines_to_account_changes()
211 def validate_booking_lines(self):
212 prefix = f"booking at line {self.start_line}"
215 for line in self.lines[1:]:
218 _, amount, currency = line
221 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
224 if currency not in sums:
226 sums[currency] += amount
227 if empty_values == 0:
228 for k, v in sums.items():
230 raise HandledException(f"{prefix} does not add up to zero / {k} {v}")
233 for k, v in sums.items():
237 raise HandledException(f"{prefix} has empty value that cannot be filled")
239 def parse_booking_lines_to_account_changes(self):
243 for line in self.lines[1:]:
246 account, amount, currency = line
248 sink_account = account
250 apply_booking_to_account_balances(account_changes, account, currency, amount)
251 if currency not in debt:
252 debt[currency] = amount
254 debt[currency] += amount
256 for currency, amount in debt.items():
257 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
258 self.sink[currency] = -amount
259 return account_changes
267 self.db_file = db_name + ".json"
268 self.lock_file = db_name+ ".lock"
272 if os.path.exists(self.db_file):
273 with open(self.db_file, "r") as f:
274 self.real_lines += [l.rstrip() for l in f.readlines()]
275 ret = parse_lines(self.real_lines)
276 self.bookings += ret[0]
277 self.comments += ret[1]
279 def get_lines(self, start, end):
280 return self.real_lines[start:end]
282 def write_db(self, text, mode='w'):
284 if os.path.exists(self.lock_file):
285 raise HandledException('Sorry, lock file!')
286 f = open(self.lock_file, 'w+')
289 # always back up most recent to .bak
290 bakpath = f'{self.db_file}.bak'
291 shutil.copy(self.db_file, bakpath)
293 # collect modification times of numbered .bak files
294 bak_prefix = f'{bakpath}.'
297 bak_as = f'{bak_prefix}{i}'
298 while os.path.exists(bak_as):
299 mod_time = os.path.getmtime(bak_as)
300 backup_dates += [str(datetime.datetime.fromtimestamp(mod_time))]
302 bak_as = f'{bak_prefix}{i}'
304 # collect what numbered .bak files to save
307 now = str(datetime.datetime.now())[:datetime_len]
308 while datetime_len > 2:
309 for i, date in reversed(list(enumerate(backup_dates))):
310 if date[:datetime_len] == now:
315 now = now[:datetime_len]
317 # remove redundant backup files
319 for i in reversed(to_save):
321 source = f'{bak_prefix}{i}'
322 target = f'{bak_prefix}{j}'
323 shutil.move(source, target)
327 for i in range(j, len(backup_dates)):
330 os.remove(f'{bak_prefix}{i}')
331 except FileNotFoundError:
335 shutil.copy(self.db_file, f'{bak_prefix}{j}')
336 with open(self.db_file, mode) as f:
338 os.remove(self.lock_file)
340 def replace(self, start, end, lines):
341 total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
342 text = '\n'.join(total_lines)
345 def append(self, lines):
346 text = '\n\n' + '\n'.join(lines) + '\n\n'
347 self.write_db(text, 'a')
349 def add_taxes(self, lines, finish=False):
351 bookings, _ = parse_lines(lines)
352 date = bookings[0].date_string
353 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
354 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
355 acc_kk = 'Expenses:KrankenKasse'
356 acc_est = 'Reserves:Einkommenssteuer'
357 acc_assets = 'Assets'
358 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
359 last_monthbreak_assets = 0
360 last_monthbreak_est = 0
361 last_monthbreak_kk_minimum = 0
362 last_monthbreak_kk_add = 0
366 months_passed = -int(finish)
367 for b in self.bookings:
368 if date == b.date_string:
370 acc_keys = b.account_changes.keys()
371 if acc_buffer in acc_keys:
372 buffer_expenses -= b.account_changes[acc_buffer]['€']
373 if acc_kk_add in acc_keys:
374 kk_expenses += b.account_changes[acc_kk_add]['€']
375 if acc_kk in acc_keys:
376 kk_expenses += b.account_changes[acc_kk]['€']
377 if acc_est in acc_keys:
378 est_expenses += b.account_changes[acc_est]['€']
379 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
382 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
383 last_monthbreak_est = b.account_changes[acc_est]['€']
384 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
385 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
386 old_needed_income = last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum + last_monthbreak_est
388 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income}€']
389 _, account_sums = bookings_to_account_tree(bookings)
390 expenses_so_far = -1 * account_sums[acc_assets]['€'] - old_needed_income
391 needed_income_before_kk = expenses_so_far
393 left_over = needed_income_before_kk - ESt_this_month
395 too_high = 2 * needed_income_before_kk
396 E0 = decimal.Decimal(10908)
397 E1 = decimal.Decimal(15999)
398 E2 = decimal.Decimal(62809)
399 E3 = decimal.Decimal(277825)
401 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
403 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
405 ESt = decimal.Decimal(0)
408 ESt = (decimal.Decimal(979.18) * y + 1400) * y
411 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
413 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
415 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
416 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
417 left_over = needed_income_before_kk - ESt_this_month
418 if abs(left_over - expenses_so_far) < 0.001:
420 elif left_over < expenses_so_far:
421 too_low = needed_income_before_kk
422 elif left_over > expenses_so_far:
423 too_high = needed_income_before_kk
424 needed_income_before_kk = too_low + (too_high - too_low)/2
425 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
426 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}€']
427 kk_minimum_income = 1131.67
428 if date < '2023-02-01':
429 kk_minimum_income = decimal.Decimal(1096.67)
430 kk_factor = decimal.Decimal(0.189)
431 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
432 elif date < '2023-08-01':
433 kk_factor = decimal.Decimal(0.191)
434 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
436 kk_factor = decimal.Decimal(0.197)
437 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
438 kk_add = max(0, kk_factor * needed_income_before_kk - kk_minimum_tax)
439 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
441 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; max(0, {kk_factor:.3f} * {-(old_needed_income - last_monthbreak_est):.2f}€ - {kk_minimum_tax}€)']
443 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
444 ret += [f' {acc_kk_add} {kk_add}€ ; max(0, {kk_factor:.3f} * {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€)']
445 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
447 diff += kk_minimum_tax
448 final_minus = expenses_so_far + old_needed_income + diff
449 ret += [f' {acc_assets} {-diff} €']
450 ret += [f' {acc_assets} {final_minus} €']
451 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
452 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {-year_needed}']
456 class MyServer(BaseHTTPRequestHandler):
458 <meta charset="UTF-8">
460 body { color: #000000; }
461 table { margin-bottom: 2em; }
462 th, td { text-align: left }
463 input[type=number] { text-align: right; font-family: monospace; }
464 .money { font-family: monospace; text-align: right; }
465 .comment { font-style: italic; color: #777777; }
466 .meta { font-size: 0.75em; color: #777777; }
467 .full_line_comment { display: block; white-space: nowrap; width: 0; }
470 <a href="/ledger1">ledger1</a>
471 <a href="/ledger2">ledger2</a>
472 <a href="/balance">balance</a>
473 <a href="/add_free">add free</a>
474 <a href="/add_structured">add structured</a>
477 booking_tmpl = jinja2.Template("""
478 <p id="{{start}}"><a href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
479 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
480 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
481 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
482 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
483 | balance <a href="/balance?stop={{date}}&plus={{steps_after_date}}">before</a> or <a href="/balance?stop={{date}}&plus={{steps_after_date + 1}}">after</a>
486 {% for l in booking_lines %}
488 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
490 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
495 footer = "</body>\n<html>"
500 length = int(self.headers['content-length'])
501 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
502 parsed_url = urlparse(self.path)
504 add_empty_line = None
505 start = int(postvars['start'][0])
506 end = int(postvars['end'][0])
507 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
508 date = postvars['date'][0]
509 description = postvars['description'][0]
510 start_comment = postvars['line_0_comment'][0]
511 lines = [f'{date} {description} ; {start_comment}']
512 if 'line_0_add' in postvars.keys():
515 while f'line_{i}_comment' in postvars.keys():
516 if f'line_{i}_delete' in postvars.keys():
519 elif f'line_{i}_delete_after' in postvars.keys():
521 elif f'line_{i}_add' in postvars.keys():
523 account = postvars[f'line_{i}_account'][0]
524 amount = postvars[f'line_{i}_amount'][0]
525 currency = postvars[f'line_{i}_currency'][0]
526 comment = postvars[f'line_{i}_comment'][0]
528 new_main = f' {account} {amount}'
529 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
531 if len(amount.rstrip()) > 0:
532 new_main += f' {currency}'
535 if comment.rstrip() != '':
536 new_line += f' ; {comment}'
538 if 'add_sink' in postvars.keys():
539 temp_lines = lines.copy() + ['_']
541 temp_bookings, _ = parse_lines(temp_lines)
542 for currency in temp_bookings[0].sink:
543 amount = temp_bookings[0].sink[currency]
544 lines += [f'Assets {amount:.2f} {currency}']
545 except HandledException:
547 if 'add_taxes' in postvars.keys():
548 lines += db.add_taxes(lines, finish=False)
549 elif 'add_taxes2' in postvars.keys():
550 lines += db.add_taxes(lines, finish=True)
551 elif '/add_free' == parsed_url.path:
552 lines = postvars['booking'][0].splitlines()
553 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
554 _, _ = parse_lines(lines)
555 if 'save' in postvars.keys():
556 if start == end == 0:
558 redir_url = f'/#last'
560 db.replace(start, end, lines)
561 redir_url = f'/#{start}'
562 self.send_response(301)
563 self.send_header('Location', redir_url)
566 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
567 self.send_response(200)
568 self.send_header("Content-type", "text/html")
570 self.wfile.write(bytes(page, "utf-8"))
571 except HandledException as e:
572 self.send_response(400)
573 self.send_header("Content-type", "text/html")
575 page = f'{self.header}ERROR: {e}{self.footer}'
576 self.wfile.write(bytes(page, "utf-8"))
579 self.send_response(200)
580 self.send_header("Content-type", "text/html")
583 parsed_url = urlparse(self.path)
584 page = self.header + ''
585 params = parse_qs(parsed_url.query)
586 start = int(params.get('start', ['0'])[0])
587 end = int(params.get('end', ['0'])[0])
588 if parsed_url.path == '/balance':
589 stop_date = params.get('stop', [None])[0]
590 plus = int(params.get('plus', [0])[0])
591 page += self.balance_as_html(db, stop_date, plus)
592 elif parsed_url.path == '/add_free':
593 page += self.add_free(db, start, end)
594 elif parsed_url.path == '/add_structured':
595 page += self.add_structured(db, start, end)
596 elif parsed_url.path == '/copy_free':
597 page += self.add_free(db, start, end, copy=True)
598 elif parsed_url.path == '/copy_structured':
599 page += self.add_structured(db, start, end, copy=True)
600 elif parsed_url.path == '/ledger2':
601 page += self.ledger2_as_html(db)
603 page += self.ledger_as_html(db)
605 self.wfile.write(bytes(page, "utf-8"))
607 def balance_as_html(self, db, stop_date=None, plus=0):
609 bookings = db.bookings
613 for b in db.bookings:
614 if b.date_string == stop_date:
622 account_tree, account_sums = bookings_to_account_tree(bookings)
623 def print_subtree(lines, indent, node, subtree, path):
624 line = f"{indent}{node}"
625 n_tabs = 5 - (len(line) // 8)
626 line += n_tabs * "\t"
627 if "€" in account_sums[path + node].keys():
628 amount = account_sums[path + node]["€"]
629 line += f"{amount:9.2f} €\t"
632 for currency, amount in account_sums[path + node].items():
633 if currency != '€' and amount > 0:
634 line += f"{amount:5.2f} {currency}\t"
637 for k, v in sorted(subtree.items()):
638 print_subtree(lines, indent, k, v, path + node + ":")
639 for k, v in sorted(account_tree.items()):
640 print_subtree(lines, "", k, v, "")
641 content = "\n".join(lines)
642 return f"<pre>{content}</pre>"
644 def ledger2_as_html(self, db):
645 elements_to_write = []
649 for booking in db.bookings:
650 if booking.date_string == same_date:
651 nth_of_same_date += 1
653 same_date = booking.date_string
655 booking_end = booking.start_line + len(booking.lines)
657 for booking_line in booking.lines[1:]:
658 if booking_line == '':
660 account = booking_line[0] ##
661 account_toks = account.split(':') ##
663 for tok in account_toks: ##
665 if not path in account_sums.keys(): ##
666 account_sums[path] = {} ##
670 if booking_line[1] is not None:
671 moneys += [(booking_line[1], booking_line[2])] ##
672 money = f'{moneys[0][0]} {moneys[0][1]}'
674 for currency, amount in booking.sink.items(): ##
675 moneys += {(amount, currency)} ##
678 money += f'{m[0]} {m[1]} ' ##
681 for amount, currency in moneys: ##
683 for tok in account_toks: ##
685 if not currency in account_sums[path].keys(): ##
686 account_sums[path][currency] = 0 ##
687 account_sums[path][currency] += amount ##
689 balance += f'{account_sums[account][currency]} {currency}' ##
690 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':balance}] ##
691 elements_to_write += [self.booking_tmpl.render(
692 start=booking.start_line,
694 date=booking.date_string,
695 desc=booking.description,
696 head_comment=db.comments[booking.start_line],
697 steps_after_date=nth_of_same_date,
698 booking_lines = booking_lines)]
699 return '\n'.join(elements_to_write)
701 def ledger_as_html(self, db):
702 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
703 elements_to_write = []
707 for booking in db.bookings:
708 if booking.date_string == same_date:
709 nth_of_same_date += 1
711 same_date = booking.date_string
713 i = booking.start_line ##
714 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
715 booking_end = last_i = booking.start_line + len(booking.lines)
717 for booking_line in booking.lines[1:]:
719 comment = db.comments[i]
720 if booking_line == '':
721 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
723 account = booking_line[0]
725 if booking_line[1] is not None:
726 money = f'{booking_line[1]} {booking_line[2]}'
727 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
728 elements_to_write += [self.booking_tmpl.render(
729 start=booking.start_line,
731 date=booking.date_string,
732 desc=booking.description,
733 head_comment=db.comments[booking.start_line],
734 steps_after_date=nth_of_same_date,
735 booking_lines = booking_lines)]
736 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
737 return '\n'.join(elements_to_write)
739 def add_free(self, db, start=0, end=0, copy=False):
740 tmpl = jinja2.Template("""
741 <form method="POST" action="{{action|e}}">
742 <textarea name="booking" rows=10 cols=80>
743 {% for line in lines %}{{ line }}
746 <input type="hidden" name="start" value={{start}} />
747 <input type="hidden" name="end" value={{end}} />
748 <input type="submit" name="save" value="save!">
751 lines = db.get_lines(start, end)
754 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
756 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
757 tmpl = jinja2.Template("""
758 <form method="POST" action="{{action|e}}">
759 <input type="submit" name="check" value="check" />
760 <input type="submit" name="revert" value="revert" />
761 <input type="submit" name="add_taxes" value="add taxes" />
762 <input type="submit" name="add_taxes2" value="add taxes2" />
763 <input type="submit" name="add_sink" value="add sink" />
765 <input name="date" value="{{date|e}}" size=9 />
766 <input name="description" value="{{desc|e}}" list="descriptions" />
767 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
768 <input type="submit" name="line_0_add" value="[+]" />
770 {% for line in booking_lines %}
771 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
772 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
773 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
774 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
775 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
776 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
777 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
780 {% for name, items in datalist_sets.items() %}
781 <datalist id="{{name}}">
782 {% for item in items %}
783 <option value="{{item|e}}">{{item|e}}</option>
787 <input type="hidden" name="start" value={{start}} />
788 <input type="hidden" name="end" value={{end}} />
789 <input type="submit" name="save" value="save!">
792 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
793 bookings, comments = parse_lines(lines, validate_bookings=False)
794 if len(bookings) > 1:
795 raise HandledException('can only edit single Booking')
796 if add_empty_line is not None:
797 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
798 booking = bookings[0]
799 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
800 action = 'add_structured'
801 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
802 for b in db.bookings:
803 datalist_sets['descriptions'].add(b.description)
804 for account, moneys in b.account_changes.items():
805 datalist_sets['accounts'].add(account)
806 for currency in moneys.keys():
807 datalist_sets['currencies'].add(currency)
809 today = str(datetime.datetime.now())[:10]
813 desc = head_comment = ''
814 if len(bookings) == 0:
815 for i in range(1, 3):
816 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
819 booking = bookings[0]
820 desc = booking.description
821 date = today if copy else booking.date_string
822 head_comment=comments[0]
823 last_line = len(comments)
824 for i in range(1, len(comments)):
825 account = amount = currency = ''
826 if i < len(booking.lines) and booking.lines[i] != '':
827 account = booking.lines[i][0]
828 amount = booking.lines[i][1]
829 currency = booking.lines[i][2]
834 'curr': currency if currency else '€',
835 'comment': comments[i],
836 'comm_cols': len(comments[i])}]
837 content += tmpl.render(
841 head_comment=head_comment,
842 booking_lines=booking_lines,
843 datalist_sets=datalist_sets,
849 if __name__ == "__main__":
850 webServer = HTTPServer((hostName, serverPort), MyServer)
851 print(f"Server started http://{hostName}:{serverPort}")
853 webServer.serve_forever()
854 except KeyboardInterrupt:
856 webServer.server_close()
857 print("Server stopped.")