3 from datetime import datetime, timedelta
4 from urllib.parse import parse_qs, urlparse
5 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
6 from plomlib import PlomDB, PlomException, run_server, PlomHandler
8 db_path = '/home/plom/org/ledger2024.dat'
10 j2env = JinjaEnv(loader=JinjaFSLoader('ledger_templates'))
12 class EditableException(PlomException):
13 def __init__(self, booking_index, *args, **kwargs):
14 self.booking_index = booking_index
15 super().__init__(*args, **kwargs)
20 def __init__(self, text_line):
21 self.text_line = text_line
23 split_by_comment = text_line.rstrip().split(sep=';', maxsplit=1)
24 self.non_comment = split_by_comment[0].rstrip()
25 self.empty = len(split_by_comment) == 1 and len(self.non_comment) == 0
28 if len(split_by_comment) == 2:
29 self.comment = split_by_comment[1].lstrip()
35 # body { color: #000000; }
36 # table { margin-bottom: 2em; }
37 # th, td { text-align: left }
38 # input[type=number] { text-align: right; font-family: monospace; }
39 # .money { font-family: monospace; text-align: right; }
40 # .comment { font-style: italic; color: #777777; }
41 # .meta { font-size: 0.75em; color: #777777; }
42 # .full_line_comment { display: block; white-space: nowrap; width: 0; }
45 # <a href="{{prefix}}/ledger">ledger</a>
46 # <a href="{{prefix}}/ledger2">ledger2</a>
47 # <a href="{{prefix}}/balance">balance</a>
48 # <a href="{{prefix}}/balance2">balance2</a>
49 # <a href="{{prefix}}/add_free">add free</a>
50 # <a href="{{prefix}}/add_structured">add structured</a>
51 # <a href="{{prefix}}/edit">add</a>
55 # <p id="{{nth}}"><a href="{{prefix}}#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
56 # <span class="meta">[edit: <a href="{{prefix}}/add_structured?start={{start}}&end={{end}}">structured</a>
57 # / <a href="{{prefix}}/add_free?start={{start}}&end={{end}}">free</a>
58 # | copy:<a href="{{prefix}}/copy_structured?start={{start}}&end={{end}}">structured</a>
59 # / <a href="{{prefix}}/copy_free?start={{start}}&end={{end}}">free</a>
60 # | move {% if move_up %}<a href="{{prefix}}/move_up?start={{start}}&end={{end}}">up</a>{% else %}up{% endif %}/{% if move_down %}<a href="{{prefix}}/move_down?start={{start}}&end={{end}}">down</a>{% else %}down{% endif %}
61 # | <a href="{{prefix}}/balance?stop={{nth+1}}">balance after</a>
64 # {% for l in booking_lines %}
66 # <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
68 # <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
73 # add_form_header = """<form method="POST" action="{{action|e}}">
74 # <input type="submit" name="check" value="check" tabindex="5" />
75 # <input type="submit" name="revert" value="revert" tabindex="5" />
77 # add_form_footer = """
78 # <input type="hidden" name="start" value={{start}} />
79 # <input type="hidden" name="end" value={{end}} />
80 # <input type="submit" name="save" value="save!" tabindex="5" >
83 # add_free_html = """<br />
84 # <textarea name="booking" rows=10 cols=80>{% for line in lines %}{{ line }}{% if not loop.last %}
85 # {% endif %}{% endfor %}</textarea>
87 # add_structured_html = """
88 # <input type="submit" name="add_taxes" value="add taxes" tabindex="5" />
89 # <input type="submit" name="add_taxes2" value="add taxes2" tabindex="5" />
90 # <input type="submit" name="add_sink" value="add sink" tabindex="5" />
91 # <input name="replace_from" tabindex="5" />
92 # <input type="submit" name="replace" value="-> replace ->" tabindex="5" />
93 # <input name="replace_to" tabindex="5" />
94 # <input type="submit" name="add_mirror" value="add mirror" tabindex="5" />
96 # <input name="date" value="{{date|e}}" size=9 tabindex="3" />
97 # <input name="description" value="{{desc|e}}" list="descriptions" tabindex="3" />
98 # <textarea name="line_0_comment" rows=1 cols=20 tabindex="3" >{{head_comment|e}}</textarea>
99 # <input type="submit" name="line_0_add" value="[+]" tabindex="5" />
101 # {% for line in booking_lines %}
102 # <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" tabindex="3" />
103 # <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 tabindex="3" />
104 # <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" tabindex="5" />
105 # <input type="submit" name="line_{{line.i}}_delete" value="[x]" tabindex="5" />
106 # <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" tabindex="5" />
107 # <input type="submit" name="line_{{line.i}}_add" value="[+]" tabindex="5" />
108 # <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %} tabindex="3">{{line.comment|e}}</textarea>
111 # {% for name, items in datalist_sets.items() %}
112 # <datalist id="{{name}}">
113 # {% for item in items %}
114 # <option value="{{item|e}}">{{item|e}}</option>
126 def __iadd__(self, moneys):
128 if type(moneys) == Wealth:
129 moneys = moneys.money_dict
130 for currency, amount in moneys.items():
131 if not currency in self.money_dict.keys():
132 self.money_dict[currency] = 0
133 self.money_dict[currency] += amount
137 def sink_empty(self):
138 return len(self.as_sink) == 0
143 for currency, amount in self.money_dict.items():
146 sink[currency] = -amount
152 def __init__(self, own_name, parent):
153 self.own_name = own_name
156 self.parent.children += [self]
157 self.own_moneys = Wealth()
160 def add_wealth(self, moneys):
161 self.own_moneys += moneys
165 if self.parent and len(self.parent.own_name) > 0:
166 return f'{self.parent.full_name}:{self.own_name}'
171 def full_moneys(self):
172 full_moneys = Wealth()
173 full_moneys += self.own_moneys
174 for child in self.children:
175 full_moneys += child.full_moneys
179 # def apply_booking_to_account_balances(account_sums, account, currency, amount):
180 # if not account in account_sums:
181 # account_sums[account] = {currency: amount}
182 # elif not currency in account_sums[account].keys():
183 # account_sums[account][currency] = amount
185 # account_sums[account][currency] += amount
188 # def bookings_to_account_tree(bookings):
190 # for booking in bookings:
191 # for account, changes in booking.account_changes.items():
192 # for currency, amount in changes.items():
193 # apply_booking_to_account_balances(account_sums, account, currency, amount)
195 # def collect_branches(account_name, path):
196 # node = account_tree
197 # path_copy = path[:]
198 # while len(path_copy) > 0:
199 # step = path_copy.pop(0)
201 # toks = account_name.split(":", maxsplit=1)
203 # if parent in node.keys():
204 # child = node[parent]
207 # node[parent] = child
209 # k, v = collect_branches(toks[1], path + [parent])
210 # if k not in child.keys():
214 # return parent, child
215 # for account_name in sorted(account_sums.keys()):
216 # k, v = collect_branches(account_name, [])
217 # if k not in account_tree.keys():
218 # account_tree[k] = v
220 # account_tree[k].update(v)
221 # def collect_totals(parent_path, tree_node):
222 # for k, v in tree_node.items():
223 # child_path = parent_path + ":" + k
224 # for currency, amount in collect_totals(child_path, v).items():
225 # apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
226 # return account_sums[parent_path]
227 # for account_name in account_tree.keys():
228 # account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
229 # return account_tree, account_sums
232 def parse_lines_to_bookings(lines, ignore_editable_exceptions=False):
233 lines = [LedgerTextLine(line) for line in lines]
234 lines += [LedgerTextLine('')] # to simulate ending of last booking
236 inside_booking = False
240 for i, line in enumerate(lines):
241 intro = f'file line {i}'
244 booking = Booking(lines=booking_lines, starts_at=booking_start_i)
245 if last_date > booking.date and not ignore_editable_exceptions:
246 raise EditableException(len(bookings), f'{intro}: out-of-order date (follows {last_date})')
247 last_date = booking.date
248 bookings += [booking]
249 inside_booking =False
252 if not inside_booking:
254 inside_booking = True
255 booking_lines += [line]
257 raise PlomException(f'{intro}: last booking unfinished')
261 # def parse_lines(lines, validate_bookings=True):
262 # inside_booking = False
263 # date_string, description = None, None
268 # lines = lines.copy() + [''] # to ensure a booking-ending last line
270 # for i, line in enumerate(lines):
271 # prefix = f"line {i}"
272 # # we start with the case of an utterly empty line
274 # stripped_line = line.rstrip()
275 # if stripped_line == '':
277 # # assume we finished a booking, finalize, and commit to DB
278 # if len(booking_lines) < 2:
279 # raise PlomException(f"{prefix} booking ends to early")
280 # booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
281 # bookings += [booking]
282 # # expect new booking to follow so re-zeroall booking data
283 # inside_booking = False
284 # date_string, description = None, None
287 # # if non-empty line, first get comment if any, and commit to DB
288 # split_by_comment = stripped_line.split(sep=";", maxsplit=1)
289 # if len(split_by_comment) == 2:
290 # comments[i] = split_by_comment[1].lstrip()
291 # # 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
292 # non_comment = split_by_comment[0].rstrip()
293 # if non_comment.rstrip() == '':
295 # booking_lines += ['']
297 # # if we're starting a booking, parse by first-line pattern
298 # if not inside_booking:
300 # toks = non_comment.split(maxsplit=1)
301 # date_string = toks[0]
303 # datetime.strptime(date_string, '%Y-%m-%d')
305 # raise PlomException(f"{prefix} bad date string: {date_string}")
306 # # if last_date > date_string:
307 # # raise PlomException(f"{prefix} out-of-order-date")
308 # last_date = date_string
310 # description = toks[1]
312 # raise PlomException(f"{prefix} bad description: {description}")
313 # inside_booking = True
314 # booking_lines += [non_comment]
316 # # otherwise, read as transfer data
317 # toks = non_comment.split() # ignore specification's allowance of single spaces in names
319 # raise PlomException(f"{prefix} too many booking line tokens: {toks}")
320 # amount, currency = None, None
321 # account_name = toks[0]
322 # if account_name[0] == '[' and account_name[-1] == ']':
323 # # ignore specification's differentiation of "virtual" accounts
324 # account_name = account_name[1:-1]
325 # decimal_chars = ".-0123456789"
329 # amount = decimal.Decimal(toks[1])
331 # except decimal.InvalidOperation:
333 # amount = decimal.Decimal(toks[2])
334 # except decimal.InvalidOperation:
335 # raise PlomException(f"{prefix} no decimal number in: {toks[1:]}")
336 # currency = toks[i_currency]
337 # if currency[0] in decimal_chars:
338 # raise PlomException(f"{prefix} currency starts with int, dot, or minus: {currency}")
339 # elif len(toks) == 2:
341 # inside_amount = False
342 # inside_currency = False
346 # for i, c in enumerate(value):
348 # if c in decimal_chars:
349 # inside_amount = True
351 # inside_currency = True
352 # if inside_currency:
353 # if c in decimal_chars and len(amount_string) == 0:
354 # inside_currency = False
355 # inside_amount = True
360 # if c not in decimal_chars:
361 # if len(currency) > 0:
362 # raise PlomException(f"{prefix} amount has non-decimal chars: {value}")
363 # inside_currency = True
364 # inside_amount = False
367 # if c == '-' and len(amount_string) > 1:
368 # raise PlomException(f"{prefix} amount has non-start '-': {value}")
370 # if dots_counted > 1:
371 # raise PlomException(f"{prefix} amount has multiple dots: {value}")
374 # if len(currency) == 0:
375 # raise PlomException(f"{prefix} currency missing: {value}")
376 # if len(amount_string) > 0:
377 # amount = decimal.Decimal(amount_string)
378 # booking_lines += [(account_name, amount, currency)]
380 # raise PlomException(f"{prefix} last booking unfinished")
381 # return bookings, comments
386 def __init__(self, line=None, account='', amount=None, currency='', comment='', validate=True):
387 self.account = account
389 self.currency = currency
390 self.comment = comment
393 raise PlomException('line empty')
394 self.comment = line.comment
395 toks = line.non_comment.split()
396 if (len(toks) not in {1, 3}):
398 raise PlomException(f'number of non-comment tokens not 1 or 3')
403 self.account = toks[0]
406 self.amount = decimal.Decimal(toks[1])
407 except decimal.InvalidOperation:
409 raise PlomException(f'invalid token for Decimal: {toks[1]}')
411 self.comment = f'unparsed: {toks[1]}; {self.comment}'
412 self.currency = toks[2]
415 def amount_fmt(self):
416 if self.amount is None:
418 elif self.amount.as_tuple().exponent < -2:
419 return f'{self.amount:.1f}…'
421 return f'{self.amount:.2f}'
424 def for_writing(self):
425 line = f' {self.account}'
426 if self.amount is not None:
427 line += f' {self.amount} {self.currency}'
428 if self.comment != '':
429 line += f' ; {self.comment}'
433 def comment_cols(self):
434 return max(20, len(self.comment))
439 def __init__(self, lines=None, starts_at='?', date='', description='', top_comment='', transfer_lines=None, validate=True):
440 self.validate = validate
441 self.starts_at = starts_at
442 self.intro = f'booking starting at line {self.starts_at}'
449 self.description = description
450 self.top_comment = top_comment
452 self.transfer_lines = transfer_lines if transfer_lines else []
453 if self.validate and len(self.transfer_lines) < 2:
454 raise PlomException(f'{self.intro}: too few transfer lines')
455 self.calculate_account_changes()
456 self.lines = [LedgerTextLine(l) for l in self.for_writing]
459 def from_postvars(cls, postvars, starts_at='?', validate=True):
460 date = postvars['date'][0]
461 description = postvars['description'][0]
462 top_comment = postvars['top_comment'][0]
464 for i, account in enumerate(postvars['account']):
465 if len(account) == 0:
468 if len(postvars['amount'][i]) > 0:
469 amount = decimal.Decimal(postvars['amount'][i])
470 transfer_lines += [TransferLine(None, account, amount, postvars['currency'][i], postvars['comment'][i])]
471 return cls(None, starts_at, date, description, top_comment, transfer_lines, validate=validate)
474 self.transfer_lines = []
475 self.account_changes = {}
477 def parse_lines(self):
478 if len(self.lines) < 3 and self.validate:
479 raise PlomException(f'{self.intro}: ends with less than 3 lines:' + str(self.lines))
480 top_line = self.lines[0]
481 if top_line.empty and self.validate:
482 raise PlomException('{self.intro}: headline empty')
483 self.top_comment = top_line.comment
484 toks = top_line.non_comment.split(maxsplit=1)
487 raise PlomException(f'{self.intro}: headline missing elements: {non_comment}')
493 self.description = toks[1]
495 for i, line in enumerate(self.lines[1:]):
497 self.transfer_lines += [TransferLine(line, validate=self.validate)]
498 except PlomException as e:
499 raise PlomException(f'{self.intro}, transfer line {i}: {e}')
500 self.calculate_account_changes()
502 def calculate_account_changes(self):
504 money_changes = Wealth()
505 for i, transfer_line in enumerate(self.transfer_lines):
506 intro = f'{self.intro}, transfer line {i}'
507 if transfer_line.amount is None:
508 if sink_account is not None and self.validate:
509 raise PlomException(f'{intro}: second sink found (only one allowed)')
510 sink_account = transfer_line.account
512 if not transfer_line.account in self.account_changes.keys():
513 self.account_changes[transfer_line.account] = Wealth()
514 money = {transfer_line.currency: transfer_line.amount}
515 self.account_changes[transfer_line.account] += money
516 money_changes += money
517 if sink_account is None and (not money_changes.sink_empty) and self.validate:
518 raise PlomException(f'{intro}: does not balance (undeclared non-empty sink)')
519 if sink_account is not None:
520 if not sink_account in self.account_changes.keys():
521 self.account_changes[sink_account] = Wealth()
522 self.account_changes[sink_account] += money_changes.as_sink
525 def for_writing(self):
526 lines = [f'{self.date} {self.description}']
527 if self.top_comment is not None and self.top_comment.rstrip() != '':
528 lines[0] += f' ; {self.top_comment}'
529 for line in self.transfer_lines:
530 lines += [line.for_writing]
534 def comment_cols(self):
535 return max(20, len(self.top_comment))
537 def validate_head(self):
538 if not self.validate:
540 if len(self.date) == 0:
541 raise PlomException(f'{self.intro}: missing date')
542 if len(self.description) == 0:
543 raise PlomException(f'{self.intro}: missing description')
545 datetime.strptime(self.date, '%Y-%m-%d')
547 raise PlomException(f'{self.intro}: bad headline date format: {self.date}')
550 replacement_lines = []
551 for i, line in enumerate(self.transfer_lines):
552 if line.amount is None:
553 for currency, amount in self.account_changes[line.account].money_dict.items():
554 replacement_lines += [TransferLine(None, f'{line.account}', amount, currency).for_writing]
556 lines = self.lines[:i+1] + [LedgerTextLine(l) for l in replacement_lines] + self.lines[i+2:]
562 new_transfer_lines = []
563 for transfer_line in self.transfer_lines:
564 uncommented_source = LedgerTextLine(transfer_line.for_writing).non_comment
565 comment = f're: {uncommented_source.lstrip()}'
567 new_transfer_lines += [TransferLine(None, new_account, -transfer_line.amount, transfer_line.currency, comment)]
568 for transfer_line in new_transfer_lines:
569 self.lines += [LedgerTextLine(transfer_line.for_writing)]
573 def replace(self, replace_from, replace_to):
575 for l in self.for_writing:
576 lines += [l.replace(replace_from, replace_to)]
577 self.lines = [LedgerTextLine(l) for l in lines]
582 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
583 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
584 acc_kk = 'Expenses:KrankenKasse'
585 acc_est = 'Reserves:EinkommensSteuer'
586 acc_assets = 'Assets'
587 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
588 buffer_expenses = 0 # FIXME: hardcoded for now
589 kk_expenses = 0 # FIXME: hardcoded for now
590 est_expenses = 0 # FIXME: hardcoded for now
591 months_passed = 0 # FIXME: hardcoded for now
592 last_monthbreak_assets = 0 # FIXME: hardcoded for now
593 last_monthbreak_est = 0 # FIXME: hardcoded for now
594 last_monthbreak_kk_minimum = 0 # FIXME: hardcoded for now
595 last_monthbreak_kk_add = 0 # FIXME: hardcoded for now
596 expenses_so_far = 0 # FIXME: hardcoded for now
597 needed_netto = self.account_changes['Assets'].money_dict['€']
599 left_over = needed_netto - ESt_this_month
601 too_high = 2 * needed_netto
602 E0 = decimal.Decimal(10908)
603 E1 = decimal.Decimal(15999)
604 E2 = decimal.Decimal(62809)
605 E3 = decimal.Decimal(277825)
607 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_netto
609 # zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
611 ESt = decimal.Decimal(0)
614 ESt = (decimal.Decimal(979.18) * y + 1400) * y
617 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
619 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
621 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
622 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
623 left_over = needed_netto - ESt_this_month
624 if abs(left_over - expenses_so_far) < 0.001:
626 elif left_over < expenses_so_far:
627 too_low = needed_netto
628 elif left_over > expenses_so_far:
629 too_high = needed_netto
630 needed_netto = too_low + (too_high - too_low)/2
631 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
632 self.transfer_lines += [TransferLine(None, acc_est, ESt_this_month, '€')]
633 kk_minimum_income = 1131.67
634 kk_factor = decimal.Decimal(0.197)
635 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
636 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
637 kk_add = needed_netto / (1 - kk_factor) - needed_netto - kk_minimum_tax
638 hit_kk_minimum_income_limit = False
639 if kk_add_so_far + kk_add < 0:
640 hit_kk_minimum_income_limit = True
641 kk_add_uncorrect = kk_add
642 kk_add = -(kk_add + kk_add_so_far)
643 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
644 self.transfer_lines += [TransferLine(None, acc_kk_minimum, kk_minimum_tx, '€')]
645 self.transfer_lines += [TransferLine(None, acc_kk_add, kk_add, '€')]
646 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
648 diff += kk_minimum_tax
649 final_minus = expenses_so_far - old_needed_income_before_anything + diff
650 diff += kk_minimum_tax
651 final_minus = expenses_so_far - old_needed_income_before_anything + diff
652 self.transfer_lines += [TransferLine(None, acc_assets, -diff, '€')]
653 self.transfer_lines += [TransferLine(None, acc_assets, final_minus, '€')]
654 self.transfer_lines += [TransferLine(None, acc_buffer, -final_minus, '€')]
659 # def __init__(self, date_string, description, booking_lines, start_line, process=True):
660 # self.date_string = date_string
661 # self.description = description
662 # self.lines = booking_lines
663 # self.start_line = start_line
665 # self.validate_booking_lines()
667 # self.account_changes = self.parse_booking_lines_to_account_changes()
669 # def validate_booking_lines(self):
670 # prefix = f"booking at line {self.start_line}"
673 # for line in self.lines[1:]:
676 # _, amount, currency = line
678 # if empty_values > 0:
679 # raise PlomException(f"{prefix} relates more than one empty value of same currency {currency}")
682 # if currency not in sums:
684 # sums[currency] += amount
685 # if empty_values == 0:
686 # for k, v in sums.items():
688 # raise PlomException(f"{prefix} does not add up to zero / {k} {v}")
691 # for k, v in sums.items():
695 # raise PlomException(f"{prefix} has empty value that cannot be filled")
697 # def parse_booking_lines_to_account_changes(self):
698 # account_changes = {}
700 # sink_account = None
701 # for line in self.lines[1:]:
704 # account, amount, currency = line
706 # sink_account = account
708 # apply_booking_to_account_balances(account_changes, account, currency, amount)
709 # if currency not in debt:
710 # debt[currency] = amount
712 # debt[currency] += amount
714 # for currency, amount in debt.items():
715 # apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
716 # self.sink[currency] = -amount
717 # return account_changes
721 class LedgerDB(PlomDB):
723 def __init__(self, prefix, ignore_editable_exceptions=False):
728 super().__init__(db_path)
729 self.bookings = parse_lines_to_bookings(self.text_lines, ignore_editable_exceptions)
731 def read_db_file(self, f):
732 self.text_lines += f.readlines()
733 # self.text_lines += [l.rstrip() for l in f.readlines()] # TODO is this necessary? (parser already removes lines?)
735 # def get_lines(self, start, end):
736 # return self.text_lines[start:end]
738 # def write_db(self, text, mode='w'):
739 # if text[-1] != '\n':
741 # self.write_text_to_db(text)
743 # def insert_at_date(self, lines, date):
745 # if len(self.bookings) > 0:
746 # if date >= self.bookings[-1].date_string:
747 # start_at = len(self.text_lines)
748 # lines = [''] + lines
750 # for b in self.bookings:
751 # if b.date_string == date:
752 # start_at = b.start_line
753 # elif b.date_string > date:
754 # start_at = b.start_line
756 # lines += [''] # DEBUG is new
757 # return self.write_lines_in_total_lines_at(self.text_lines, start_at, lines)
759 # def update(self, start, end, lines, date):
760 # remaining_lines = self.text_lines[:start] + self.text_lines[end:]
761 # n_original_lines = end - start
762 # start_at = len(remaining_lines)
763 # for b in self.bookings:
764 # if b.date_string == date:
765 # if start_at == len(remaining_lines) or b.start_line == start:
766 # start_at = b.start_line
767 # if b.start_line > start:
768 # start_at -= n_original_lines
769 # elif b.date_string > date:
771 # # print("DEBUG update start_at", start_at, "len(remaining_lines)", len(remaining_lines), "len(self.text_lines)", len(self.text_lines), "end", end)
772 # if start_at != 0 and end != len(self.text_lines) and start_at == len(remaining_lines):
773 # # Add empty predecessor line if appending.
774 # lines = [''] + lines
775 # return self.write_lines_in_total_lines_at(remaining_lines, start_at, lines)
777 # def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
778 # # total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
779 # total_lines = total_lines[:start_at] + lines + total_lines[start_at:]
780 # _, _ = parse_lines(lines)
781 # text = '\n'.join(total_lines)
782 # self.write_db(text)
785 # def get_nth_for_booking_of_start_line(self, start_line):
787 # for b in self.bookings:
788 # if b.start_line >= start_line:
793 def insert_booking_at_date(self, booking):
795 if len(self.bookings) > 0:
796 for i, iterated_booking in enumerate(self.bookings):
797 if booking.date < iterated_booking.date:
799 elif booking.date == iterated_booking.date:
804 self.bookings.insert(place_at, booking)
806 def add_taxes(self, lines, finish=False):
808 bookings, _ = parse_lines(lines)
809 date = bookings[0].date_string
810 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
811 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
812 acc_kk = 'Expenses:KrankenKasse'
813 acc_est = 'Reserves:Einkommenssteuer'
814 acc_assets = 'Assets'
815 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
816 last_monthbreak_assets = 0
817 last_monthbreak_est = 0
818 last_monthbreak_kk_minimum = 0
819 last_monthbreak_kk_add = 0
823 months_passed = -int(finish)
824 for b in self.bookings:
825 if date == b.date_string:
827 acc_keys = b.account_changes.keys()
828 if acc_buffer in acc_keys:
829 buffer_expenses -= b.account_changes[acc_buffer]['€']
830 if acc_kk_add in acc_keys:
831 kk_expenses += b.account_changes[acc_kk_add]['€']
832 if acc_kk in acc_keys:
833 kk_expenses += b.account_changes[acc_kk]['€']
834 if acc_est in acc_keys:
835 est_expenses += b.account_changes[acc_est]['€']
836 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
839 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
840 last_monthbreak_est = b.account_changes[acc_est]['€']
841 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
842 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
843 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
845 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
846 _, account_sums = bookings_to_account_tree(bookings)
847 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
848 needed_income_before_kk = expenses_so_far
850 left_over = needed_income_before_kk - ESt_this_month
852 too_high = 2 * needed_income_before_kk
853 E0 = decimal.Decimal(10908)
854 E1 = decimal.Decimal(15999)
855 E2 = decimal.Decimal(62809)
856 E3 = decimal.Decimal(277825)
858 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
860 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
862 ESt = decimal.Decimal(0)
865 ESt = (decimal.Decimal(979.18) * y + 1400) * y
868 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
870 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
872 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
873 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
874 left_over = needed_income_before_kk - ESt_this_month
875 if abs(left_over - expenses_so_far) < 0.001:
877 elif left_over < expenses_so_far:
878 too_low = needed_income_before_kk
879 elif left_over > expenses_so_far:
880 too_high = needed_income_before_kk
881 needed_income_before_kk = too_low + (too_high - too_low)/2
882 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
883 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}€']
884 kk_minimum_income = 1131.67
885 if date < '2023-02-01':
886 kk_minimum_income = decimal.Decimal(1096.67)
887 kk_factor = decimal.Decimal(0.189)
888 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
889 elif date < '2023-08-01':
890 kk_factor = decimal.Decimal(0.191)
891 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
893 kk_factor = decimal.Decimal(0.197)
894 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
895 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
896 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
897 hit_kk_minimum_income_limit = False
898 if kk_add_so_far + kk_add < 0:
899 hit_kk_minimum_income_limit = True
900 kk_add_uncorrect = kk_add
901 kk_add = -(kk_add + kk_add_so_far)
902 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
904 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
906 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
907 if hit_kk_minimum_income_limit:
908 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']
910 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
911 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
913 diff += kk_minimum_tax
914 final_minus = expenses_so_far - old_needed_income_before_anything + diff
915 ret += [f' {acc_assets} {-diff} €']
916 ret += [f' {acc_assets} {final_minus} €']
917 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
919 ret += [f' {acc_buffer} {-final_minus} €']
921 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
924 # def add_mirror(self, lines):
926 # bookings, _ = parse_lines(lines)
927 # booking = bookings[0]
928 # for line in booking.lines[1:]:
929 # ret += [f'? {-line[1]} {line[2]}']
932 def ledger_as_html(self):
933 for index, booking in enumerate(self.bookings):
934 booking.can_up = index > 0 and self.bookings[index - 1].date == booking.date
935 booking.can_down = index < len(self.bookings) - 1 and self.bookings[index + 1].date == booking.date
936 return j2env.get_template('ledger.html').render(bookings=self.bookings)
938 # def ledger_as_html(self):
939 # booking_tmpl = jinja2.Template(booking_html)
940 # single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
941 # elements_to_write = []
943 # for nth, booking in enumerate(self.bookings):
944 # move_up = nth > 0 and self.bookings[nth - 1].date_string == booking.date_string
945 # move_down = nth < len(self.bookings) - 1 and self.bookings[nth + 1].date_string == booking.date_string
946 # booking_end = last_i = booking.start_line + len(booking.lines)
948 # i = booking.start_line ##
949 # elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:i] if c != ''] ##
950 # for booking_line in booking.lines[1:]:
952 # comment = self.comments[i] ##
953 # if booking_line == '':
954 # booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
956 # account = booking_line[0]
958 # if booking_line[1] is not None:
959 # money = f'{booking_line[1]} {booking_line[2]}'
960 # booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
961 # elements_to_write += [booking_tmpl.render(
962 # prefix=self.prefix,
964 # start=booking.start_line,
966 # date=booking.date_string,
967 # desc=booking.description,
968 # head_comment=self.comments[booking.start_line],
970 # move_down=move_down,
971 # booking_lines = booking_lines)]
972 # elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:] if c != ''] #
973 # return '\n'.join(elements_to_write)
975 def balance_as_html(self, until_after=None):
976 bookings = self.bookings[:(until_after if until_after is None else int(until_after)+1)]
977 account_trunk = Account('', None)
978 accounts = {account_trunk.full_name: account_trunk}
979 for booking in bookings:
980 for full_account_name, moneys in booking.account_changes.items():
981 toks = full_account_name.split(':')
984 parent_name = ':'.join(path)
986 account_name = ':'.join(path)
987 if not account_name in accounts.keys():
988 accounts[account_name] = Account(own_name=tok, parent=accounts[parent_name])
989 accounts[full_account_name].add_wealth(moneys)
991 def __init__(self, indent, name, moneys):
994 self.moneys = moneys.money_dict
996 def walk_tree(nodes, indent, account):
997 nodes += [Node(indent, account.own_name, account.full_moneys)]
998 for child in account.children:
999 walk_tree(nodes, indent+1, child)
1000 for acc in account_trunk.children:
1001 walk_tree(nodes, 0, acc)
1002 return j2env.get_template('balance.html').render(nodes=nodes)
1004 # def balance_as_html(self, until=None):
1005 # bookings = self.bookings[:until if until is None else int(until)]
1007 # account_tree, account_sums = bookings_to_account_tree(bookings)
1008 # def print_subtree(lines, indent, node, subtree, path):
1009 # line = f"{indent}{node}"
1010 # n_tabs = 5 - (len(line) // 8)
1011 # line += n_tabs * "\t"
1012 # if "€" in account_sums[path + node].keys():
1013 # amount = account_sums[path + node]["€"]
1014 # line += f"{amount:9.2f} €\t"
1017 # for currency, amount in account_sums[path + node].items():
1018 # if currency != '€' and amount != 0:
1019 # line += f"{amount:5.2f} {currency}\t"
1022 # for k, v in sorted(subtree.items()):
1023 # print_subtree(lines, indent, k, v, path + node + ":")
1024 # for k, v in sorted(account_tree.items()):
1025 # print_subtree(lines, "", k, v, "")
1026 # content = "\n".join(lines)
1027 # return f"<pre>{content}</pre>"
1029 def edit(self, index, sent=None, error_msg=None, edit_mode='table', copy=False):
1031 if sent or -1 == index:
1032 content = sent if sent else ([] if 'textarea'==edit_mode else None)
1034 content = self.bookings[index]
1035 date_today = str(datetime.now())[:10]
1037 content.date = date_today
1038 elif -1 == index and (content is None or [] == content):
1039 content = Booking(date=date_today, validate=False)
1040 if 'textarea' == edit_mode and content:
1041 content = content.for_writing
1043 for booking in self.bookings:
1044 for transfer_line in booking.transfer_lines:
1045 accounts.add(transfer_line.account)
1046 return j2env.get_template('edit.html').render(content=content, index=index, error_msg=error_msg, edit_mode=edit_mode, accounts=accounts, adding=(copy or -1 == index))
1048 # def add_free(self, start=0, end=0, copy=False):
1049 # tmpl = jinja2.Template(add_form_header + add_free_html + add_form_footer)
1050 # lines = self.get_lines(start, end)
1053 # return tmpl.render(action=self.prefix + '/add_free', start=start, end=end, lines=lines)
1055 # def add_structured(self, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
1056 # tmpl = jinja2.Template(add_form_header + add_structured_html + add_form_footer)
1057 # lines = temp_lines if len(''.join(temp_lines)) > 0 else self.get_lines(start, end)
1058 # bookings, comments = parse_lines(lines, validate_bookings=False)
1059 # if len(bookings) > 1:
1060 # raise PlomException('can only structurally edit single Booking')
1061 # if add_empty_line is not None:
1062 # comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
1063 # booking = bookings[0]
1064 # booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
1065 # action = self.prefix + '/add_structured'
1066 # datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
1067 # for b in self.bookings:
1068 # datalist_sets['descriptions'].add(b.description)
1069 # for account, moneys in b.account_changes.items():
1070 # datalist_sets['accounts'].add(account)
1071 # for currency in moneys.keys():
1072 # datalist_sets['currencies'].add(currency)
1074 # today = str(datetime.now())[:10]
1075 # booking_lines = []
1078 # desc = head_comment = ''
1079 # if len(bookings) == 0:
1082 # booking = bookings[0]
1083 # desc = booking.description
1084 # date = today if copy else booking.date_string
1085 # head_comment=comments[0]
1086 # for i in range(1, len(comments)):
1087 # account = amount = currency = ''
1088 # if i < len(booking.lines) and booking.lines[i] != '':
1089 # account = booking.lines[i][0]
1090 # amount = booking.lines[i][1]
1091 # currency = booking.lines[i][2]
1092 # booking_lines += [{
1096 # 'curr': currency if currency else '€',
1097 # 'comment': comments[i],
1098 # 'comm_cols': len(comments[i])}]
1099 # for i in range(len(comments), len(comments) + 8):
1100 # booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
1101 # content += tmpl.render(
1105 # head_comment=head_comment,
1106 # booking_lines=booking_lines,
1107 # datalist_sets=datalist_sets,
1112 def move_up(self, index):
1113 return self.move(index, -1)
1115 def move_down(self, index):
1116 return self.move(index, +1)
1118 def move(self, index, direction):
1119 to_move = self.bookings[index]
1120 swap_index = index + 1*(direction)
1121 to_swap = self.bookings[swap_index]
1122 self.bookings[index] = to_swap
1123 self.bookings[index + 1*(direction)] = to_move
1128 for i, booking in enumerate(self.bookings):
1131 lines += booking.for_writing
1132 self.write_text_to_db('\n'.join(lines) + '\n')
1134 # def move_up(self, start, end):
1135 # prev_booking = None
1136 # for redir_nth, b in enumerate(self.bookings):
1137 # if b.start_line >= start:
1140 # start_at = prev_booking.start_line
1141 # self.make_move(start, end, start_at)
1142 # return redir_nth - 1
1144 # def move_down(self, start, end):
1145 # next_booking = None
1146 # for redir_nth, b in enumerate(self.bookings):
1147 # if b.start_line > start:
1150 # # start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1
1151 # # self.make_move(start, end, start_at-1)
1152 # start_at = next_booking.start_line + len(next_booking.lines) - (end - start)
1153 # self.make_move(start, end, start_at)
1156 # def make_move(self, start, end, start_at):
1157 # # FIXME currently broken due to changed self.write_lines_in_total_lines_at, easy fix would be lines += [""] maybe?
1158 # lines = self.get_lines(start, end)
1160 # total_lines = self.text_lines[end+1:]
1161 # lines = [''] + lines
1164 # total_lines = self.text_lines[:start-1] + self.text_lines[end:] # -1 because we reduce the original position's two empty limit lines to one in-between line
1166 # self.write_lines_in_total_lines_at(total_lines, start_at, lines)
1168 # def booking_lines_from_postvars(self, postvars):
1169 # add_empty_line = None
1170 # date = postvars['date'][0]
1171 # description = postvars['description'][0]
1172 # start_comment = postvars['line_0_comment'][0]
1173 # start_line = f'{date} {description}'
1174 # if start_comment.rstrip() != '':
1175 # start_line += f' ; {start_comment}'
1176 # lines = [start_line]
1177 # if 'line_0_add' in postvars.keys():
1178 # add_empty_line = 0
1180 # while f'line_{i}_comment' in postvars.keys():
1181 # if f'line_{i}_delete' in postvars.keys():
1184 # elif f'line_{i}_delete_after' in postvars.keys():
1186 # elif f'line_{i}_add' in postvars.keys():
1187 # add_empty_line = j
1188 # account = postvars[f'line_{i}_account'][0]
1189 # amount = postvars[f'line_{i}_amount'][0]
1190 # currency = postvars[f'line_{i}_currency'][0]
1191 # comment = postvars[f'line_{i}_comment'][0]
1193 # new_main = f' {account} {amount}'
1194 # if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
1196 # if len(amount.rstrip()) > 0:
1197 # new_main += f' {currency}'
1199 # new_line = new_main
1200 # if comment.rstrip() != '':
1201 # new_line += f' ; {comment}'
1202 # lines += [new_line]
1203 # if 'add_sink' in postvars.keys():
1204 # temp_lines = lines.copy() + ['_']
1206 # temp_bookings, _ = parse_lines(temp_lines)
1207 # for currency in temp_bookings[0].sink:
1208 # amount = temp_bookings[0].sink[currency]
1209 # # lines += [f'Assets {amount:.2f} {currency}']
1210 # lines += [f'Assets {amount} {currency}']
1211 # except PlomException:
1213 # elif 'add_taxes' in postvars.keys():
1214 # lines += self.add_taxes(lines, finish=False)
1215 # elif 'add_taxes2' in postvars.keys():
1216 # lines += self.add_taxes(lines, finish=True)
1217 # elif 'replace' in postvars.keys():
1218 # for i, line in enumerate(lines):
1219 # lines[i] = line.replace(postvars['replace_from'][0], postvars['replace_to'][0])
1220 # elif 'add_mirror' in postvars.keys():
1221 # lines += self.add_mirror(lines)
1222 # return lines, add_empty_line
1226 class LedgerHandler(PlomHandler):
1228 def app_init(self, handler):
1229 default_path = '/ledger'
1230 handler.add_route('GET', default_path, self.forward_gets)
1231 handler.add_route('POST', default_path, self.forward_posts)
1232 return 'ledger', default_path
1235 self.try_do(self.forward_posts)
1237 def forward_posts(self):
1238 prefix = self.apps['ledger'] if hasattr(self, 'apps') else ''
1239 length = int(self.headers['content-length'])
1240 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
1241 db = LedgerDB(prefix, ignore_editable_exceptions=True)
1243 parsed_url = urlparse(self.path)
1244 for string in {'update', 'add', 'check', 'mirror', 'fill_sink', 'textarea', 'table', 'move_up', 'move_down', 'add_taxes', 'replace'}:
1245 if string in postvars.keys():
1246 submit_button = string
1248 if f'{prefix}/ledger' == parsed_url.path and submit_button in {'move_up', 'move_down'}:
1249 mover = getattr(db, submit_button)
1250 index = mover(int(postvars[submit_button][0]))
1251 elif prefix + '/edit' == parsed_url.path:
1252 index = int(postvars['index'][0])
1253 edit_mode = postvars['edit_mode'][0]
1254 validate = submit_button in {'update', 'add', 'copy', 'check'}
1255 starts_at = '?' if index == -1 else db.bookings[index].starts_at
1256 if 'textarea' == edit_mode:
1257 lines = [LedgerTextLine(line) for line in postvars['booking'][0].rstrip().split('\n')]
1258 booking = Booking(lines, starts_at, validate=validate)
1260 booking = Booking.from_postvars(postvars, starts_at, validate)
1261 if submit_button in {'update', 'add'}:
1262 if submit_button == 'update':
1263 if 'textarea' == edit_mode and 'delete' == ''.join([l.text_line for l in lines]).strip():
1264 del db.bookings[index]
1265 # if not creating new Booking, and date unchanged, keep it in place
1266 elif booking.date == db.bookings[index].date:
1267 db.bookings[index] = booking
1269 del db.bookings[index]
1270 db.insert_booking_at_date(booking)
1272 db.insert_booking_at_date(booking)
1273 else: # non-DB-writing calls
1275 if 'check' == submit_button:
1276 error_msg = 'All looks fine!'
1277 elif submit_button in {'mirror', 'fill_sink', 'add_taxes'}:
1278 getattr(booking, submit_button)()
1279 elif 'replace' == submit_button:
1280 booking.replace(postvars['replace_from'][0], postvars['replace_to'][0])
1281 elif submit_button in {'textarea', 'table'}:
1282 edit_mode = submit_button
1283 page = db.edit(index, booking, error_msg=error_msg, edit_mode=edit_mode)
1284 self.send_HTML(page)
1287 index = index if index >= 0 else len(db.bookings) - 1
1288 self.redirect(prefix + f'/ledger#{index}')
1290 # def forward_posts(self):
1291 # prefix = self.apps['ledger'] if hasattr(self, 'apps') else ''
1292 # parsed_url = urlparse(self.path)
1293 # length = int(self.headers['content-length'])
1294 # postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
1295 # start = int(postvars['start'][0])
1296 # end = int(postvars['end'][0])
1297 # print("DEBUG start, end", start, end)
1298 # db = LedgerDB(prefix)
1299 # add_empty_line = None
1302 # if prefix + '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
1303 # lines, add_empty_line = db.booking_lines_from_postvars(postvars)
1304 # elif prefix + '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
1305 # lines = postvars['booking'][0].splitlines()
1306 # # validate where appropriate
1307 # if ('save' in postvars.keys()) or ('check' in postvars.keys()):
1308 # _, _ = parse_lines(lines)
1309 # # if saving, process where to and where to redirect after
1310 # if 'save' in postvars.keys():
1311 # last_date = str(datetime.now())[:10]
1312 # if len(db.bookings) > 0:
1313 # last_date = db.bookings[-1].date_string
1314 # target_date = last_date[:]
1315 # first_line_tokens = lines[0].split() if len(lines) > 0 else ''
1316 # first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
1318 # datetime.strptime(first_token, '%Y-%m-%d')
1319 # target_date = first_token
1320 # except ValueError:
1322 # if start == end == 0:
1323 # start = db.insert_at_date(lines, target_date)
1324 # nth = db.get_nth_for_booking_of_start_line(start)
1326 # new_start = db.update(start, end, lines, target_date)
1327 # print("DEBUG save", new_start, start, end, lines)
1328 # nth = db.get_nth_for_booking_of_start_line(new_start)
1329 # if new_start > start:
1331 # self.redirect(prefix + f'/#{nth}')
1332 # # otherwise just re-build editing form
1334 # if prefix + '/add_structured' == parsed_url.path:
1335 # edit_content = db.add_structured(start, end, temp_lines=lines, add_empty_line=add_empty_line)
1337 # edit_content = db.add_free(start, end)
1338 # header = jinja2.Template(html_head).render(prefix=prefix)
1339 # self.send_HTML(header + edit_content)
1342 self.try_do(self.forward_gets)
1344 def forward_gets(self):
1345 prefix = self.apps['ledger'] if hasattr(self, 'apps') else ''
1347 db = LedgerDB(prefix=prefix)
1348 except EditableException as e:
1349 # We catch the EditableException for further editing, and then
1350 # re-run the DB initiation without it blocking DB creation.
1351 db = LedgerDB(prefix=prefix, ignore_editable_exceptions=True)
1352 page = db.edit(index=e.booking_index, error_msg=f'ERROR: {e}')
1353 self.send_HTML(page)
1355 parsed_url = urlparse(self.path)
1356 params = parse_qs(parsed_url.query)
1357 if parsed_url.path == f'{prefix}/balance':
1358 stop = params.get('until_after', [None])[0]
1359 page = db.balance_as_html(stop)
1360 elif parsed_url.path == f'{prefix}/edit':
1361 index = params.get('i', [-1])[0]
1362 copy = params.get('copy', [0])[0]
1363 page = db.edit(int(index), copy=bool(copy))
1365 page = db.ledger_as_html()
1366 self.send_HTML(page)
1370 if __name__ == "__main__":
1371 run_server(server_port, LedgerHandler)