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