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