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):
70 inside_booking = False
71 date_string, description = None, None
76 lines = lines.copy() + [''] # to ensure a booking-ending last line
78 for i, line in enumerate(lines):
80 # we start with the case of an utterly empty line
82 stripped_line = line.rstrip()
83 if stripped_line == '':
85 # assume we finished a booking, finalize, and commit to DB
86 if len(booking_lines) < 2:
87 raise HandledException(f"{prefix} booking ends to early")
88 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
90 # expect new booking to follow so re-zeroall booking data
91 inside_booking = False
92 date_string, description = None, None
95 # if non-empty line, first get comment if any, and commit to DB
96 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
97 if len(split_by_comment) == 2:
98 comments[i] = split_by_comment[1].lstrip()
99 # 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
100 non_comment = split_by_comment[0].rstrip()
101 if non_comment.rstrip() == '':
103 booking_lines += ['']
105 # if we're starting a booking, parse by first-line pattern
106 if not inside_booking:
108 toks = non_comment.split(maxsplit=1)
109 date_string = toks[0]
111 datetime.datetime.strptime(date_string, '%Y-%m-%d')
113 raise HandledException(f"{prefix} bad date string: {date_string}")
114 if last_date > date_string:
115 raise HandledException(f"{prefix} out-of-order-date")
116 last_date = date_string
118 description = toks[1]
120 raise HandledException(f"{prefix} bad description: {description}")
121 inside_booking = True
122 booking_lines += [non_comment]
124 # otherwise, read as transfer data
125 toks = non_comment.split() # ignore specification's allowance of single spaces in names
127 raise HandledException(f"{prefix} too many booking line tokens: {toks}")
128 amount, currency = None, None
129 account_name = toks[0]
130 if account_name[0] == '[' and account_name[-1] == ']':
131 # ignore specification's differentiation of "virtual" accounts
132 account_name = account_name[1:-1]
133 decimal_chars = ".-0123456789"
137 amount = decimal.Decimal(toks[1])
139 except decimal.InvalidOperation:
141 amount = decimal.Decimal(toks[2])
142 except decimal.InvalidOperation:
143 raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
144 currency = toks[i_currency]
145 if currency[0] in decimal_chars:
146 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
149 inside_amount = False
150 inside_currency = False
154 for i, c in enumerate(value):
156 if c in decimal_chars:
159 inside_currency = True
161 if c in decimal_chars and len(amount_string) == 0:
162 inside_currency = False
168 if c not in decimal_chars:
169 if len(currency) > 0:
170 raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
171 inside_currency = True
172 inside_amount = False
175 if c == '-' and len(amount_string) > 1:
176 raise HandledException(f"{prefix} amount has non-start '-': {value}")
179 raise HandledException(f"{prefix} amount has multiple dots: {value}")
182 if len(currency) == 0:
183 raise HandledException(f"{prefix} currency missing: {value}")
184 if len(amount_string) > 0:
185 amount = decimal.Decimal(amount_string)
186 booking_lines += [(account_name, amount, currency)]
188 raise HandledException(f"{prefix} last booking unfinished")
189 return bookings, comments
194 def __init__(self, date_string, description, booking_lines, start_line, process=True):
195 self.date_string = date_string
196 self.description = description
197 self.lines = booking_lines
198 self.start_line = start_line
200 self.validate_booking_lines()
202 self.account_changes = self.parse_booking_lines_to_account_changes()
204 def validate_booking_lines(self):
205 prefix = f"booking at line {self.start_line}"
208 for line in self.lines[1:]:
211 _, amount, currency = line
214 raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
217 if currency not in sums:
219 sums[currency] += amount
220 if empty_values == 0:
221 for k, v in sums.items():
223 raise HandledException(f"{prefix} does not add up to zero / {k} {v}")
226 for k, v in sums.items():
230 raise HandledException(f"{prefix} has empty value that cannot be filled")
232 def parse_booking_lines_to_account_changes(self):
236 for line in self.lines[1:]:
239 account, amount, currency = line
241 sink_account = account
243 apply_booking_to_account_balances(account_changes, account, currency, amount)
244 if currency not in debt:
245 debt[currency] = amount
247 debt[currency] += amount
249 for currency, amount in debt.items():
250 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
251 self.sink[currency] = -amount
252 return account_changes
260 self.db_file = db_name + ".json"
261 self.lock_file = db_name+ ".lock"
265 if os.path.exists(self.db_file):
266 with open(self.db_file, "r") as f:
267 self.real_lines += [l.rstrip() for l in f.readlines()]
268 ret = parse_lines(self.real_lines)
269 self.bookings += ret[0]
270 self.comments += ret[1]
272 def get_lines(self, start, end):
273 return self.real_lines[start:end]
275 def write_db(self, text, mode='w'):
277 if os.path.exists(self.lock_file):
278 raise HandledException('Sorry, lock file!')
279 f = open(self.lock_file, 'w+')
282 # always back up most recent to .bak
283 bakpath = f'{self.db_file}.bak'
284 shutil.copy(self.db_file, bakpath)
286 # collect modification times of numbered .bak files
287 bak_prefix = f'{bakpath}.'
290 bak_as = f'{bak_prefix}{i}'
291 while os.path.exists(bak_as):
292 mod_time = os.path.getmtime(bak_as)
293 backup_dates += [str(datetime.datetime.fromtimestamp(mod_time))]
295 bak_as = f'{bak_prefix}{i}'
297 # collect what numbered .bak files to save:
298 # shrink datetime string right to left character by character,
299 # on each step add the oldest file whose mtime still fits the pattern
300 # (privilege older files to keep existing longer)
303 now = str(datetime.datetime.now())[:datetime_len]
304 while datetime_len > 2:
305 # assume backup_dates starts with oldest dates
306 for i, date in enumerate(backup_dates):
307 if date[:datetime_len] == now:
312 now = now[:datetime_len]
314 # remove redundant backup files
318 source = f'{bak_prefix}{i}'
319 target = f'{bak_prefix}{j}'
320 shutil.move(source, target)
322 for i in range(j, len(backup_dates)):
324 os.remove(f'{bak_prefix}{i}')
325 except FileNotFoundError:
328 # put second backup copy of current state at end of bak list
329 shutil.copy(self.db_file, f'{bak_prefix}{j}')
330 with open(self.db_file, mode) as f:
332 os.remove(self.lock_file)
334 def insert_at_date(self, lines, date):
335 start_at = len(self.real_lines)
336 for b in self.bookings:
337 if b.date_string == date:
338 start_at = b.start_line
340 elif b.date_string > date:
342 if start_at == len(self.real_lines):
344 return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
346 def update(self, start, end, lines, date):
347 total_lines = self.real_lines[:start] + self.real_lines[end:]
348 n_original_lines = end - start
349 start_at = len(total_lines)
350 for b in self.bookings:
351 if b.date_string == date:
352 if start_at == len(total_lines) or b.start_line == start:
353 start_at = b.start_line
354 if b.start_line > start:
355 start_at -= n_original_lines
356 elif b.date_string > date:
358 if start_at == len(total_lines):
360 return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
362 def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
363 total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
364 _, _ = parse_lines(lines)
365 text = '\n'.join(total_lines)
369 def get_nth_for_booking_of_start_line(self, start_line):
371 for b in self.bookings:
372 if b.start_line >= start_line:
377 def add_taxes(self, lines, finish=False):
379 bookings, _ = parse_lines(lines)
380 date = bookings[0].date_string
381 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
382 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
383 acc_kk = 'Expenses:KrankenKasse'
384 acc_est = 'Reserves:Einkommenssteuer'
385 acc_assets = 'Assets'
386 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
387 last_monthbreak_assets = 0
388 last_monthbreak_est = 0
389 last_monthbreak_kk_minimum = 0
390 last_monthbreak_kk_add = 0
394 months_passed = -int(finish)
395 for b in self.bookings:
396 if date == b.date_string:
398 acc_keys = b.account_changes.keys()
399 if acc_buffer in acc_keys:
400 buffer_expenses -= b.account_changes[acc_buffer]['€']
401 if acc_kk_add in acc_keys:
402 kk_expenses += b.account_changes[acc_kk_add]['€']
403 if acc_kk in acc_keys:
404 kk_expenses += b.account_changes[acc_kk]['€']
405 if acc_est in acc_keys:
406 est_expenses += b.account_changes[acc_est]['€']
407 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
410 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
411 last_monthbreak_est = b.account_changes[acc_est]['€']
412 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
413 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
414 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
416 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
417 _, account_sums = bookings_to_account_tree(bookings)
418 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
419 needed_income_before_kk = expenses_so_far
421 left_over = needed_income_before_kk - ESt_this_month
423 too_high = 2 * needed_income_before_kk
424 E0 = decimal.Decimal(10908)
425 E1 = decimal.Decimal(15999)
426 E2 = decimal.Decimal(62809)
427 E3 = decimal.Decimal(277825)
429 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
431 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
433 ESt = decimal.Decimal(0)
436 ESt = (decimal.Decimal(979.18) * y + 1400) * y
439 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
441 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
443 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
444 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
445 left_over = needed_income_before_kk - ESt_this_month
446 if abs(left_over - expenses_so_far) < 0.001:
448 elif left_over < expenses_so_far:
449 too_low = needed_income_before_kk
450 elif left_over > expenses_so_far:
451 too_high = needed_income_before_kk
452 needed_income_before_kk = too_low + (too_high - too_low)/2
453 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
454 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}€']
455 kk_minimum_income = 1131.67
456 if date < '2023-02-01':
457 kk_minimum_income = decimal.Decimal(1096.67)
458 kk_factor = decimal.Decimal(0.189)
459 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
460 elif date < '2023-08-01':
461 kk_factor = decimal.Decimal(0.191)
462 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
464 kk_factor = decimal.Decimal(0.197)
465 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
466 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
467 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
468 hit_kk_minimum_income_limit = False
469 if kk_add_so_far + kk_add < 0:
470 hit_kk_minimum_income_limit = True
471 kk_add_uncorrect = kk_add
472 kk_add = -(kk_add + kk_add_so_far)
473 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
475 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
477 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
478 if hit_kk_minimum_income_limit:
479 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']
481 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
482 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
484 diff += kk_minimum_tax
485 final_minus = expenses_so_far - old_needed_income_before_anything + diff
486 ret += [f' {acc_assets} {-diff} €']
487 ret += [f' {acc_assets} {final_minus} €']
488 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
490 ret += [f' {acc_buffer} {-final_minus} €']
492 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
496 class MyServer(BaseHTTPRequestHandler):
498 <meta charset="UTF-8">
500 body { color: #000000; }
501 table { margin-bottom: 2em; }
502 th, td { text-align: left }
503 input[type=number] { text-align: right; font-family: monospace; }
504 .money { font-family: monospace; text-align: right; }
505 .comment { font-style: italic; color: #777777; }
506 .meta { font-size: 0.75em; color: #777777; }
507 .full_line_comment { display: block; white-space: nowrap; width: 0; }
510 <a href="/">ledger</a>
511 <a href="/balance">balance</a>
512 <a href="/add_free">add free</a>
513 <a href="/add_structured">add structured</a>
516 booking_tmpl = jinja2.Template("""
517 <p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
518 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
519 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
520 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
521 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
522 | move {% if move_up %}<a href="/move_up?start={{start}}&end={{end}}">up</a>{% else %}up{% endif %}/{% if move_down %}<a href="/move_down?start={{start}}&end={{end}}">down</a>{% else %}down{% endif %}
523 | <a href="/balance?stop={{nth+1}}">balance after</a>
526 {% for l in booking_lines %}
528 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
530 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
535 add_form_header = """<form method="POST" action="{{action|e}}">
536 <input type="submit" name="check" value="check" />
537 <input type="submit" name="revert" value="revert" />
539 add_form_footer = """
540 <input type="hidden" name="start" value={{start}} />
541 <input type="hidden" name="end" value={{end}} />
542 <input type="submit" name="save" value="save!">
545 footer = "</body>\n<html>"
549 parsed_url = urlparse(self.path)
550 length = int(self.headers['content-length'])
551 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
552 start = int(postvars['start'][0])
553 end = int(postvars['end'][0])
555 add_empty_line = None
558 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
559 lines, add_empty_line = self.booking_lines_from_postvars(postvars, db)
560 elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
561 lines = postvars['booking'][0].splitlines()
562 # validate where appropriate
563 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
564 _, _ = parse_lines(lines)
565 # if saving, process where to and where to redirect after
566 if 'save' in postvars.keys():
567 last_date = str(datetime.datetime.now())[:10]
568 if len(db.bookings) > 0:
569 last_date = db.bookings[-1].date_string
570 target_date = last_date[:]
571 first_line_tokens = lines[0].split() if len(lines) > 0 else ''
572 first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
574 datetime.datetime.strptime(first_token, '%Y-%m-%d')
575 target_date = first_token
578 if start == end == 0:
579 start = db.insert_at_date(lines, target_date)
580 nth = db.get_nth_for_booking_of_start_line(start)
582 new_start = db.update(start, end, lines, target_date)
583 nth = db.get_nth_for_booking_of_start_line(new_start)
584 if new_start > start:
586 redir_url = f'/#{nth}'
587 self.send_code_and_headers(302, [('Location', redir_url)])
588 # otherwise just re-build editing form
590 if '/add_structured' == parsed_url.path:
591 edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
593 edit_content = self.add_free(db, start, end)
594 self.send_HTML(self.header + edit_content + self.footer)
595 except HandledException as e:
600 parsed_url = urlparse(self.path)
601 params = parse_qs(parsed_url.query)
602 start = int(params.get('start', ['0'])[0])
603 end = int(params.get('end', ['0'])[0])
606 if parsed_url.path == '/balance':
607 stop = params.get('stop', [None])[0]
608 page += self.balance_as_html(db, stop)
609 elif parsed_url.path == '/add_free':
610 page += self.add_free(db, start, end)
611 elif parsed_url.path == '/add_structured':
612 page += self.add_structured(db, start, end)
613 elif parsed_url.path == '/copy_free':
614 page += self.add_free(db, start, end, copy=True)
615 elif parsed_url.path == '/copy_structured':
616 page += self.add_structured(db, start, end, copy=True)
617 elif parsed_url.path == '/move_up':
618 nth = self.move_up(db, start, end)
619 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
621 elif parsed_url.path == '/move_down':
622 nth = self.move_down(db, start, end)
623 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
626 page += self.ledger_as_html(db)
629 except HandledException as e:
632 def fail_400(self, e):
633 page = f'{self.header}ERROR: {e}{self.footer}'
634 self.send_HTML(page, 400)
636 def send_HTML(self, html, code=200):
637 self.send_code_and_headers(code, [('Content-type', 'text/html')])
638 self.wfile.write(bytes(html, "utf-8"))
640 def send_code_and_headers(self, code, headers=[]):
641 self.send_response(code)
642 for fieldname, content in headers:
643 self.send_header(fieldname, content)
646 def booking_lines_from_postvars(self, postvars, db):
647 add_empty_line = None
648 date = postvars['date'][0]
649 description = postvars['description'][0]
650 start_comment = postvars['line_0_comment'][0]
651 start_line = f'{date} {description}'
652 if start_comment.rstrip() != '':
653 start_line += f' ; {start_comment}'
655 if 'line_0_add' in postvars.keys():
658 while f'line_{i}_comment' in postvars.keys():
659 if f'line_{i}_delete' in postvars.keys():
662 elif f'line_{i}_delete_after' in postvars.keys():
664 elif f'line_{i}_add' in postvars.keys():
666 account = postvars[f'line_{i}_account'][0]
667 amount = postvars[f'line_{i}_amount'][0]
668 currency = postvars[f'line_{i}_currency'][0]
669 comment = postvars[f'line_{i}_comment'][0]
671 new_main = f' {account} {amount}'
672 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
674 if len(amount.rstrip()) > 0:
675 new_main += f' {currency}'
678 if comment.rstrip() != '':
679 new_line += f' ; {comment}'
681 if 'add_sink' in postvars.keys():
682 temp_lines = lines.copy() + ['_']
684 temp_bookings, _ = parse_lines(temp_lines)
685 for currency in temp_bookings[0].sink:
686 amount = temp_bookings[0].sink[currency]
687 lines += [f'Assets {amount:.2f} {currency}']
688 except HandledException:
690 if 'add_taxes' in postvars.keys():
691 lines += db.add_taxes(lines, finish=False)
692 elif 'add_taxes2' in postvars.keys():
693 lines += db.add_taxes(lines, finish=True)
694 return lines, add_empty_line
696 def balance_as_html(self, db, until=None):
697 bookings = db.bookings[:until if until is None else int(until)]
699 account_tree, account_sums = bookings_to_account_tree(bookings)
700 def print_subtree(lines, indent, node, subtree, path):
701 line = f"{indent}{node}"
702 n_tabs = 5 - (len(line) // 8)
703 line += n_tabs * "\t"
704 if "€" in account_sums[path + node].keys():
705 amount = account_sums[path + node]["€"]
706 line += f"{amount:9.2f} €\t"
709 for currency, amount in account_sums[path + node].items():
710 if currency != '€' and amount > 0:
711 line += f"{amount:5.2f} {currency}\t"
714 for k, v in sorted(subtree.items()):
715 print_subtree(lines, indent, k, v, path + node + ":")
716 for k, v in sorted(account_tree.items()):
717 print_subtree(lines, "", k, v, "")
718 content = "\n".join(lines)
719 return f"<pre>{content}</pre>"
721 def ledger_as_html(self, db):
722 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
723 elements_to_write = []
725 for nth, booking in enumerate(db.bookings):
726 move_up = nth > 0 and db.bookings[nth - 1].date_string == booking.date_string
727 move_down = nth < len(db.bookings) - 1 and db.bookings[nth + 1].date_string == booking.date_string
728 booking_end = last_i = booking.start_line + len(booking.lines)
730 i = booking.start_line ##
731 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
732 for booking_line in booking.lines[1:]:
734 comment = db.comments[i] ##
735 if booking_line == '':
736 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
738 account = booking_line[0]
740 if booking_line[1] is not None:
741 money = f'{booking_line[1]} {booking_line[2]}'
742 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
743 elements_to_write += [self.booking_tmpl.render(
745 start=booking.start_line,
747 date=booking.date_string,
748 desc=booking.description,
749 head_comment=db.comments[booking.start_line],
752 booking_lines = booking_lines)]
753 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != ''] #
754 return '\n'.join(elements_to_write)
756 def add_free(self, db, start=0, end=0, copy=False):
757 tmpl = jinja2.Template(self.add_form_header + """<br />
758 <textarea name="booking" rows=10 cols=80>
759 {% for line in lines %}{{ line }}
762 """ + self.add_form_footer)
763 lines = db.get_lines(start, end)
766 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
768 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
769 tmpl = jinja2.Template(self.add_form_header + """
770 <input type="submit" name="add_taxes" value="add taxes" />
771 <input type="submit" name="add_taxes2" value="add taxes2" />
772 <input type="submit" name="add_sink" value="add sink" />
774 <input name="date" value="{{date|e}}" size=9 />
775 <input name="description" value="{{desc|e}}" list="descriptions" />
776 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
777 <input type="submit" name="line_0_add" value="[+]" />
779 {% for line in booking_lines %}
780 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
781 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
782 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
783 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
784 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
785 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
786 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
789 {% for name, items in datalist_sets.items() %}
790 <datalist id="{{name}}">
791 {% for item in items %}
792 <option value="{{item|e}}">{{item|e}}</option>
796 """ + self.add_form_footer)
797 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
798 bookings, comments = parse_lines(lines, validate_bookings=False)
799 if len(bookings) > 1:
800 raise HandledException('can only structurally edit single Booking')
801 if add_empty_line is not None:
802 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
803 booking = bookings[0]
804 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
805 action = 'add_structured'
806 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
807 for b in db.bookings:
808 datalist_sets['descriptions'].add(b.description)
809 for account, moneys in b.account_changes.items():
810 datalist_sets['accounts'].add(account)
811 for currency in moneys.keys():
812 datalist_sets['currencies'].add(currency)
814 today = str(datetime.datetime.now())[:10]
818 desc = head_comment = ''
819 if len(bookings) == 0:
820 for i in range(1, 3):
821 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
824 booking = bookings[0]
825 desc = booking.description
826 date = today if copy else booking.date_string
827 head_comment=comments[0]
828 last_line = len(comments)
829 for i in range(1, len(comments)):
830 account = amount = currency = ''
831 if i < len(booking.lines) and booking.lines[i] != '':
832 account = booking.lines[i][0]
833 amount = booking.lines[i][1]
834 currency = booking.lines[i][2]
839 'curr': currency if currency else '€',
840 'comment': comments[i],
841 'comm_cols': len(comments[i])}]
842 content += tmpl.render(
846 head_comment=head_comment,
847 booking_lines=booking_lines,
848 datalist_sets=datalist_sets,
853 def move_up(self, db, start, end):
855 for redir_nth, b in enumerate(db.bookings):
856 if b.start_line >= start:
859 start_at = prev_booking.start_line
860 self.make_move(db, start, end, start_at)
863 def move_down(self, db, start, end):
865 for redir_nth, b in enumerate(db.bookings):
866 if b.start_line > start:
869 start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1
870 self.make_move(db, start, end, start_at)
873 def make_move(self, db, start, end, start_at):
874 lines = db.get_lines(start, end)
875 total_lines = db.real_lines[:start] + db.real_lines[end:]
876 db.write_lines_in_total_lines_at(total_lines, start_at, lines)
879 if __name__ == "__main__":
880 webServer = HTTPServer((hostName, serverPort), MyServer)
881 print(f"Server started http://{hostName}:{serverPort}")
883 webServer.serve_forever()
884 except KeyboardInterrupt:
886 webServer.server_close()
887 print("Server stopped.")