home · contact · privacy
cd38b820da6354866cd23d64fb196a3ec9f40952
[misc] / ledger.py
1 import os
2 import jinja2
3 import decimal
4 from datetime import datetime, timedelta
5 from urllib.parse import parse_qs, urlparse
6 from plomlib import PlomDB, PlomException, run_server, PlomHandler 
7
8 server_port = 8082
9 db_path = '/home/plom/org/ledger2023.dat'
10
11 html_head = """
12 <style>
13 body { color: #000000; }
14 table { margin-bottom: 2em; }
15 th, td { text-align: left }
16 input[type=number] { text-align: right; font-family: monospace; }
17 .money { font-family: monospace; text-align: right; }
18 .comment { font-style: italic; color: #777777; }
19 .meta { font-size: 0.75em; color: #777777; }
20 .full_line_comment { display: block; white-space: nowrap; width: 0; }
21 </style>
22 <body>
23 <a href="{{prefix}}/ledger">ledger</a>
24 <a href="{{prefix}}/balance">balance</a>
25 <a href="{{prefix}}/add_free">add free</a>
26 <a href="{{prefix}}/add_structured">add structured</a>
27 <hr />
28 """
29 booking_html = """
30 <p id="{{nth}}"><a href="{{prefix}}#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
31 <span class="meta">[edit: <a href="{{prefix}}/add_structured?start={{start}}&end={{end}}">structured</a>
32 / <a href="{{prefix}}/add_free?start={{start}}&end={{end}}">free</a>
33 | copy:<a href="{{prefix}}/copy_structured?start={{start}}&end={{end}}">structured</a>
34 / <a href="{{prefix}}/copy_free?start={{start}}&end={{end}}">free</a>
35 | 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 %}
36 | <a href="{{prefix}}/balance?stop={{nth+1}}">balance after</a>
37 ]</span>
38 <table>
39 {% for l in booking_lines %}
40 {% if l.acc %}
41 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
42 {% else %}
43 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
44 {% endif %}
45 {% endfor %}
46 </table></p>
47 """
48 add_form_header = """<form method="POST" action="{{action|e}}">
49 <input type="submit" name="check" value="check" />
50 <input type="submit" name="revert" value="revert" />
51 """
52 add_form_footer = """
53 <input type="hidden" name="start" value={{start}} />
54 <input type="hidden" name="end" value={{end}} />
55 <input type="submit" name="save" value="save!">
56 </form>
57 """
58 add_free_html = """<br />
59 <textarea name="booking" rows=10 cols=80>
60 {% for line in lines %}{{ line }}
61 {% endfor %}
62 </textarea>
63 """
64 add_structured_html = """
65 <input type="submit" name="add_taxes" value="add taxes" />
66 <input type="submit" name="add_taxes2" value="add taxes2" />
67 <input type="submit" name="add_sink" value="add sink" />
68 <input name="replace_from" />
69 <input type="submit" name="replace" value="-> replace ->" />
70 <input name="replace_to" />
71 <br />
72 <input name="date" value="{{date|e}}" size=9 />
73 <input name="description" value="{{desc|e}}" list="descriptions" />
74 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
75 <input type="submit" name="line_0_add" value="[+]" />
76 <br />
77 {% for line in booking_lines %}
78 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
79 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
80 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
81 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
82 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
83 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
84 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
85 <br />
86 {% endfor %}
87 {% for name, items in datalist_sets.items() %}
88 <datalist id="{{name}}">
89 {% for item in items %}
90   <option value="{{item|e}}">{{item|e}}</option>
91 {% endfor %}
92 </datalist>
93 {% endfor %}
94 """
95
96
97 def apply_booking_to_account_balances(account_sums, account, currency, amount):
98     if not account in account_sums:
99         account_sums[account] = {currency: amount}
100     elif not currency in account_sums[account].keys():
101         account_sums[account][currency] = amount
102     else:
103         account_sums[account][currency] += amount
104
105
106 def bookings_to_account_tree(bookings):
107     account_sums = {}
108     for booking in bookings:
109         for account, changes in booking.account_changes.items():
110             for currency, amount in changes.items():
111                 apply_booking_to_account_balances(account_sums, account, currency, amount)
112     account_tree = {}
113     def collect_branches(account_name, path):
114         node = account_tree
115         path_copy = path[:]
116         while len(path_copy) > 0:
117             step = path_copy.pop(0)
118             node = node[step]
119         toks = account_name.split(":", maxsplit=1)
120         parent = toks[0]
121         if parent in node.keys():
122             child = node[parent]
123         else:
124             child = {}
125             node[parent] = child
126         if len(toks) == 2:
127             k, v = collect_branches(toks[1], path + [parent])
128             if k not in child.keys():
129                 child[k] = v
130             else:
131                 child[k].update(v)
132         return parent, child
133     for account_name in sorted(account_sums.keys()):
134         k, v = collect_branches(account_name, [])
135         if k not in account_tree.keys():
136             account_tree[k] = v
137         else:
138             account_tree[k].update(v)
139     def collect_totals(parent_path, tree_node):
140         for k, v in tree_node.items():
141             child_path = parent_path + ":" + k
142             for currency, amount in collect_totals(child_path, v).items():
143                 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
144         return account_sums[parent_path]
145     for account_name in account_tree.keys():
146         account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
147     return account_tree, account_sums
148
149
150 def parse_lines(lines, validate_bookings=True):
151     inside_booking = False
152     date_string, description = None, None
153     booking_lines = []
154     start_line = 0
155     bookings = []
156     comments = []
157     lines = lines.copy() + [''] # to ensure a booking-ending last line
158     last_date = ''
159     for i, line in enumerate(lines):
160         prefix = f"line {i}"
161         # we start with the case of an utterly empty line
162         comments += [""]
163         stripped_line = line.rstrip()
164         if stripped_line == '':
165             if inside_booking:
166                 # assume we finished a booking, finalize, and commit to DB
167                 if len(booking_lines) < 2:
168                     raise PlomException(f"{prefix} booking ends to early")
169                 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
170                 bookings += [booking]
171             # expect new booking to follow so re-zeroall booking data
172             inside_booking = False
173             date_string, description = None, None
174             booking_lines = []
175             continue
176         # if non-empty line, first get comment if any, and commit to DB
177         split_by_comment = stripped_line.split(sep=";", maxsplit=1)
178         if len(split_by_comment) == 2:
179             comments[i] = split_by_comment[1].lstrip()
180         # 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
181         non_comment = split_by_comment[0].rstrip()
182         if non_comment.rstrip() == '':
183              if inside_booking:
184                  booking_lines += ['']
185              continue
186         # if we're starting a booking, parse by first-line pattern
187         if not inside_booking:
188             start_line = i
189             toks = non_comment.split(maxsplit=1)
190             date_string = toks[0]
191             try:
192                 datetime.strptime(date_string, '%Y-%m-%d')
193             except ValueError:
194                 raise PlomException(f"{prefix} bad date string: {date_string}")
195             if last_date > date_string:
196                 raise PlomException(f"{prefix} out-of-order-date")
197             last_date = date_string
198             try:
199                 description = toks[1]
200             except IndexError:
201                 raise PlomException(f"{prefix} bad description: {description}")
202             inside_booking = True
203             booking_lines += [non_comment]
204             continue
205         # otherwise, read as transfer data
206         toks = non_comment.split()  # ignore specification's allowance of single spaces in names
207         if len(toks) > 3:
208             raise PlomException(f"{prefix} too many booking line tokens: {toks}")
209         amount, currency = None, None
210         account_name = toks[0]
211         if account_name[0] == '[' and account_name[-1] == ']':
212             # ignore specification's differentiation of "virtual" accounts
213             account_name = account_name[1:-1]
214         decimal_chars = ".-0123456789"
215         if len(toks) == 3:
216             i_currency = 1
217             try:
218                 amount = decimal.Decimal(toks[1])
219                 i_currency = 2
220             except decimal.InvalidOperation:
221                 try:
222                     amount = decimal.Decimal(toks[2])
223                 except decimal.InvalidOperation:
224                     raise PlomException(f"{prefix} no decimal number in: {toks[1:]}")
225             currency = toks[i_currency]
226             if currency[0] in decimal_chars:
227                 raise PlomException(f"{prefix} currency starts with int, dot, or minus: {currency}")
228         elif len(toks) == 2:
229             value = toks[1]
230             inside_amount = False
231             inside_currency = False
232             amount_string = ""
233             currency = ""
234             dots_counted = 0
235             for i, c in enumerate(value):
236                 if i == 0:
237                     if c in decimal_chars:
238                         inside_amount = True
239                     else:
240                         inside_currency = True
241                 if inside_currency:
242                     if c in decimal_chars and len(amount_string) == 0:
243                         inside_currency = False
244                         inside_amount = True
245                     else:
246                         currency += c
247                         continue
248                 if inside_amount:
249                     if c not in decimal_chars:
250                         if len(currency) > 0:
251                             raise PlomException(f"{prefix} amount has non-decimal chars: {value}")
252                         inside_currency = True
253                         inside_amount = False
254                         currency += c
255                         continue
256                     if c == '-' and len(amount_string) > 1:
257                         raise PlomException(f"{prefix} amount has non-start '-': {value}")
258                     if c == '.':
259                         if dots_counted > 1:
260                             raise PlomException(f"{prefix} amount has multiple dots: {value}")
261                         dots_counted += 1
262                     amount_string += c
263             if len(currency) == 0:
264                 raise PlomException(f"{prefix} currency missing: {value}")
265             if len(amount_string) > 0:
266                 amount = decimal.Decimal(amount_string)
267         booking_lines += [(account_name, amount, currency)]
268     if inside_booking:
269         raise PlomException(f"{prefix} last booking unfinished")
270     return bookings, comments
271
272
273 class Booking:
274
275     def __init__(self, date_string, description, booking_lines, start_line, process=True):
276         self.date_string = date_string
277         self.description = description
278         self.lines = booking_lines
279         self.start_line = start_line
280         if process:
281             self.validate_booking_lines()
282             self.sink = {}
283             self.account_changes = self.parse_booking_lines_to_account_changes()
284
285     def validate_booking_lines(self):
286         prefix = f"booking at line {self.start_line}"
287         sums = {}
288         empty_values = 0
289         for line in self.lines[1:]:
290             if line == '':
291                 continue
292             _, amount, currency = line
293             if amount is None:
294                 if empty_values > 0:
295                     raise PlomException(f"{prefix} relates more than one empty value of same currency {currency}")
296                 empty_values += 1
297                 continue
298             if currency not in sums:
299                 sums[currency] = 0
300             sums[currency] += amount
301         if empty_values == 0:
302             for k, v in sums.items():
303                 if v != 0:
304                     raise PlomException(f"{prefix} does not add up to zero / {k} {v}")
305         else:
306             sinkable = False
307             for k, v in sums.items():
308                 if v != 0:
309                     sinkable = True
310             if not sinkable:
311                 raise PlomException(f"{prefix} has empty value that cannot be filled")
312
313     def parse_booking_lines_to_account_changes(self):
314         account_changes = {}
315         debt = {}
316         sink_account = None
317         for line in self.lines[1:]:
318             if line == '':
319                 continue
320             account, amount, currency = line
321             if amount is None:
322                 sink_account = account
323                 continue
324             apply_booking_to_account_balances(account_changes, account, currency, amount)
325             if currency not in debt:
326                 debt[currency] = amount
327             else:
328                 debt[currency] += amount
329         if sink_account:
330             for currency, amount in debt.items():
331                 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
332                 self.sink[currency] = -amount
333         return account_changes
334
335
336
337 class LedgerDB(PlomDB):
338
339     def __init__(self, prefix):
340         self.prefix = prefix 
341         self.bookings = []
342         self.comments = []
343         self.real_lines = []
344         super().__init__(db_path)
345         ret = parse_lines(self.real_lines)
346         self.bookings += ret[0]
347         self.comments += ret[1]
348
349     def read_db_file(self, f):
350         self.real_lines += [l.rstrip() for l in f.readlines()]
351
352     def get_lines(self, start, end):
353         return self.real_lines[start:end]
354
355     def write_db(self, text, mode='w'):
356         if text[-1] != '\n':
357             text += '\n'
358         self.write_text_to_db(text)
359
360     def insert_at_date(self, lines, date):
361         print("DEBUG insert_at_date")
362         start_at = 0 
363         if len(self.bookings) > 0:
364             if date >= self.bookings[-1].date_string:
365                 start_at = len(self.real_lines)
366                 lines = [''] + lines
367             else:
368                 for b in self.bookings:
369                     if b.date_string == date:
370                         start_at = b.start_line 
371                     elif b.date_string > date:
372                         start_at = b.start_line 
373                         break
374         return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
375
376     def update(self, start, end, lines, date):
377         print("DEBUG update")
378         total_lines = self.real_lines[:start] + self.real_lines[end:]
379         n_original_lines = end - start
380         start_at = len(total_lines)
381         for b in self.bookings:
382             if b.date_string == date:
383                 if start_at == len(total_lines) or b.start_line == start:
384                     start_at = b.start_line 
385                     if b.start_line > start:
386                         start_at -= n_original_lines
387             elif b.date_string > date:
388                 break
389         if start_at == len(total_lines):
390             lines = [''] + lines
391         return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
392
393     def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
394         total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
395         _, _ = parse_lines(lines)
396         text = '\n'.join(total_lines)
397         self.write_db(text)
398         return start_at
399
400     def get_nth_for_booking_of_start_line(self, start_line):
401         nth = 0
402         for b in self.bookings:
403             if b.start_line >= start_line:
404                 break
405             nth += 1
406         return nth
407
408     def add_taxes(self, lines, finish=False):
409         ret = []
410         bookings, _ = parse_lines(lines)
411         date = bookings[0].date_string
412         acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
413         acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
414         acc_kk = 'Expenses:KrankenKasse'
415         acc_est = 'Reserves:Einkommenssteuer'
416         acc_assets = 'Assets'
417         acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
418         last_monthbreak_assets = 0
419         last_monthbreak_est = 0
420         last_monthbreak_kk_minimum = 0
421         last_monthbreak_kk_add = 0
422         buffer_expenses = 0
423         kk_expenses = 0
424         est_expenses = 0
425         months_passed = -int(finish) 
426         for b in self.bookings:
427             if date == b.date_string:
428                 break
429             acc_keys = b.account_changes.keys()
430             if acc_buffer in acc_keys:
431                 buffer_expenses -= b.account_changes[acc_buffer]['€']
432             if acc_kk_add in acc_keys:
433                 kk_expenses += b.account_changes[acc_kk_add]['€']
434             if acc_kk in acc_keys:
435                 kk_expenses += b.account_changes[acc_kk]['€']
436             if acc_est in acc_keys:
437                 est_expenses += b.account_changes[acc_est]['€']
438             if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
439                 months_passed += 1
440                 if finish:
441                     last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
442                     last_monthbreak_est = b.account_changes[acc_est]['€']
443                     last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
444                     last_monthbreak_assets = b.account_changes[acc_buffer]['€']
445         old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
446         if finish:
447             ret += [f'  {acc_est}  {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
448         _, account_sums = bookings_to_account_tree(bookings)
449         expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
450         needed_income_before_kk = expenses_so_far
451         ESt_this_month = 0
452         left_over = needed_income_before_kk - ESt_this_month
453         too_low = 0
454         too_high = 2 * needed_income_before_kk
455         E0 = decimal.Decimal(10908)
456         E1 = decimal.Decimal(15999)
457         E2 = decimal.Decimal(62809)
458         E3 = decimal.Decimal(277825)
459         while True:
460             zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
461             if finish:
462                 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
463             if zvE < E0:
464                 ESt = decimal.Decimal(0)
465             elif zvE < E1:
466                 y = (zvE - E0)/10000
467                 ESt = (decimal.Decimal(979.18) * y + 1400) * y
468             elif zvE < E2:
469                 y = (zvE - E1)/10000
470                 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
471             elif zvE < E3:
472                 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809))  + decimal.Decimal(16405.54)
473             else:
474                 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
475             ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
476             left_over = needed_income_before_kk - ESt_this_month
477             if abs(left_over - expenses_so_far) < 0.001:
478                 break
479             elif left_over < expenses_so_far:
480                 too_low = needed_income_before_kk
481             elif left_over > expenses_so_far:
482                 too_high = needed_income_before_kk
483             needed_income_before_kk = too_low + (too_high - too_low)/2
484         ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
485         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}€']
486         kk_minimum_income = 1131.67
487         if date < '2023-02-01':
488             kk_minimum_income = decimal.Decimal(1096.67)
489             kk_factor = decimal.Decimal(0.189)
490             kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
491         elif date < '2023-08-01':
492             kk_factor = decimal.Decimal(0.191)
493             kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
494         else:
495             kk_factor = decimal.Decimal(0.197)
496             kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
497         kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
498         kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
499         hit_kk_minimum_income_limit = False
500         if kk_add_so_far + kk_add < 0:
501             hit_kk_minimum_income_limit = True 
502             kk_add_uncorrect = kk_add
503             kk_add = -(kk_add + kk_add_so_far) 
504         kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
505         if finish:
506             ret += [f'  {acc_kk_add}  {-last_monthbreak_kk_add}€  ; for old assumption of needed income']
507         else:
508             ret += [f'  {acc_kk_minimum}  {kk_minimum_tax}€  ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
509         if hit_kk_minimum_income_limit:
510             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']
511         else:
512             ret += [f'  {acc_kk_add}  {kk_add}€  ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
513         diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
514         if not finish:
515             diff += kk_minimum_tax
516         final_minus = expenses_so_far - old_needed_income_before_anything + diff
517         ret += [f'  {acc_assets}  {-diff} €']
518         ret += [f'  {acc_assets}  {final_minus} €']
519         year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus 
520         if finish:
521             ret += [f'  {acc_buffer}  {-final_minus} €']
522         else:
523             ret += [f'  {acc_buffer}  {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
524         return ret
525
526     def ledger_as_html(self):
527         booking_tmpl = jinja2.Template(booking_html)
528         single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />')  ##
529         elements_to_write = []
530         last_i = i = 0  ##
531         for nth, booking in enumerate(self.bookings):
532             move_up = nth > 0 and self.bookings[nth - 1].date_string == booking.date_string
533             move_down = nth < len(self.bookings) - 1 and self.bookings[nth + 1].date_string == booking.date_string
534             booking_end = last_i = booking.start_line + len(booking.lines)
535             booking_lines = []
536             i = booking.start_line  ##
537             elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:i] if c != '']  ##
538             for booking_line in booking.lines[1:]:
539                  i += 1  ##
540                  comment = self.comments[i]  ##
541                  if booking_line == '':
542                      booking_lines += [{'acc': None, 'money': None, 'comment': comment}]  ##
543                      continue
544                  account = booking_line[0]
545                  money = ''
546                  if booking_line[1] is not None:
547                      money = f'{booking_line[1]} {booking_line[2]}'
548                  booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}]  ##
549             elements_to_write += [booking_tmpl.render(
550                 prefix=self.prefix,
551                 nth=nth,
552                 start=booking.start_line,
553                 end=booking_end,
554                 date=booking.date_string,
555                 desc=booking.description,
556                 head_comment=self.comments[booking.start_line],
557                 move_up=move_up,
558                 move_down=move_down,
559                 booking_lines = booking_lines)]
560         elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:] if c != '']  #
561         return '\n'.join(elements_to_write)
562
563     def balance_as_html(self, until=None):
564         bookings = self.bookings[:until if until is None else int(until)]
565         lines = []
566         account_tree, account_sums = bookings_to_account_tree(bookings)
567         def print_subtree(lines, indent, node, subtree, path):
568             line = f"{indent}{node}"
569             n_tabs = 5 - (len(line) // 8)
570             line += n_tabs * "\t"
571             if "€" in account_sums[path + node].keys():
572                 amount = account_sums[path + node]["€"]
573                 line += f"{amount:9.2f} €\t"
574             else:
575                 line += f"\t\t"
576             for currency, amount in account_sums[path + node].items():
577                 if currency != '€' and amount > 0:
578                     line += f"{amount:5.2f} {currency}\t"
579             lines += [line]
580             indent += "  "
581             for k, v in sorted(subtree.items()):
582                 print_subtree(lines, indent, k, v, path + node + ":")
583         for k, v in sorted(account_tree.items()):
584             print_subtree(lines, "", k, v, "")
585         content = "\n".join(lines)
586         return f"<pre>{content}</pre>"
587
588     def add_free(self, start=0, end=0, copy=False):
589         tmpl = jinja2.Template(add_form_header + add_free_html + add_form_footer) 
590         lines = self.get_lines(start, end)
591         if copy:
592             start = end = 0
593         return tmpl.render(action=self.prefix + '/add_free', start=start, end=end, lines=lines)
594
595     def add_structured(self, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
596         tmpl = jinja2.Template(add_form_header + add_structured_html + add_form_footer) 
597         lines = temp_lines if len(''.join(temp_lines)) > 0 else self.get_lines(start, end)
598         bookings, comments = parse_lines(lines, validate_bookings=False)
599         if len(bookings) > 1:
600             raise PlomException('can only structurally edit single Booking')
601         if add_empty_line is not None:
602             comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
603             booking = bookings[0]
604             booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
605         action = self.prefix + '/add_structured'
606         datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
607         for b in self.bookings:
608             datalist_sets['descriptions'].add(b.description)
609             for account, moneys in b.account_changes.items():
610                 datalist_sets['accounts'].add(account)
611                 for currency in moneys.keys():
612                     datalist_sets['currencies'].add(currency)
613         content = ''
614         today = str(datetime.now())[:10]
615         booking_lines = []
616         if copy:
617             start = end = 0
618         desc = head_comment = ''
619         if len(bookings) == 0:
620             date=today
621         else:
622             booking = bookings[0]
623             desc = booking.description
624             date = today if copy else booking.date_string
625             head_comment=comments[0]
626             for i in range(1, len(comments)):
627                 account = amount = currency = ''
628                 if i < len(booking.lines) and booking.lines[i] != '':
629                     account = booking.lines[i][0]
630                     amount = booking.lines[i][1]
631                     currency = booking.lines[i][2]
632                 booking_lines += [{
633                         'i': i,
634                         'acc': account,
635                         'amt': amount,
636                         'curr': currency if currency else '€',
637                         'comment': comments[i],
638                         'comm_cols': len(comments[i])}]
639         for i in range(len(comments), len(comments) + 8):
640             booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
641         content += tmpl.render(
642                 action=action,
643                 date=date,
644                 desc=desc,
645                 head_comment=head_comment,
646                 booking_lines=booking_lines,
647                 datalist_sets=datalist_sets,
648                 start=start,
649                 end=end)
650         return content
651
652     def move_up(self, start, end):
653         prev_booking = None
654         for redir_nth, b in enumerate(self.bookings):
655             if b.start_line >= start:
656                 break
657             prev_booking = b
658         start_at = prev_booking.start_line 
659         self.make_move(start, end, start_at)
660         return redir_nth - 1
661
662     def move_down(self, start, end):
663         next_booking = None
664         for redir_nth, b in enumerate(self.bookings):
665             if b.start_line > start:
666                 next_booking = b
667                 break
668         start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1 
669         self.make_move(start, end, start_at-1)
670         return redir_nth
671
672     def make_move(self, start, end, start_at):
673         lines = self.get_lines(start, end)
674         total_lines = self.real_lines[:start-1] + self.real_lines[end:]  # +1 because we reduce the original position's two empty border lines to in-between line
675         self.write_lines_in_total_lines_at(total_lines, start_at, lines)
676
677     def booking_lines_from_postvars(self, postvars):
678         add_empty_line = None
679         date = postvars['date'][0]
680         description = postvars['description'][0]
681         start_comment = postvars['line_0_comment'][0]
682         start_line = f'{date} {description}'
683         if start_comment.rstrip() != '':
684             start_line += f' ; {start_comment}' 
685         lines = [start_line]
686         if 'line_0_add' in postvars.keys():
687             add_empty_line = 0
688         i = j = 1
689         while f'line_{i}_comment' in postvars.keys():
690             if f'line_{i}_delete' in postvars.keys():
691                 i += 1
692                 continue
693             elif f'line_{i}_delete_after' in postvars.keys():
694                 break 
695             elif f'line_{i}_add' in postvars.keys():
696                 add_empty_line = j
697             account = postvars[f'line_{i}_account'][0]
698             amount = postvars[f'line_{i}_amount'][0]
699             currency = postvars[f'line_{i}_currency'][0]
700             comment = postvars[f'line_{i}_comment'][0]
701             i += 1
702             new_main = f'  {account}  {amount}'
703             if '' == new_main.rstrip() == comment.rstrip():  # don't write empty lines, ignore currency if nothing else set
704                 continue
705             if len(amount.rstrip()) > 0:
706                 new_main += f' {currency}'
707             j += 1
708             new_line = new_main
709             if comment.rstrip() != '':
710                 new_line += f'  ; {comment}'
711             lines += [new_line]
712         if 'add_sink' in postvars.keys():
713             temp_lines = lines.copy() + ['_']
714             try:
715                 temp_bookings, _ = parse_lines(temp_lines)
716                 for currency in temp_bookings[0].sink:
717                     amount = temp_bookings[0].sink[currency]
718                     lines += [f'Assets  {amount:.2f} {currency}']
719             except PlomException:
720                 pass
721         elif 'add_taxes' in postvars.keys():
722             lines += self.add_taxes(lines, finish=False)
723         elif 'add_taxes2' in postvars.keys():
724             lines += self.add_taxes(lines, finish=True)
725         elif 'replace' in postvars.keys():
726             for i, line in enumerate(lines):
727                 lines[i] = line.replace(postvars['replace_from'][0], postvars['replace_to'][0])
728         return lines, add_empty_line
729
730
731
732 class LedgerHandler(PlomHandler):
733     
734     def app_init(self, handler):
735         default_path = '/ledger'
736         handler.add_route('GET', default_path, self.forward_gets) 
737         handler.add_route('POST', default_path, self.forward_posts) 
738         return 'ledger', default_path 
739
740     def do_POST(self):
741         self.try_do(self.forward_posts)
742
743     def forward_posts(self):
744         prefix = self.apps['ledger'] if hasattr(self, 'apps') else '' 
745         parsed_url = urlparse(self.path)
746         length = int(self.headers['content-length'])
747         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
748         start = int(postvars['start'][0])
749         end = int(postvars['end'][0])
750         db = LedgerDB(prefix)
751         add_empty_line = None
752         lines = []
753         # get inputs
754         if prefix + '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
755             lines, add_empty_line = db.booking_lines_from_postvars(postvars) 
756         elif prefix + '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
757             lines = postvars['booking'][0].splitlines()
758         # validate where appropriate
759         if ('save' in postvars.keys()) or ('check' in postvars.keys()):
760             _, _ = parse_lines(lines)
761         # if saving, process where to and where to redirect after
762         if 'save' in postvars.keys():
763             last_date = str(datetime.now())[:10]
764             if len(db.bookings) > 0:
765                 last_date = db.bookings[-1].date_string
766             target_date = last_date[:] 
767             first_line_tokens = lines[0].split() if len(lines) > 0 else ''
768             first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
769             try:
770                 datetime.strptime(first_token, '%Y-%m-%d')
771                 target_date = first_token
772             except ValueError:
773                  pass
774             if start == end == 0:
775                 start = db.insert_at_date(lines, target_date)
776                 nth = db.get_nth_for_booking_of_start_line(start) 
777             else:
778                 new_start = db.update(start, end, lines, target_date)
779                 nth = db.get_nth_for_booking_of_start_line(new_start)
780                 if new_start > start: 
781                     nth -= 1 
782             self.redirect(prefix + f'/#{nth}')
783         # otherwise just re-build editing form
784         else:
785             if prefix + '/add_structured' == parsed_url.path: 
786                 edit_content = db.add_structured(start, end, temp_lines=lines, add_empty_line=add_empty_line)
787             else:
788                 edit_content = db.add_free(start, end)
789             header = jinja2.Template(html_head).render(prefix=prefix)
790             self.send_HTML(header + edit_content)
791
792     def do_GET(self):
793         self.try_do(self.forward_gets)
794
795     def forward_gets(self):
796         prefix = self.apps['ledger'] if hasattr(self, 'apps') else '' 
797         parsed_url = urlparse(self.path)
798         params = parse_qs(parsed_url.query)
799         start = int(params.get('start', ['0'])[0])
800         end = int(params.get('end', ['0'])[0])
801         db = LedgerDB(prefix=prefix)
802         if parsed_url.path == prefix + '/balance':
803             stop = params.get('stop', [None])[0]
804             page = db.balance_as_html(stop)
805         elif parsed_url.path == prefix + '/add_free':
806             page = db.add_free(start, end)
807         elif parsed_url.path == prefix + '/add_structured':
808             page = db.add_structured(start, end)
809         elif parsed_url.path == prefix + '/copy_free':
810             page = db.add_free(start, end, copy=True)
811         elif parsed_url.path == prefix + '/copy_structured':
812             page = db.add_structured(start, end, copy=True)
813         elif parsed_url.path == prefix + '/move_up':
814             nth = db.move_up(start, end)
815             self.redirect(prefix + f'/#{nth}')
816             return
817         elif parsed_url.path == prefix + '/move_down':
818             nth = db.move_down(start, end)
819             self.redirect(prefix + f'/#{nth}')
820             return
821         else:
822             page = db.ledger_as_html()
823         header = jinja2.Template(html_head).render(prefix=prefix)
824         self.send_HTML(header + page)
825
826
827
828 if __name__ == "__main__":  
829     run_server(server_port, LedgerHandler)