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