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 .full_line_comment { display: block; white-space: nowrap; width: 0; }
421 <a href="/ledger">ledger</a>
422 <a href="/balance">balance</a>
423 <a href="/add_free">add free</a>
424 <a href="/add_structured">add structured</a>
427 footer = "</body>\n<html>"
431 length = int(self.headers['content-length'])
432 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
433 parsed_url = urlparse(self.path)
435 add_empty_line = None
436 start = int(postvars['start'][0])
437 end = int(postvars['end'][0])
438 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
439 date = postvars['date'][0]
440 description = postvars['description'][0]
441 start_comment = postvars['line_0_comment'][0]
442 lines = [f'{date} {description} ; {start_comment}']
443 if 'line_0_add' in postvars.keys():
446 while f'line_{i}_comment' in postvars.keys():
447 if f'line_{i}_delete' in postvars.keys():
450 if f'line_{i}_add' in postvars.keys():
452 account = postvars[f'line_{i}_account'][0]
453 amount = postvars[f'line_{i}_amount'][0]
454 currency = postvars[f'line_{i}_currency'][0]
455 comment = postvars[f'line_{i}_comment'][0]
457 new_main = f'{account} {amount} {currency}'
458 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines
462 if comment.rstrip() != '':
463 new_line += f' ; {comment}'
465 if 'add_taxes' in postvars.keys():
466 lines += db.add_taxes(lines, finish=False)
467 elif 'add_taxes2' in postvars.keys():
468 lines += db.add_taxes(lines, finish=True)
469 elif '/add_free' == parsed_url.path:
470 lines = postvars['booking'][0].splitlines()
472 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
473 _, _ = parse_lines(lines)
474 if 'save' in postvars.keys():
475 if start == end == 0:
477 redir_url = f'/#last'
479 db.replace(start, end, lines)
480 redir_url = f'/#{start}'
481 self.send_response(301)
482 self.send_header('Location', redir_url)
485 page = self.header + self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line) + self.footer
486 self.send_response(200)
487 self.send_header("Content-type", "text/html")
489 self.wfile.write(bytes(page, "utf-8"))
490 except HandledException as e:
491 self.send_response(400)
492 self.send_header("Content-type", "text/html")
494 page = f'{self.header}ERROR: {e}{self.footer}'
495 self.wfile.write(bytes(page, "utf-8"))
498 self.send_response(200)
499 self.send_header("Content-type", "text/html")
502 parsed_url = urlparse(self.path)
503 page = self.header + ''
504 params = parse_qs(parsed_url.query)
505 start = int(params.get('start', ['0'])[0])
506 end = int(params.get('end', ['0'])[0])
507 if parsed_url.path == '/balance':
508 stop_date = params.get('stop', [None])[0]
509 page += self.balance_as_html(db, stop_date)
510 elif parsed_url.path == '/add_free':
511 page += self.add_free(db, start, end)
512 elif parsed_url.path == '/add_structured':
513 page += self.add_structured(db, start, end)
514 elif parsed_url.path == '/copy_free':
515 page += self.add_free(db, start, end, copy=True)
516 elif parsed_url.path == '/copy_structured':
517 page += self.add_structured(db, start, end, copy=True)
518 elif parsed_url.path == '/ledger2':
519 page += self.ledger2_as_html(db)
521 page += self.ledger_as_html(db)
523 self.wfile.write(bytes(page, "utf-8"))
525 def balance_as_html(self, db, stop_date=None):
527 bookings = db.bookings
530 for b in db.bookings:
531 if b.date_string == stop_date:
534 account_tree, account_sums = bookings_to_account_tree(bookings)
535 def print_subtree(lines, indent, node, subtree, path):
536 line = f"{indent}{node}"
537 n_tabs = 5 - (len(line) // 8)
538 line += n_tabs * "\t"
539 if "€" in account_sums[path + node].keys():
540 amount = account_sums[path + node]["€"]
541 line += f"{amount:9.2f} €\t"
544 for currency, amount in account_sums[path + node].items():
545 if currency != '€' and amount > 0:
546 line += f"{amount:5.2f} {currency}\t"
549 for k, v in sorted(subtree.items()):
550 print_subtree(lines, indent, k, v, path + node + ":")
551 for k, v in sorted(account_tree.items()):
552 print_subtree(lines, "", k, v, "")
553 content = "\n".join(lines)
554 return f"<pre>{content}</pre>"
556 def ledger2_as_html(self, db):
557 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
558 booking_tmpl = jinja2.Template("""
559 <p id="{{start}}"><a href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span>
560 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
561 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
562 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
563 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
565 {% for l in booking_lines %}
566 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="money">{{l.balance|e}}</td></tr>
570 elements_to_write = []
572 for booking in db.bookings:
573 i = booking.start_line
574 booking_end = booking.start_line + len(booking.lines)
576 for booking_line in booking.lines[1:]:
577 if booking_line == '':
579 account = booking_line[0]
580 account_toks = account.split(':')
582 for tok in account_toks:
584 if not path in account_sums.keys():
585 account_sums[path] = {}
589 if booking_line[1] is not None:
590 moneys += [(booking_line[1], booking_line[2])]
591 money = f'{moneys[0][0]} {moneys[0][1]}'
593 for currency, amount in booking.sink.items():
594 moneys += {(amount, currency)}
597 money += f'{m[0]} {m[1]} '
600 for amount, currency in moneys:
602 for tok in account_toks:
604 if not currency in account_sums[path].keys():
605 account_sums[path][currency] = 0
606 account_sums[path][currency] += amount
608 balance += f'{account_sums[account][currency]} {currency}'
609 booking_lines += [{'acc': booking_line[0], 'money':money, 'balance':balance}]
610 elements_to_write += [booking_tmpl.render(
611 start=booking.start_line,
613 date=booking.date_string,
614 desc=booking.description,
615 head_comment=db.comments[booking.start_line],
616 booking_lines = booking_lines)]
617 return '\n'.join(elements_to_write)
619 def ledger_as_html(self, db):
620 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')
621 booking_tmpl = jinja2.Template("""
622 <p id="{{start}}"><a {% if last %}id="last"{% endif %} href="#{{start}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span>
623 [edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
624 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
625 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
626 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>]
628 {% for l in booking_lines %}
630 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
632 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
637 elements_to_write = []
639 last_start = db.bookings[-1].start_line
640 for booking in db.bookings:
641 i = booking.start_line
642 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != '']
643 booking_end = last_i = booking.start_line + len(booking.lines)
645 for booking_line in booking.lines[1:]:
647 comment = db.comments[i]
648 if booking_line == '':
649 booking_lines += [{'acc': None, 'money': None, 'comment': comment}]
651 account = booking_line[0]
653 if booking_line[1] is not None:
654 money = f'{booking_line[1]} {booking_line[2]}'
655 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]
656 elements_to_write += [booking_tmpl.render(
657 last=booking.start_line == last_start,
658 start=booking.start_line,
660 date=booking.date_string,
661 desc=booking.description,
662 head_comment=db.comments[booking.start_line],
663 booking_lines = booking_lines)]
664 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']
665 return '\n'.join(elements_to_write)
667 def add_free(self, db, start=0, end=0, copy=False):
668 tmpl = jinja2.Template("""
669 <form method="POST" action="{{action|e}}">
670 <textarea name="booking" rows=10 cols=80>
671 {% for line in lines %}{{ line }}
674 <input type="hidden" name="start" value={{start}} />
675 <input type="hidden" name="end" value={{end}} />
676 <input type="submit" name="save" value="save!">
679 lines = db.get_lines(start, end)
682 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
684 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
685 tmpl = jinja2.Template("""
686 <form method="POST" action="{{action|e}}">
687 <input type="submit" name="check" value="check" />
688 <input type="submit" name="revert" value="revert" />
689 <input type="submit" name="add_taxes" value="add taxes" />
690 <input type="submit" name="add_taxes2" value="add taxes2" />
692 <input name="date" value="{{date|e}}" size=9 />
693 <input name="description" value="{{desc|e}}" list="descriptions" />
694 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
695 <input type="submit" name="line_0_add" value="[+]" />
697 {% for line in booking_lines %}
698 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
699 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
700 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
701 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
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 <input type="hidden" name="start" value={{start}} />
714 <input type="hidden" name="end" value={{end}} />
715 <input type="submit" name="save" value="save!">
719 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
720 bookings, comments = parse_lines(lines, validate_bookings=False)
721 if len(bookings) > 1:
722 raise HandledException('can only edit single Booking')
723 if add_empty_line is not None:
724 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
725 booking = bookings[0]
726 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
727 action = 'add_structured'
728 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
729 for b in db.bookings:
730 datalist_sets['descriptions'].add(b.description)
731 for account, moneys in b.account_changes.items():
732 datalist_sets['accounts'].add(account)
733 for currency in moneys.keys():
734 datalist_sets['currencies'].add(currency)
736 today = str(datetime.datetime.now())[:10]
740 desc = head_comment = ''
741 if len(bookings) == 0:
742 for i in range(1, 3):
743 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '', 'comment': ''}]
746 booking = bookings[0]
747 desc = booking.description
748 date = today if copy else booking.date_string
749 head_comment=comments[0]
750 last_line = len(comments)
751 for i in range(1, len(comments)):
752 account = amount = currency = ''
753 if i < len(booking.lines) and booking.lines[i] != '':
754 account = booking.lines[i][0]
755 amount = booking.lines[i][1]
756 currency = booking.lines[i][2]
761 'curr': currency if currency else '',
762 'comment': comments[i],
763 'comm_cols': len(comments[i])}]
764 content += tmpl.render(
768 head_comment=head_comment,
769 booking_lines=booking_lines,
770 datalist_sets=datalist_sets,
776 if __name__ == "__main__":
777 webServer = HTTPServer((hostName, serverPort), MyServer)
778 print(f"Server started http://{hostName}:{serverPort}")
780 webServer.serve_forever()
781 except KeyboardInterrupt:
783 webServer.server_close()
784 print("Server stopped.")