1 from http.server import BaseHTTPRequestHandler, HTTPServer
6 from datetime import datetime, timedelta
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.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 # collect modification times of numbered .bak files
283 bak_prefix = f'{self.db_file}.bak.'
286 bak_as = f'{bak_prefix}{i}'
287 while os.path.exists(bak_as):
288 mod_time = os.path.getmtime(bak_as)
289 backup_dates += [str(datetime.fromtimestamp(mod_time))]
291 bak_as = f'{bak_prefix}{i}'
293 # collect what numbered .bak files to save: the older, the fewer; for each
294 # timedelta, keep the newest file that's older
295 ages_to_keep = [timedelta(minutes=4**i) for i in range(0, 8)]
298 for age in ages_to_keep:
300 for i, date in enumerate(reversed(backup_dates)):
301 if datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') < limit:
302 unreversed_i = len(backup_dates) - i - 1
303 if unreversed_i not in to_save:
304 to_save += [unreversed_i]
307 # remove redundant backup files
311 source = f'{bak_prefix}{i}'
312 target = f'{bak_prefix}{j}'
313 shutil.move(source, target)
315 for i in range(j, len(backup_dates)):
317 os.remove(f'{bak_prefix}{i}')
318 except FileNotFoundError:
321 # put copy of current state at end of bak list
322 shutil.copy(self.db_file, f'{bak_prefix}{j}')
323 with open(self.db_file, mode) as f:
325 os.remove(self.lock_file)
327 def insert_at_date(self, lines, date):
328 start_at = len(self.real_lines)
329 for b in self.bookings:
330 if b.date_string == date:
331 start_at = b.start_line
333 elif b.date_string > date:
335 if start_at == len(self.real_lines):
337 return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
339 def update(self, start, end, lines, date):
340 total_lines = self.real_lines[:start] + self.real_lines[end:]
341 n_original_lines = end - start
342 start_at = len(total_lines)
343 for b in self.bookings:
344 if b.date_string == date:
345 if start_at == len(total_lines) or b.start_line == start:
346 start_at = b.start_line
347 if b.start_line > start:
348 start_at -= n_original_lines
349 elif b.date_string > date:
351 if start_at == len(total_lines):
353 return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
355 def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
356 total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
357 _, _ = parse_lines(lines)
358 text = '\n'.join(total_lines)
362 def get_nth_for_booking_of_start_line(self, start_line):
364 for b in self.bookings:
365 if b.start_line >= start_line:
370 def add_taxes(self, lines, finish=False):
372 bookings, _ = parse_lines(lines)
373 date = bookings[0].date_string
374 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
375 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
376 acc_kk = 'Expenses:KrankenKasse'
377 acc_est = 'Reserves:Einkommenssteuer'
378 acc_assets = 'Assets'
379 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
380 last_monthbreak_assets = 0
381 last_monthbreak_est = 0
382 last_monthbreak_kk_minimum = 0
383 last_monthbreak_kk_add = 0
387 months_passed = -int(finish)
388 for b in self.bookings:
389 if date == b.date_string:
391 acc_keys = b.account_changes.keys()
392 if acc_buffer in acc_keys:
393 buffer_expenses -= b.account_changes[acc_buffer]['€']
394 if acc_kk_add in acc_keys:
395 kk_expenses += b.account_changes[acc_kk_add]['€']
396 if acc_kk in acc_keys:
397 kk_expenses += b.account_changes[acc_kk]['€']
398 if acc_est in acc_keys:
399 est_expenses += b.account_changes[acc_est]['€']
400 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
403 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
404 last_monthbreak_est = b.account_changes[acc_est]['€']
405 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
406 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
407 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
409 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
410 _, account_sums = bookings_to_account_tree(bookings)
411 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
412 needed_income_before_kk = expenses_so_far
414 left_over = needed_income_before_kk - ESt_this_month
416 too_high = 2 * needed_income_before_kk
417 E0 = decimal.Decimal(10908)
418 E1 = decimal.Decimal(15999)
419 E2 = decimal.Decimal(62809)
420 E3 = decimal.Decimal(277825)
422 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
424 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
426 ESt = decimal.Decimal(0)
429 ESt = (decimal.Decimal(979.18) * y + 1400) * y
432 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
434 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
436 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
437 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
438 left_over = needed_income_before_kk - ESt_this_month
439 if abs(left_over - expenses_so_far) < 0.001:
441 elif left_over < expenses_so_far:
442 too_low = needed_income_before_kk
443 elif left_over > expenses_so_far:
444 too_high = needed_income_before_kk
445 needed_income_before_kk = too_low + (too_high - too_low)/2
446 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
447 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}€']
448 kk_minimum_income = 1131.67
449 if date < '2023-02-01':
450 kk_minimum_income = decimal.Decimal(1096.67)
451 kk_factor = decimal.Decimal(0.189)
452 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
453 elif date < '2023-08-01':
454 kk_factor = decimal.Decimal(0.191)
455 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
457 kk_factor = decimal.Decimal(0.197)
458 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
459 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
460 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
461 hit_kk_minimum_income_limit = False
462 if kk_add_so_far + kk_add < 0:
463 hit_kk_minimum_income_limit = True
464 kk_add_uncorrect = kk_add
465 kk_add = -(kk_add + kk_add_so_far)
466 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
468 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
470 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
471 if hit_kk_minimum_income_limit:
472 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']
474 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
475 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
477 diff += kk_minimum_tax
478 final_minus = expenses_so_far - old_needed_income_before_anything + diff
479 ret += [f' {acc_assets} {-diff} €']
480 ret += [f' {acc_assets} {final_minus} €']
481 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
483 ret += [f' {acc_buffer} {-final_minus} €']
485 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
489 class MyServer(BaseHTTPRequestHandler):
491 <meta charset="UTF-8">
493 body { color: #000000; }
494 table { margin-bottom: 2em; }
495 th, td { text-align: left }
496 input[type=number] { text-align: right; font-family: monospace; }
497 .money { font-family: monospace; text-align: right; }
498 .comment { font-style: italic; color: #777777; }
499 .meta { font-size: 0.75em; color: #777777; }
500 .full_line_comment { display: block; white-space: nowrap; width: 0; }
503 <a href="/">ledger</a>
504 <a href="/balance">balance</a>
505 <a href="/add_free">add free</a>
506 <a href="/add_structured">add structured</a>
509 booking_tmpl = jinja2.Template("""
510 <p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
511 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
512 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
513 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
514 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
515 | 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 %}
516 | <a href="/balance?stop={{nth+1}}">balance after</a>
519 {% for l in booking_lines %}
521 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
523 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
528 add_form_header = """<form method="POST" action="{{action|e}}">
529 <input type="submit" name="check" value="check" />
530 <input type="submit" name="revert" value="revert" />
532 add_form_footer = """
533 <input type="hidden" name="start" value={{start}} />
534 <input type="hidden" name="end" value={{end}} />
535 <input type="submit" name="save" value="save!">
538 footer = "</body>\n<html>"
542 parsed_url = urlparse(self.path)
543 length = int(self.headers['content-length'])
544 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
545 start = int(postvars['start'][0])
546 end = int(postvars['end'][0])
548 add_empty_line = None
551 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
552 lines, add_empty_line = self.booking_lines_from_postvars(postvars, db)
553 elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
554 lines = postvars['booking'][0].splitlines()
555 # validate where appropriate
556 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
557 _, _ = parse_lines(lines)
558 # if saving, process where to and where to redirect after
559 if 'save' in postvars.keys():
560 last_date = str(datetime.now())[:10]
561 if len(db.bookings) > 0:
562 last_date = db.bookings[-1].date_string
563 target_date = last_date[:]
564 first_line_tokens = lines[0].split() if len(lines) > 0 else ''
565 first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
567 datetime.strptime(first_token, '%Y-%m-%d')
568 target_date = first_token
571 if start == end == 0:
572 start = db.insert_at_date(lines, target_date)
573 nth = db.get_nth_for_booking_of_start_line(start)
575 new_start = db.update(start, end, lines, target_date)
576 nth = db.get_nth_for_booking_of_start_line(new_start)
577 if new_start > start:
579 redir_url = f'/#{nth}'
580 self.send_code_and_headers(302, [('Location', redir_url)])
581 # otherwise just re-build editing form
583 if '/add_structured' == parsed_url.path:
584 edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
586 edit_content = self.add_free(db, start, end)
587 self.send_HTML(self.header + edit_content + self.footer)
588 except HandledException as e:
593 parsed_url = urlparse(self.path)
594 params = parse_qs(parsed_url.query)
595 start = int(params.get('start', ['0'])[0])
596 end = int(params.get('end', ['0'])[0])
599 if parsed_url.path == '/balance':
600 stop = params.get('stop', [None])[0]
601 page += self.balance_as_html(db, stop)
602 elif parsed_url.path == '/add_free':
603 page += self.add_free(db, start, end)
604 elif parsed_url.path == '/add_structured':
605 page += self.add_structured(db, start, end)
606 elif parsed_url.path == '/copy_free':
607 page += self.add_free(db, start, end, copy=True)
608 elif parsed_url.path == '/copy_structured':
609 page += self.add_structured(db, start, end, copy=True)
610 elif parsed_url.path == '/move_up':
611 nth = self.move_up(db, start, end)
612 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
614 elif parsed_url.path == '/move_down':
615 nth = self.move_down(db, start, end)
616 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
619 page += self.ledger_as_html(db)
622 except HandledException as e:
625 def fail_400(self, e):
626 page = f'{self.header}ERROR: {e}{self.footer}'
627 self.send_HTML(page, 400)
629 def send_HTML(self, html, code=200):
630 self.send_code_and_headers(code, [('Content-type', 'text/html')])
631 self.wfile.write(bytes(html, "utf-8"))
633 def send_code_and_headers(self, code, headers=[]):
634 self.send_response(code)
635 for fieldname, content in headers:
636 self.send_header(fieldname, content)
639 def booking_lines_from_postvars(self, postvars, db):
640 add_empty_line = None
641 date = postvars['date'][0]
642 description = postvars['description'][0]
643 start_comment = postvars['line_0_comment'][0]
644 start_line = f'{date} {description}'
645 if start_comment.rstrip() != '':
646 start_line += f' ; {start_comment}'
648 if 'line_0_add' in postvars.keys():
651 while f'line_{i}_comment' in postvars.keys():
652 if f'line_{i}_delete' in postvars.keys():
655 elif f'line_{i}_delete_after' in postvars.keys():
657 elif f'line_{i}_add' in postvars.keys():
659 account = postvars[f'line_{i}_account'][0]
660 amount = postvars[f'line_{i}_amount'][0]
661 currency = postvars[f'line_{i}_currency'][0]
662 comment = postvars[f'line_{i}_comment'][0]
664 new_main = f' {account} {amount}'
665 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
667 if len(amount.rstrip()) > 0:
668 new_main += f' {currency}'
671 if comment.rstrip() != '':
672 new_line += f' ; {comment}'
674 if 'add_sink' in postvars.keys():
675 temp_lines = lines.copy() + ['_']
677 temp_bookings, _ = parse_lines(temp_lines)
678 for currency in temp_bookings[0].sink:
679 amount = temp_bookings[0].sink[currency]
680 lines += [f'Assets {amount:.2f} {currency}']
681 except HandledException:
683 if 'add_taxes' in postvars.keys():
684 lines += db.add_taxes(lines, finish=False)
685 elif 'add_taxes2' in postvars.keys():
686 lines += db.add_taxes(lines, finish=True)
687 return lines, add_empty_line
689 def balance_as_html(self, db, until=None):
690 bookings = db.bookings[:until if until is None else int(until)]
692 account_tree, account_sums = bookings_to_account_tree(bookings)
693 def print_subtree(lines, indent, node, subtree, path):
694 line = f"{indent}{node}"
695 n_tabs = 5 - (len(line) // 8)
696 line += n_tabs * "\t"
697 if "€" in account_sums[path + node].keys():
698 amount = account_sums[path + node]["€"]
699 line += f"{amount:9.2f} €\t"
702 for currency, amount in account_sums[path + node].items():
703 if currency != '€' and amount > 0:
704 line += f"{amount:5.2f} {currency}\t"
707 for k, v in sorted(subtree.items()):
708 print_subtree(lines, indent, k, v, path + node + ":")
709 for k, v in sorted(account_tree.items()):
710 print_subtree(lines, "", k, v, "")
711 content = "\n".join(lines)
712 return f"<pre>{content}</pre>"
714 def ledger_as_html(self, db):
715 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
716 elements_to_write = []
718 for nth, booking in enumerate(db.bookings):
719 move_up = nth > 0 and db.bookings[nth - 1].date_string == booking.date_string
720 move_down = nth < len(db.bookings) - 1 and db.bookings[nth + 1].date_string == booking.date_string
721 booking_end = last_i = booking.start_line + len(booking.lines)
723 i = booking.start_line ##
724 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
725 for booking_line in booking.lines[1:]:
727 comment = db.comments[i] ##
728 if booking_line == '':
729 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
731 account = booking_line[0]
733 if booking_line[1] is not None:
734 money = f'{booking_line[1]} {booking_line[2]}'
735 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
736 elements_to_write += [self.booking_tmpl.render(
738 start=booking.start_line,
740 date=booking.date_string,
741 desc=booking.description,
742 head_comment=db.comments[booking.start_line],
745 booking_lines = booking_lines)]
746 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != ''] #
747 return '\n'.join(elements_to_write)
749 def add_free(self, db, start=0, end=0, copy=False):
750 tmpl = jinja2.Template(self.add_form_header + """<br />
751 <textarea name="booking" rows=10 cols=80>
752 {% for line in lines %}{{ line }}
755 """ + self.add_form_footer)
756 lines = db.get_lines(start, end)
759 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
761 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
762 tmpl = jinja2.Template(self.add_form_header + """
763 <input type="submit" name="add_taxes" value="add taxes" />
764 <input type="submit" name="add_taxes2" value="add taxes2" />
765 <input type="submit" name="add_sink" value="add sink" />
767 <input name="date" value="{{date|e}}" size=9 />
768 <input name="description" value="{{desc|e}}" list="descriptions" />
769 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
770 <input type="submit" name="line_0_add" value="[+]" />
772 {% for line in booking_lines %}
773 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
774 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
775 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
776 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
777 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
778 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
779 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
782 {% for name, items in datalist_sets.items() %}
783 <datalist id="{{name}}">
784 {% for item in items %}
785 <option value="{{item|e}}">{{item|e}}</option>
789 """ + self.add_form_footer)
790 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
791 bookings, comments = parse_lines(lines, validate_bookings=False)
792 if len(bookings) > 1:
793 raise HandledException('can only structurally edit single Booking')
794 if add_empty_line is not None:
795 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
796 booking = bookings[0]
797 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
798 action = 'add_structured'
799 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
800 for b in db.bookings:
801 datalist_sets['descriptions'].add(b.description)
802 for account, moneys in b.account_changes.items():
803 datalist_sets['accounts'].add(account)
804 for currency in moneys.keys():
805 datalist_sets['currencies'].add(currency)
807 today = str(datetime.now())[:10]
811 desc = head_comment = ''
812 if len(bookings) == 0:
813 for i in range(1, 3):
814 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
817 booking = bookings[0]
818 desc = booking.description
819 date = today if copy else booking.date_string
820 head_comment=comments[0]
821 last_line = len(comments)
822 for i in range(1, len(comments)):
823 account = amount = currency = ''
824 if i < len(booking.lines) and booking.lines[i] != '':
825 account = booking.lines[i][0]
826 amount = booking.lines[i][1]
827 currency = booking.lines[i][2]
832 'curr': currency if currency else '€',
833 'comment': comments[i],
834 'comm_cols': len(comments[i])}]
835 content += tmpl.render(
839 head_comment=head_comment,
840 booking_lines=booking_lines,
841 datalist_sets=datalist_sets,
846 def move_up(self, db, start, end):
848 for redir_nth, b in enumerate(db.bookings):
849 if b.start_line >= start:
852 start_at = prev_booking.start_line
853 self.make_move(db, start, end, start_at)
856 def move_down(self, db, start, end):
858 for redir_nth, b in enumerate(db.bookings):
859 if b.start_line > start:
862 start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1
863 self.make_move(db, start, end, start_at)
866 def make_move(self, db, start, end, start_at):
867 lines = db.get_lines(start, end)
868 total_lines = db.real_lines[:start] + db.real_lines[end:]
869 db.write_lines_in_total_lines_at(total_lines, start_at, lines)
872 if __name__ == "__main__":
873 webServer = HTTPServer((hostName, serverPort), MyServer)
874 print(f"Server started http://{hostName}:{serverPort}")
876 webServer.serve_forever()
877 except KeyboardInterrupt:
879 webServer.server_close()
880 print("Server stopped.")