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