4 from datetime import datetime, timedelta
5 from urllib.parse import parse_qs, urlparse
6 from plomlib import PlomDB, PlomException, run_server, PlomHandler
9 db_path = '/home/plom/org/ledger2023.dat'
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; }
23 <a href="{{prefix}}/ledger">ledger</a>
24 <a href="{{prefix}}/balance">balance</a>
25 <a href="{{prefix}}/add_free">add free</a>
26 <a href="{{prefix}}/add_structured">add structured</a>
30 <p id="{{nth}}"><a href="{{prefix}}#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
31 <span class="meta">[edit: <a href="{{prefix}}/add_structured?start={{start}}&end={{end}}">structured</a>
32 / <a href="{{prefix}}/add_free?start={{start}}&end={{end}}">free</a>
33 | copy:<a href="{{prefix}}/copy_structured?start={{start}}&end={{end}}">structured</a>
34 / <a href="{{prefix}}/copy_free?start={{start}}&end={{end}}">free</a>
35 | move {% if move_up %}<a href="{{prefix}}/move_up?start={{start}}&end={{end}}">up</a>{% else %}up{% endif %}/{% if move_down %}<a href="{{prefix}}/move_down?start={{start}}&end={{end}}">down</a>{% else %}down{% endif %}
36 | <a href="{{prefix}}/balance?stop={{nth+1}}">balance after</a>
39 {% for l in booking_lines %}
41 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
43 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
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" />
53 <input type="hidden" name="start" value={{start}} />
54 <input type="hidden" name="end" value={{end}} />
55 <input type="submit" name="save" value="save!">
58 add_free_html = """<br />
59 <textarea name="booking" rows=10 cols=80>
60 {% for line in lines %}{{ line }}
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" />
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="[+]" />
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>
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>
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
100 account_sums[account][currency] += amount
103 def bookings_to_account_tree(bookings):
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)
110 def collect_branches(account_name, path):
113 while len(path_copy) > 0:
114 step = path_copy.pop(0)
116 toks = account_name.split(":", maxsplit=1)
118 if parent in node.keys():
124 k, v = collect_branches(toks[1], path + [parent])
125 if k not in child.keys():
130 for account_name in sorted(account_sums.keys()):
131 k, v = collect_branches(account_name, [])
132 if k not in account_tree.keys():
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
147 def parse_lines(lines, validate_bookings=True):
148 inside_booking = False
149 date_string, description = None, None
154 lines = lines.copy() + [''] # to ensure a booking-ending last line
156 for i, line in enumerate(lines):
158 # we start with the case of an utterly empty line
160 stripped_line = line.rstrip()
161 if stripped_line == '':
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
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() == '':
181 booking_lines += ['']
183 # if we're starting a booking, parse by first-line pattern
184 if not inside_booking:
186 toks = non_comment.split(maxsplit=1)
187 date_string = toks[0]
189 datetime.strptime(date_string, '%Y-%m-%d')
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
196 description = toks[1]
198 raise PlomException(f"{prefix} bad description: {description}")
199 inside_booking = True
200 booking_lines += [non_comment]
202 # otherwise, read as transfer data
203 toks = non_comment.split() # ignore specification's allowance of single spaces in names
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"
215 amount = decimal.Decimal(toks[1])
217 except decimal.InvalidOperation:
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}")
227 inside_amount = False
228 inside_currency = False
232 for i, c in enumerate(value):
234 if c in decimal_chars:
237 inside_currency = True
239 if c in decimal_chars and len(amount_string) == 0:
240 inside_currency = False
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
253 if c == '-' and len(amount_string) > 1:
254 raise PlomException(f"{prefix} amount has non-start '-': {value}")
257 raise PlomException(f"{prefix} amount has multiple dots: {value}")
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)]
266 raise PlomException(f"{prefix} last booking unfinished")
267 return bookings, comments
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
278 self.validate_booking_lines()
280 self.account_changes = self.parse_booking_lines_to_account_changes()
282 def validate_booking_lines(self):
283 prefix = f"booking at line {self.start_line}"
286 for line in self.lines[1:]:
289 _, amount, currency = line
292 raise PlomException(f"{prefix} relates more than one empty value of same currency {currency}")
295 if currency not in sums:
297 sums[currency] += amount
298 if empty_values == 0:
299 for k, v in sums.items():
301 raise PlomException(f"{prefix} does not add up to zero / {k} {v}")
304 for k, v in sums.items():
308 raise PlomException(f"{prefix} has empty value that cannot be filled")
310 def parse_booking_lines_to_account_changes(self):
314 for line in self.lines[1:]:
317 account, amount, currency = line
319 sink_account = account
321 apply_booking_to_account_balances(account_changes, account, currency, amount)
322 if currency not in debt:
323 debt[currency] = amount
325 debt[currency] += amount
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
334 class LedgerDB(PlomDB):
336 def __init__(self, prefix):
341 super().__init__(db_path)
342 ret = parse_lines(self.real_lines)
343 self.bookings += ret[0]
344 self.comments += ret[1]
346 def read_db_file(self, f):
347 self.real_lines += [l.rstrip() for l in f.readlines()]
349 def get_lines(self, start, end):
350 return self.real_lines[start:end]
352 def write_db(self, text, mode='w'):
353 self.write_text_to_db(text)
355 def insert_at_date(self, lines, date):
356 start_at = len(self.real_lines)
357 for b in self.bookings:
358 if b.date_string >= date:
359 start_at = b.start_line
361 elif b.date_string > date:
363 if start_at == len(self.real_lines):
365 return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
367 def update(self, start, end, lines, date):
368 print("DEBUG update", date)
369 total_lines = self.real_lines[:start] + self.real_lines[end:]
370 n_original_lines = end - start
371 start_at = len(total_lines)
372 for b in self.bookings:
373 if b.date_string == date:
374 if start_at == len(total_lines) or b.start_line == start:
375 start_at = b.start_line
376 if b.start_line > start:
377 start_at -= n_original_lines
378 elif b.date_string > date:
380 if start_at == len(total_lines):
382 return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
384 def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
385 total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
386 _, _ = parse_lines(lines)
387 text = '\n'.join(total_lines)
391 def get_nth_for_booking_of_start_line(self, start_line):
393 for b in self.bookings:
394 if b.start_line >= start_line:
399 def add_taxes(self, lines, finish=False):
401 bookings, _ = parse_lines(lines)
402 date = bookings[0].date_string
403 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
404 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
405 acc_kk = 'Expenses:KrankenKasse'
406 acc_est = 'Reserves:Einkommenssteuer'
407 acc_assets = 'Assets'
408 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
409 last_monthbreak_assets = 0
410 last_monthbreak_est = 0
411 last_monthbreak_kk_minimum = 0
412 last_monthbreak_kk_add = 0
416 months_passed = -int(finish)
417 for b in self.bookings:
418 if date == b.date_string:
420 acc_keys = b.account_changes.keys()
421 if acc_buffer in acc_keys:
422 buffer_expenses -= b.account_changes[acc_buffer]['€']
423 if acc_kk_add in acc_keys:
424 kk_expenses += b.account_changes[acc_kk_add]['€']
425 if acc_kk in acc_keys:
426 kk_expenses += b.account_changes[acc_kk]['€']
427 if acc_est in acc_keys:
428 est_expenses += b.account_changes[acc_est]['€']
429 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
432 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
433 last_monthbreak_est = b.account_changes[acc_est]['€']
434 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
435 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
436 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
438 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
439 _, account_sums = bookings_to_account_tree(bookings)
440 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
441 needed_income_before_kk = expenses_so_far
443 left_over = needed_income_before_kk - ESt_this_month
445 too_high = 2 * needed_income_before_kk
446 E0 = decimal.Decimal(10908)
447 E1 = decimal.Decimal(15999)
448 E2 = decimal.Decimal(62809)
449 E3 = decimal.Decimal(277825)
451 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
453 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
455 ESt = decimal.Decimal(0)
458 ESt = (decimal.Decimal(979.18) * y + 1400) * y
461 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
463 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
465 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
466 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
467 left_over = needed_income_before_kk - ESt_this_month
468 if abs(left_over - expenses_so_far) < 0.001:
470 elif left_over < expenses_so_far:
471 too_low = needed_income_before_kk
472 elif left_over > expenses_so_far:
473 too_high = needed_income_before_kk
474 needed_income_before_kk = too_low + (too_high - too_low)/2
475 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
476 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}€']
477 kk_minimum_income = 1131.67
478 if date < '2023-02-01':
479 kk_minimum_income = decimal.Decimal(1096.67)
480 kk_factor = decimal.Decimal(0.189)
481 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
482 elif date < '2023-08-01':
483 kk_factor = decimal.Decimal(0.191)
484 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
486 kk_factor = decimal.Decimal(0.197)
487 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
488 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
489 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
490 hit_kk_minimum_income_limit = False
491 if kk_add_so_far + kk_add < 0:
492 hit_kk_minimum_income_limit = True
493 kk_add_uncorrect = kk_add
494 kk_add = -(kk_add + kk_add_so_far)
495 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
497 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
499 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
500 if hit_kk_minimum_income_limit:
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}€ = {kk_add_uncorrect:.2f}€ would reduce current {acc_kk_dd} ({kk_add_so_far:.2f}€) below 0']
503 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
504 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
506 diff += kk_minimum_tax
507 final_minus = expenses_so_far - old_needed_income_before_anything + diff
508 ret += [f' {acc_assets} {-diff} €']
509 ret += [f' {acc_assets} {final_minus} €']
510 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
512 ret += [f' {acc_buffer} {-final_minus} €']
514 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
517 def ledger_as_html(self):
518 booking_tmpl = jinja2.Template(booking_html)
519 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
520 elements_to_write = []
522 for nth, booking in enumerate(self.bookings):
523 move_up = nth > 0 and self.bookings[nth - 1].date_string == booking.date_string
524 move_down = nth < len(self.bookings) - 1 and self.bookings[nth + 1].date_string == booking.date_string
525 booking_end = last_i = booking.start_line + len(booking.lines)
527 i = booking.start_line ##
528 elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:i] if c != ''] ##
529 for booking_line in booking.lines[1:]:
531 comment = self.comments[i] ##
532 if booking_line == '':
533 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
535 account = booking_line[0]
537 if booking_line[1] is not None:
538 money = f'{booking_line[1]} {booking_line[2]}'
539 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
540 elements_to_write += [booking_tmpl.render(
543 start=booking.start_line,
545 date=booking.date_string,
546 desc=booking.description,
547 head_comment=self.comments[booking.start_line],
550 booking_lines = booking_lines)]
551 elements_to_write += [single_c_tmpl.render(c=c) for c in self.comments[last_i:] if c != ''] #
552 return '\n'.join(elements_to_write)
554 def balance_as_html(self, until=None):
555 bookings = self.bookings[:until if until is None else int(until)]
557 account_tree, account_sums = bookings_to_account_tree(bookings)
558 def print_subtree(lines, indent, node, subtree, path):
559 line = f"{indent}{node}"
560 n_tabs = 5 - (len(line) // 8)
561 line += n_tabs * "\t"
562 if "€" in account_sums[path + node].keys():
563 amount = account_sums[path + node]["€"]
564 line += f"{amount:9.2f} €\t"
567 for currency, amount in account_sums[path + node].items():
568 if currency != '€' and amount > 0:
569 line += f"{amount:5.2f} {currency}\t"
572 for k, v in sorted(subtree.items()):
573 print_subtree(lines, indent, k, v, path + node + ":")
574 for k, v in sorted(account_tree.items()):
575 print_subtree(lines, "", k, v, "")
576 content = "\n".join(lines)
577 return f"<pre>{content}</pre>"
579 def add_free(self, start=0, end=0, copy=False):
580 tmpl = jinja2.Template(add_form_header + add_free_html + add_form_footer)
581 lines = self.get_lines(start, end)
584 return tmpl.render(action=self.prefix + '/add_free', start=start, end=end, lines=lines)
586 def add_structured(self, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
587 tmpl = jinja2.Template(add_form_header + add_structured_html + add_form_footer)
588 lines = temp_lines if len(''.join(temp_lines)) > 0 else self.get_lines(start, end)
589 bookings, comments = parse_lines(lines, validate_bookings=False)
590 if len(bookings) > 1:
591 raise PlomException('can only structurally edit single Booking')
592 if add_empty_line is not None:
593 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
594 booking = bookings[0]
595 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
596 action = self.prefix + '/add_structured'
597 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
598 for b in self.bookings:
599 datalist_sets['descriptions'].add(b.description)
600 for account, moneys in b.account_changes.items():
601 datalist_sets['accounts'].add(account)
602 for currency in moneys.keys():
603 datalist_sets['currencies'].add(currency)
605 today = str(datetime.now())[:10]
609 desc = head_comment = ''
610 if len(bookings) == 0:
611 for i in range(1, 8):
612 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
615 booking = bookings[0]
616 desc = booking.description
617 date = today if copy else booking.date_string
618 head_comment=comments[0]
619 last_line = len(comments)
620 for i in range(1, len(comments)):
621 account = amount = currency = ''
622 if i < len(booking.lines) and booking.lines[i] != '':
623 account = booking.lines[i][0]
624 amount = booking.lines[i][1]
625 currency = booking.lines[i][2]
630 'curr': currency if currency else '€',
631 'comment': comments[i],
632 'comm_cols': len(comments[i])}]
633 content += tmpl.render(
637 head_comment=head_comment,
638 booking_lines=booking_lines,
639 datalist_sets=datalist_sets,
644 def move_up(self, start, end):
646 for redir_nth, b in enumerate(self.bookings):
647 if b.start_line >= start:
650 start_at = prev_booking.start_line
651 self.make_move(start, end, start_at)
654 def move_down(self, start, end):
656 for redir_nth, b in enumerate(self.bookings):
657 if b.start_line > start:
660 start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1
661 self.make_move(start, end, start_at)
664 def make_move(self, start, end, start_at):
665 lines = self.get_lines(start, end)
666 total_lines = self.real_lines[:start] + self.real_lines[end:]
667 self.write_lines_in_total_lines_at(total_lines, start_at, lines)
669 def booking_lines_from_postvars(self, postvars):
670 add_empty_line = None
671 date = postvars['date'][0]
672 description = postvars['description'][0]
673 start_comment = postvars['line_0_comment'][0]
674 start_line = f'{date} {description}'
675 if start_comment.rstrip() != '':
676 start_line += f' ; {start_comment}'
678 if 'line_0_add' in postvars.keys():
681 while f'line_{i}_comment' in postvars.keys():
682 if f'line_{i}_delete' in postvars.keys():
685 elif f'line_{i}_delete_after' in postvars.keys():
687 elif f'line_{i}_add' in postvars.keys():
689 account = postvars[f'line_{i}_account'][0]
690 amount = postvars[f'line_{i}_amount'][0]
691 currency = postvars[f'line_{i}_currency'][0]
692 comment = postvars[f'line_{i}_comment'][0]
694 new_main = f' {account} {amount}'
695 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
697 if len(amount.rstrip()) > 0:
698 new_main += f' {currency}'
701 if comment.rstrip() != '':
702 new_line += f' ; {comment}'
704 if 'add_sink' in postvars.keys():
705 temp_lines = lines.copy() + ['_']
707 temp_bookings, _ = parse_lines(temp_lines)
708 for currency in temp_bookings[0].sink:
709 amount = temp_bookings[0].sink[currency]
710 lines += [f'Assets {amount:.2f} {currency}']
711 except PlomException:
713 if 'add_taxes' in postvars.keys():
714 lines += self.add_taxes(lines, finish=False)
715 elif 'add_taxes2' in postvars.keys():
716 lines += self.add_taxes(lines, finish=True)
717 return lines, add_empty_line
721 class LedgerHandler(PlomHandler):
723 def app_init(self, handler):
724 default_path = '/ledger'
725 handler.add_route('GET', default_path, self.forward_gets)
726 handler.add_route('POST', default_path, self.forward_posts)
727 return 'ledger', default_path
732 def forward_posts(self):
734 prefix = self.apps['ledger'] if hasattr(self, 'apps') else ''
735 parsed_url = urlparse(self.path)
736 length = int(self.headers['content-length'])
737 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
738 print("DEBUG", postvars['start'], postvars['end'])
739 start = int(postvars['start'][0])
740 end = int(postvars['end'][0])
741 db = LedgerDB(prefix)
742 add_empty_line = None
745 if prefix + '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
746 lines, add_empty_line = db.booking_lines_from_postvars(postvars)
747 elif prefix + '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
748 lines = postvars['booking'][0].splitlines()
749 # validate where appropriate
750 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
751 _, _ = parse_lines(lines)
752 # if saving, process where to and where to redirect after
753 if 'save' in postvars.keys():
754 last_date = str(datetime.now())[:10]
755 if len(db.bookings) > 0:
756 last_date = db.bookings[-1].date_string
757 target_date = last_date[:]
758 first_line_tokens = lines[0].split() if len(lines) > 0 else ''
759 first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
761 datetime.strptime(first_token, '%Y-%m-%d')
762 target_date = first_token
765 if start == end == 0:
766 start = db.insert_at_date(lines, target_date)
767 nth = db.get_nth_for_booking_of_start_line(start)
769 new_start = db.update(start, end, lines, target_date)
770 nth = db.get_nth_for_booking_of_start_line(new_start)
771 if new_start > start:
773 self.redirect(prefix + f'/#{nth}')
774 # otherwise just re-build editing form
776 if prefix + '/add_structured' == parsed_url.path:
777 edit_content = db.add_structured(start, end, temp_lines=lines, add_empty_line=add_empty_line)
779 edit_content = db.add_free(start, end)
780 header = jinja2.Template(html_head).render(prefix=prefix)
781 self.send_HTML(header + edit_content)
782 except PlomException as e:
788 def forward_gets(self):
790 prefix = self.apps['ledger'] if hasattr(self, 'apps') else ''
791 parsed_url = urlparse(self.path)
792 params = parse_qs(parsed_url.query)
793 start = int(params.get('start', ['0'])[0])
794 end = int(params.get('end', ['0'])[0])
795 db = LedgerDB(prefix=prefix)
796 if parsed_url.path == prefix + '/balance':
797 stop = params.get('stop', [None])[0]
798 page = db.balance_as_html(stop)
799 elif parsed_url.path == prefix + '/add_free':
800 page = db.add_free(start, end)
801 elif parsed_url.path == prefix + '/add_structured':
802 page = db.add_structured(start, end)
803 elif parsed_url.path == prefix + '/copy_free':
804 page = db.add_free(start, end, copy=True)
805 elif parsed_url.path == prefix + '/copy_structured':
806 page = db.add_structured(start, end, copy=True)
807 elif parsed_url.path == prefix + '/move_up':
808 nth = db.move_up(start, end)
809 self.redirect(prefix + f'/#{nth}')
811 elif parsed_url.path == prefix + '/move_down':
812 nth = db.move_down(start, end)
813 self.redirect(prefix + f'/#{nth}')
816 page = db.ledger_as_html()
817 header = jinja2.Template(html_head).render(prefix=prefix)
818 self.send_HTML(header + page)
819 except PlomException as e:
824 if __name__ == "__main__":
825 run_server(server_port, LedgerHandler)