1 from http.server import BaseHTTPRequestHandler, HTTPServer
7 from urllib.parse import parse_qs, urlparse
12 class HandledException(Exception):
16 def handled_error_exit(msg):
17 print(f"ERROR: {msg}")
21 def apply_booking_to_account_balances(account_sums, account, currency, amount):
22 if not account in account_sums:
23 account_sums[account] = {currency: amount}
24 elif not currency in account_sums[account].keys():
25 account_sums[account][currency] = amount
27 account_sums[account][currency] += amount
30 def bookings_to_account_tree(bookings):
32 for booking in bookings:
33 for account, changes in booking.account_changes.items():
34 for currency, amount in changes.items():
35 apply_booking_to_account_balances(account_sums, account, currency, amount)
37 def collect_branches(account_name, path):
40 while len(path_copy) > 0:
41 step = path_copy.pop(0)
43 toks = account_name.split(":", maxsplit=1)
45 if parent in node.keys():
51 k, v = collect_branches(toks[1], path + [parent])
52 if k not in child.keys():
57 for account_name in sorted(account_sums.keys()):
58 k, v = collect_branches(account_name, [])
59 if k not in account_tree.keys():
62 account_tree[k].update(v)
63 def collect_totals(parent_path, tree_node):
64 for k, v in tree_node.items():
65 child_path = parent_path + ":" + k
66 for currency, amount in collect_totals(child_path, v).items():
67 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
68 return account_sums[parent_path]
69 for account_name in account_tree.keys():
70 account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
71 return account_tree, account_sums
74 def parse_lines(lines, validate_bookings=True):
76 inside_booking = False
77 date_string, description = None, None
82 lines = lines.copy() + [''] # to ensure a booking-ending last line
83 for i, line in enumerate(lines):
85 # we start with the case of an utterly empty line
87 stripped_line = line.rstrip()
88 if stripped_line == '':
90 # assume we finished a booking, finalize, and commit to DB
91 if len(booking_lines) < 2:
92 raise HandledException(f"{prefix} booking ends to early")
93 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
95 # expect new booking to follow so re-zeroall booking data
96 inside_booking = False
97 date_string, description = None, None
100 # if non-empty line, first get comment if any, and commit to DB
101 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
102 if len(split_by_comment) == 2:
103 comments[i] = split_by_comment[1].lstrip()
104 # 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
105 non_comment = split_by_comment[0].rstrip()
106 if non_comment.rstrip() == '':
108 booking_lines += ['']
110 # if we're starting a booking, parse by first-line pattern
111 if not inside_booking:
113 toks = non_comment.split(maxsplit=1)
114 date_string = toks[0]
116 datetime.datetime.strptime(date_string, '%Y-%m-%d')
118 raise HandledException(f"{prefix} bad date string: {date_string}")
120 description = toks[1]
122 raise HandledException(f"{prefix} bad description: {description}")
123 inside_booking = True
124 booking_lines += [non_comment]
126 # otherwise, read as transfer data
127 toks = non_comment.split() # ignore specification's allowance of single spaces in names
129 raise HandledException(f"{prefix} too many booking line tokens: {toks}")
130 amount, currency = None, None
131 account_name = toks[0]
132 if account_name[0] == '[' and account_name[-1] == ']':
133 # ignore specification's differentiation of "virtual" accounts
134 account_name = account_name[1:-1]
135 decimal_chars = ".-0123456789"
139 amount = decimal.Decimal(toks[1])
141 except decimal.InvalidOperation:
143 amount = decimal.Decimal(toks[2])
144 except decimal.InvalidOperation:
145 raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
146 currency = toks[i_currency]
147 if currency[0] in decimal_chars:
148 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
151 inside_amount = False
152 inside_currency = False
156 for i, c in enumerate(value):
158 if c in decimal_chars:
161 inside_currency = True
163 if c in decimal_chars and len(amount_string) == 0:
164 inside_currency = False
170 if c not in decimal_chars:
171 if len(currency) > 0:
172 raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
173 inside_currency = True
174 inside_amount = False
177 if c == '-' and len(amount_string) > 1:
178 raise HandledException(f"{prefix} amount has non-start '-': {value}")
181 raise HandledException(f"{prefix} amount has multiple dots: {value}")
184 if len(amount_string) == 0:
185 raise HandledException(f"{prefix} amount missing: {value}")
186 if len(currency) == 0:
187 raise HandledException(f"{prefix} currency missing: {value}")
188 amount = decimal.Decimal(amount_string)
189 booking_lines += [(account_name, amount, currency)]
191 raise HandledException(f"{prefix} last booking unfinished")
192 return bookings, comments
197 def __init__(self, date_string, description, booking_lines, start_line, process=True):
198 self.date_string = date_string
199 self.description = description
200 self.lines = booking_lines
201 self.start_line = start_line
203 self.validate_booking_lines()
205 self.account_changes = self.parse_booking_lines_to_account_changes()
207 def validate_booking_lines(self):
208 prefix = f"booking at line {self.start_line}"
211 for line in self.lines[1:]:
214 _, amount, currency = line
217 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
220 if currency not in sums:
222 sums[currency] += amount
223 if empty_values == 0:
224 for k, v in sums.items():
226 raise HandledException(f"{prefix} does not add up to zero / {k} {v}")
229 for k, v in sums.items():
233 raise HandledException(f"{prefix} has empty value that cannot be filled")
235 def parse_booking_lines_to_account_changes(self):
239 for line in self.lines[1:]:
242 account, amount, currency = line
244 sink_account = account
246 apply_booking_to_account_balances(account_changes, account, currency, amount)
247 if currency not in debt:
248 debt[currency] = amount
250 debt[currency] += amount
252 for currency, amount in debt.items():
253 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
254 self.sink[currency] = -amount
255 return account_changes
263 self.db_file = db_name + ".json"
264 self.lock_file = db_name+ ".lock"
268 if os.path.exists(self.db_file):
269 with open(self.db_file, "r") as f:
270 self.real_lines += [l.rstrip() for l in f.readlines()]
271 ret = parse_lines(self.real_lines)
272 self.bookings += ret[0]
273 self.comments += ret[1]
275 def get_lines(self, start, end):
276 return self.real_lines[start:end]
278 def replace(self, start, end, lines):
280 if os.path.exists(self.lock_file):
281 raise HandledException('Sorry, lock file!')
282 if os.path.exists(self.db_file):
283 shutil.copy(self.db_file, self.db_file + ".bak")
284 f = open(self.lock_file, 'w+')
286 total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
287 text = '\n'.join(total_lines)
288 with open(self.db_file, 'w') as f:
290 os.remove(self.lock_file)
292 def append(self, lines):
294 if os.path.exists(self.lock_file):
295 raise HandledException('Sorry, lock file!')
296 if os.path.exists(self.db_file):
297 shutil.copy(self.db_file, self.db_file + ".bak")
298 f = open(self.lock_file, 'w+')
300 with open(self.db_file, 'a') as f:
301 f.write('\n\n' + '\n'.join(lines) + '\n\n');
302 os.remove(self.lock_file)
304 def add_taxes(self, lines, finish=False):
306 bookings, _ = parse_lines(lines)
307 date = bookings[0].date_string
308 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
309 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
310 acc_kk = 'Expenses:KrankenKasse'
311 acc_est = 'Reserves:Einkommenssteuer'
312 acc_assets = 'Assets'
313 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
314 last_monthbreak_assets = 0
315 last_monthbreak_est = 0
316 last_monthbreak_kk_minimum = 0
317 last_monthbreak_kk_add = 0
321 for b in self.bookings:
322 if date == b.date_string:
324 acc_keys = b.account_changes.keys()
325 if acc_buffer in acc_keys:
326 buffer_expenses -= b.account_changes[acc_buffer]['€']
327 if acc_kk_add in acc_keys:
328 kk_expenses += b.account_changes[acc_kk_add]['€']
329 if acc_kk in acc_keys:
330 kk_expenses += b.account_changes[acc_kk]['€']
331 if acc_est in acc_keys:
332 est_expenses += b.account_changes[acc_est]['€']
333 if finish and acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
334 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
335 last_monthbreak_est = b.account_changes[acc_est]['€']
336 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
337 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
338 old_needed_income = last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum + last_monthbreak_est
340 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income}€']
341 _, account_sums = bookings_to_account_tree(bookings)
342 expenses_so_far = -1 * account_sums[acc_assets]['€'] - old_needed_income
343 needed_income_before_kk = expenses_so_far
345 left_over = needed_income_before_kk - ESt_this_month
347 too_high = 2 * needed_income_before_kk
348 E0 = decimal.Decimal(10908)
349 E1 = decimal.Decimal(15999)
350 E2 = decimal.Decimal(62809)
351 E3 = decimal.Decimal(277825)
352 months_passed = int(date[5:7]) - 1
354 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
356 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
358 ESt = decimal.Decimal(0)
361 ESt = (decimal.Decimal(979.18) * y + 1400) * y
364 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
366 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
368 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
369 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
370 left_over = needed_income_before_kk - ESt_this_month
371 if abs(left_over - expenses_so_far) < 0.001:
373 elif left_over < expenses_so_far:
374 too_low = needed_income_before_kk
375 elif left_over > expenses_so_far:
376 too_high = needed_income_before_kk
377 needed_income_before_kk = too_low + (too_high - too_low)/2
378 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
379 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}€']
380 kk_minimum_income = 1131.67
381 if date < '2023-02-01':
382 kk_minimum_income = decimal.Decimal(1096.67)
383 kk_factor = decimal.Decimal(0.189)
384 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
385 elif date < '2023-08-01':
386 kk_factor = decimal.Decimal(0.191)
387 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
389 kk_factor = decimal.Decimal(0.197)
390 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
391 kk_add = max(0, kk_factor * needed_income_before_kk - kk_minimum_tax)
392 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
394 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; max(0, {kk_factor:.3f} * {-(old_needed_income - last_monthbreak_est):.2f}€ - {kk_minimum_tax}€)']
396 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
397 ret += [f' {acc_kk_add} {kk_add}€ ; max(0, {kk_factor:.3f} * {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€)']
398 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
400 diff += kk_minimum_tax
401 final_minus = expenses_so_far + old_needed_income + diff
402 ret += [f' {acc_assets} {-diff} €']
403 ret += [f' {acc_assets} {final_minus} €']
404 ret += [f' {acc_buffer} {-final_minus} €']
408 class MyServer(BaseHTTPRequestHandler):
410 <meta charset="UTF-8">
412 body { color: #000000; }
413 table { margin-bottom: 2em; }
414 th, td { text-align: left }
415 input[type=number] { text-align: right; font-family: monospace; }
416 .money { font-family: monospace; text-align: right; }
417 .comment { font-style: italic; color: #777777; }
418 .meta { font-size: 0.75em; color: #777777; }
419 .full_line_comment { display: block; white-space: nowrap; width: 0; }
422 <a href="/ledger1">ledger1</a>
423 <a href="/ledger2">ledger2</a>
424 <a href="/balance">balance</a>
425 <a href="/add_free">add free</a>
426 <a href="/add_structured">add structured</a>
429 booking_tmpl = jinja2.Template("""
430 <p id="{{start}}"><a href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
431 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
432 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
433 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
434 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
435 | 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>
438 {% for l in booking_lines %}
440 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
442 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
447 footer = "</body>\n<html>"
451 length = int(self.headers['content-length'])
452 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
453 parsed_url = urlparse(self.path)
455 add_empty_line = None
456 start = int(postvars['start'][0])
457 end = int(postvars['end'][0])
458 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
459 date = postvars['date'][0]
460 description = postvars['description'][0]
461 start_comment = postvars['line_0_comment'][0]
462 lines = [f'{date} {description} ; {start_comment}']
463 if 'line_0_add' in postvars.keys():
466 while f'line_{i}_comment' in postvars.keys():
467 if f'line_{i}_delete' in postvars.keys():
470 elif f'line_{i}_delete_after' in postvars.keys():
472 elif f'line_{i}_add' in postvars.keys():
474 account = postvars[f'line_{i}_account'][0]
475 amount = postvars[f'line_{i}_amount'][0]
476 currency = postvars[f'line_{i}_currency'][0]
477 comment = postvars[f'line_{i}_comment'][0]
479 new_main = f'{account} {amount} {currency}'
480 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines
484 if comment.rstrip() != '':
485 new_line += f' ; {comment}'
487 if 'add_taxes' in postvars.keys():
488 lines += db.add_taxes(lines, finish=False)
489 elif 'add_taxes2' in postvars.keys():
490 lines += db.add_taxes(lines, finish=True)
491 elif '/add_free' == parsed_url.path:
492 lines = postvars['booking'][0].splitlines()
494 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
495 _, _ = parse_lines(lines)
496 if 'save' in postvars.keys():
497 if start == end == 0:
499 redir_url = f'/#last'
501 db.replace(start, end, lines)
502 redir_url = f'/#{start}'
503 self.send_response(301)
504 self.send_header('Location', redir_url)
507 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
508 self.send_response(200)
509 self.send_header("Content-type", "text/html")
511 self.wfile.write(bytes(page, "utf-8"))
512 except HandledException as e:
513 self.send_response(400)
514 self.send_header("Content-type", "text/html")
516 page = f'{self.header}ERROR: {e}{self.footer}'
517 self.wfile.write(bytes(page, "utf-8"))
520 self.send_response(200)
521 self.send_header("Content-type", "text/html")
524 parsed_url = urlparse(self.path)
525 page = self.header + ''
526 params = parse_qs(parsed_url.query)
527 start = int(params.get('start', ['0'])[0])
528 end = int(params.get('end', ['0'])[0])
529 if parsed_url.path == '/balance':
530 stop_date = params.get('stop', [None])[0]
531 plus = int(params.get('plus', [0])[0])
532 page += self.balance_as_html(db, stop_date, plus)
533 elif parsed_url.path == '/add_free':
534 page += self.add_free(db, start, end)
535 elif parsed_url.path == '/add_structured':
536 page += self.add_structured(db, start, end)
537 elif parsed_url.path == '/copy_free':
538 page += self.add_free(db, start, end, copy=True)
539 elif parsed_url.path == '/copy_structured':
540 page += self.add_structured(db, start, end, copy=True)
541 elif parsed_url.path == '/ledger2':
542 page += self.ledger2_as_html(db)
544 page += self.ledger_as_html(db)
546 self.wfile.write(bytes(page, "utf-8"))
548 def balance_as_html(self, db, stop_date=None, plus=0):
550 bookings = db.bookings
554 for b in db.bookings:
555 if b.date_string == stop_date:
563 account_tree, account_sums = bookings_to_account_tree(bookings)
564 def print_subtree(lines, indent, node, subtree, path):
565 line = f"{indent}{node}"
566 n_tabs = 5 - (len(line) // 8)
567 line += n_tabs * "\t"
568 if "€" in account_sums[path + node].keys():
569 amount = account_sums[path + node]["€"]
570 line += f"{amount:9.2f} €\t"
573 for currency, amount in account_sums[path + node].items():
574 if currency != '€' and amount > 0:
575 line += f"{amount:5.2f} {currency}\t"
578 for k, v in sorted(subtree.items()):
579 print_subtree(lines, indent, k, v, path + node + ":")
580 for k, v in sorted(account_tree.items()):
581 print_subtree(lines, "", k, v, "")
582 content = "\n".join(lines)
583 return f"<pre>{content}</pre>"
585 def ledger_as_html(self, db):
586 elements_to_write = []
590 for booking in db.bookings:
591 if booking.date_string == same_date:
592 nth_of_same_date += 1
594 same_date = booking.date_string
596 booking_end = booking.start_line + len(booking.lines)
598 for booking_line in booking.lines[1:]:
599 if booking_line == '':
601 account = booking_line[0] ##
602 account_toks = account.split(':') ##
604 for tok in account_toks: ##
606 if not path in account_sums.keys(): ##
607 account_sums[path] = {} ##
611 if booking_line[1] is not None:
612 moneys += [(booking_line[1], booking_line[2])] ##
613 money = f'{moneys[0][0]} {moneys[0][1]}'
615 for currency, amount in booking.sink.items(): ##
616 moneys += {(amount, currency)} ##
619 money += f'{m[0]} {m[1]} ' ##
622 for amount, currency in moneys: ##
624 for tok in account_toks: ##
626 if not currency in account_sums[path].keys(): ##
627 account_sums[path][currency] = 0 ##
628 account_sums[path][currency] += amount ##
630 balance += f'{account_sums[account][currency]} {currency}' ##
631 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':balance}] ##
632 elements_to_write += [self.booking_tmpl.render(
633 start=booking.start_line,
635 date=booking.date_string,
636 desc=booking.description,
637 head_comment=db.comments[booking.start_line],
638 steps_after_date=nth_of_same_date,
639 booking_lines = booking_lines)]
640 return '\n'.join(elements_to_write)
642 def ledger2_as_html(self, db):
643 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
644 elements_to_write = []
648 for booking in db.bookings:
649 if booking.date_string == same_date:
650 nth_of_same_date += 1
652 same_date = booking.date_string
654 i = booking.start_line ##
655 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
656 booking_end = last_i = booking.start_line + len(booking.lines)
658 for booking_line in booking.lines[1:]:
660 comment = db.comments[i]
661 if booking_line == '':
662 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
664 account = booking_line[0]
666 if booking_line[1] is not None:
667 money = f'{booking_line[1]} {booking_line[2]}'
668 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
669 elements_to_write += [self.booking_tmpl.render(
670 start=booking.start_line,
672 date=booking.date_string,
673 desc=booking.description,
674 head_comment=db.comments[booking.start_line],
675 steps_after_date=nth_of_same_date,
676 booking_lines = booking_lines)]
677 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
678 return '\n'.join(elements_to_write)
680 def add_free(self, db, start=0, end=0, copy=False):
681 tmpl = jinja2.Template("""
682 <form method="POST" action="{{action|e}}">
683 <textarea name="booking" rows=10 cols=80>
684 {% for line in lines %}{{ line }}
687 <input type="hidden" name="start" value={{start}} />
688 <input type="hidden" name="end" value={{end}} />
689 <input type="submit" name="save" value="save!">
692 lines = db.get_lines(start, end)
695 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
697 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
698 tmpl = jinja2.Template("""
699 <form method="POST" action="{{action|e}}">
700 <input type="submit" name="check" value="check" />
701 <input type="submit" name="revert" value="revert" />
702 <input type="submit" name="add_taxes" value="add taxes" />
703 <input type="submit" name="add_taxes2" value="add taxes2" />
705 <input name="date" value="{{date|e}}" size=9 />
706 <input name="description" value="{{desc|e}}" list="descriptions" />
707 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
708 <input type="submit" name="line_0_add" value="[+]" />
710 {% for line in booking_lines %}
711 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
712 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
713 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
714 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
715 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
716 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
717 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
720 {% for name, items in datalist_sets.items() %}
721 <datalist id="{{name}}">
722 {% for item in items %}
723 <option value="{{item|e}}">{{item|e}}</option>
727 <input type="hidden" name="start" value={{start}} />
728 <input type="hidden" name="end" value={{end}} />
729 <input type="submit" name="save" value="save!">
733 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
734 bookings, comments = parse_lines(lines, validate_bookings=False)
735 if len(bookings) > 1:
736 raise HandledException('can only edit single Booking')
737 if add_empty_line is not None:
738 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
739 booking = bookings[0]
740 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
741 action = 'add_structured'
742 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
743 for b in db.bookings:
744 datalist_sets['descriptions'].add(b.description)
745 for account, moneys in b.account_changes.items():
746 datalist_sets['accounts'].add(account)
747 for currency in moneys.keys():
748 datalist_sets['currencies'].add(currency)
750 today = str(datetime.datetime.now())[:10]
754 desc = head_comment = ''
755 if len(bookings) == 0:
756 for i in range(1, 3):
757 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
760 booking = bookings[0]
761 desc = booking.description
762 date = today if copy else booking.date_string
763 head_comment=comments[0]
764 last_line = len(comments)
765 for i in range(1, len(comments)):
766 account = amount = currency = ''
767 if i < len(booking.lines) and booking.lines[i] != '':
768 account = booking.lines[i][0]
769 amount = booking.lines[i][1]
770 currency = booking.lines[i][2]
775 'curr': currency if currency else '',
776 'comment': comments[i],
777 'comm_cols': len(comments[i])}]
778 content += tmpl.render(
782 head_comment=head_comment,
783 booking_lines=booking_lines,
784 datalist_sets=datalist_sets,
790 if __name__ == "__main__":
791 webServer = HTTPServer((hostName, serverPort), MyServer)
792 print(f"Server started http://{hostName}:{serverPort}")
794 webServer.serve_forever()
795 except KeyboardInterrupt:
797 webServer.server_close()
798 print("Server stopped.")