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