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