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