1 from http.server import BaseHTTPRequestHandler, HTTPServer
6 from datetime import datetime, timedelta
7 from urllib.parse import parse_qs, urlparse
8 from plomlib import PlomDB, PlomException, run_server, run_server, PlomServer
13 def apply_booking_to_account_balances(account_sums, account, currency, amount):
14 if not account in account_sums:
15 account_sums[account] = {currency: amount}
16 elif not currency in account_sums[account].keys():
17 account_sums[account][currency] = amount
19 account_sums[account][currency] += amount
22 def bookings_to_account_tree(bookings):
24 for booking in bookings:
25 for account, changes in booking.account_changes.items():
26 for currency, amount in changes.items():
27 apply_booking_to_account_balances(account_sums, account, currency, amount)
29 def collect_branches(account_name, path):
32 while len(path_copy) > 0:
33 step = path_copy.pop(0)
35 toks = account_name.split(":", maxsplit=1)
37 if parent in node.keys():
43 k, v = collect_branches(toks[1], path + [parent])
44 if k not in child.keys():
49 for account_name in sorted(account_sums.keys()):
50 k, v = collect_branches(account_name, [])
51 if k not in account_tree.keys():
54 account_tree[k].update(v)
55 def collect_totals(parent_path, tree_node):
56 for k, v in tree_node.items():
57 child_path = parent_path + ":" + k
58 for currency, amount in collect_totals(child_path, v).items():
59 apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
60 return account_sums[parent_path]
61 for account_name in account_tree.keys():
62 account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
63 return account_tree, account_sums
66 def parse_lines(lines, validate_bookings=True):
67 inside_booking = False
68 date_string, description = None, None
73 lines = lines.copy() + [''] # to ensure a booking-ending last line
75 for i, line in enumerate(lines):
77 # we start with the case of an utterly empty line
79 stripped_line = line.rstrip()
80 if stripped_line == '':
82 # assume we finished a booking, finalize, and commit to DB
83 if len(booking_lines) < 2:
84 raise PlomException(f"{prefix} booking ends to early")
85 booking = Booking(date_string, description, booking_lines, start_line, validate_bookings)
87 # expect new booking to follow so re-zeroall booking data
88 inside_booking = False
89 date_string, description = None, None
92 # if non-empty line, first get comment if any, and commit to DB
93 split_by_comment = stripped_line.split(sep=";", maxsplit=1)
94 if len(split_by_comment) == 2:
95 comments[i] = split_by_comment[1].lstrip()
96 # 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
97 non_comment = split_by_comment[0].rstrip()
98 if non_comment.rstrip() == '':
100 booking_lines += ['']
102 # if we're starting a booking, parse by first-line pattern
103 if not inside_booking:
105 toks = non_comment.split(maxsplit=1)
106 date_string = toks[0]
108 datetime.strptime(date_string, '%Y-%m-%d')
110 raise PlomException(f"{prefix} bad date string: {date_string}")
111 if last_date > date_string:
112 raise PlomException(f"{prefix} out-of-order-date")
113 last_date = date_string
115 description = toks[1]
117 raise PlomException(f"{prefix} bad description: {description}")
118 inside_booking = True
119 booking_lines += [non_comment]
121 # otherwise, read as transfer data
122 toks = non_comment.split() # ignore specification's allowance of single spaces in names
124 raise PlomException(f"{prefix} too many booking line tokens: {toks}")
125 amount, currency = None, None
126 account_name = toks[0]
127 if account_name[0] == '[' and account_name[-1] == ']':
128 # ignore specification's differentiation of "virtual" accounts
129 account_name = account_name[1:-1]
130 decimal_chars = ".-0123456789"
134 amount = decimal.Decimal(toks[1])
136 except decimal.InvalidOperation:
138 amount = decimal.Decimal(toks[2])
139 except decimal.InvalidOperation:
140 raise PlomException(f"{prefix} no decimal number in: {toks[1:]}")
141 currency = toks[i_currency]
142 if currency[0] in decimal_chars:
143 raise PlomException(f"{prefix} currency starts with int, dot, or minus: {currency}")
146 inside_amount = False
147 inside_currency = False
151 for i, c in enumerate(value):
153 if c in decimal_chars:
156 inside_currency = True
158 if c in decimal_chars and len(amount_string) == 0:
159 inside_currency = False
165 if c not in decimal_chars:
166 if len(currency) > 0:
167 raise PlomException(f"{prefix} amount has non-decimal chars: {value}")
168 inside_currency = True
169 inside_amount = False
172 if c == '-' and len(amount_string) > 1:
173 raise PlomException(f"{prefix} amount has non-start '-': {value}")
176 raise PlomException(f"{prefix} amount has multiple dots: {value}")
179 if len(currency) == 0:
180 raise PlomException(f"{prefix} currency missing: {value}")
181 if len(amount_string) > 0:
182 amount = decimal.Decimal(amount_string)
183 booking_lines += [(account_name, amount, currency)]
185 raise PlomException(f"{prefix} last booking unfinished")
186 return bookings, comments
191 def __init__(self, date_string, description, booking_lines, start_line, process=True):
192 self.date_string = date_string
193 self.description = description
194 self.lines = booking_lines
195 self.start_line = start_line
197 self.validate_booking_lines()
199 self.account_changes = self.parse_booking_lines_to_account_changes()
201 def validate_booking_lines(self):
202 prefix = f"booking at line {self.start_line}"
205 for line in self.lines[1:]:
208 _, amount, currency = line
211 raise PlomException(f"{prefix} relates more than one empty value of same currency {currency}")
214 if currency not in sums:
216 sums[currency] += amount
217 if empty_values == 0:
218 for k, v in sums.items():
220 raise PlomException(f"{prefix} does not add up to zero / {k} {v}")
223 for k, v in sums.items():
227 raise PlomException(f"{prefix} has empty value that cannot be filled")
229 def parse_booking_lines_to_account_changes(self):
233 for line in self.lines[1:]:
236 account, amount, currency = line
238 sink_account = account
240 apply_booking_to_account_balances(account_changes, account, currency, amount)
241 if currency not in debt:
242 debt[currency] = amount
244 debt[currency] += amount
246 for currency, amount in debt.items():
247 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
248 self.sink[currency] = -amount
249 return account_changes
253 class LedgerDB(PlomDB):
259 super().__init__('_ledger')
260 ret = parse_lines(self.real_lines)
261 self.bookings += ret[0]
262 self.comments += ret[1]
264 def read_db_file(self, f):
265 self.real_lines += [l.rstrip() for l in f.readlines()]
267 def get_lines(self, start, end):
268 return self.real_lines[start:end]
270 def write_db(self, text, mode='w'):
271 self.write_text_to_db(text)
273 def insert_at_date(self, lines, date):
274 start_at = len(self.real_lines)
275 for b in self.bookings:
276 if b.date_string == date:
277 start_at = b.start_line
279 elif b.date_string > date:
281 if start_at == len(self.real_lines):
283 return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
285 def update(self, start, end, lines, date):
286 total_lines = self.real_lines[:start] + self.real_lines[end:]
287 n_original_lines = end - start
288 start_at = len(total_lines)
289 for b in self.bookings:
290 if b.date_string == date:
291 if start_at == len(total_lines) or b.start_line == start:
292 start_at = b.start_line
293 if b.start_line > start:
294 start_at -= n_original_lines
295 elif b.date_string > date:
297 if start_at == len(total_lines):
299 return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
301 def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
302 total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
303 _, _ = parse_lines(lines)
304 text = '\n'.join(total_lines)
308 def get_nth_for_booking_of_start_line(self, start_line):
310 for b in self.bookings:
311 if b.start_line >= start_line:
316 def add_taxes(self, lines, finish=False):
318 bookings, _ = parse_lines(lines)
319 date = bookings[0].date_string
320 acc_kk_add = 'Reserves:KrankenkassenBeitragsWachstum'
321 acc_kk_minimum = 'Reserves:Month:KrankenkassenDefaultBeitrag'
322 acc_kk = 'Expenses:KrankenKasse'
323 acc_est = 'Reserves:Einkommenssteuer'
324 acc_assets = 'Assets'
325 acc_buffer = 'Reserves:NeuAnfangsPuffer:Ausgaben'
326 last_monthbreak_assets = 0
327 last_monthbreak_est = 0
328 last_monthbreak_kk_minimum = 0
329 last_monthbreak_kk_add = 0
333 months_passed = -int(finish)
334 for b in self.bookings:
335 if date == b.date_string:
337 acc_keys = b.account_changes.keys()
338 if acc_buffer in acc_keys:
339 buffer_expenses -= b.account_changes[acc_buffer]['€']
340 if acc_kk_add in acc_keys:
341 kk_expenses += b.account_changes[acc_kk_add]['€']
342 if acc_kk in acc_keys:
343 kk_expenses += b.account_changes[acc_kk]['€']
344 if acc_est in acc_keys:
345 est_expenses += b.account_changes[acc_est]['€']
346 if acc_kk_add in acc_keys and acc_kk_minimum in acc_keys:
349 last_monthbreak_kk_add = b.account_changes[acc_kk_add]['€']
350 last_monthbreak_est = b.account_changes[acc_est]['€']
351 last_monthbreak_kk_minimum = b.account_changes[acc_kk_minimum]['€']
352 last_monthbreak_assets = b.account_changes[acc_buffer]['€']
353 old_needed_income_before_anything = - last_monthbreak_assets - last_monthbreak_kk_add - last_monthbreak_kk_minimum - last_monthbreak_est
355 ret += [f' {acc_est} {-last_monthbreak_est}€ ; for old assumption of needed income: {old_needed_income_before_anything}€']
356 _, account_sums = bookings_to_account_tree(bookings)
357 expenses_so_far = -1 * account_sums[acc_assets]['€'] + old_needed_income_before_anything
358 needed_income_before_kk = expenses_so_far
360 left_over = needed_income_before_kk - ESt_this_month
362 too_high = 2 * needed_income_before_kk
363 E0 = decimal.Decimal(10908)
364 E1 = decimal.Decimal(15999)
365 E2 = decimal.Decimal(62809)
366 E3 = decimal.Decimal(277825)
368 zvE = buffer_expenses - kk_expenses + (12 - months_passed) * needed_income_before_kk
370 zvE += last_monthbreak_assets + last_monthbreak_kk_add + last_monthbreak_kk_minimum
372 ESt = decimal.Decimal(0)
375 ESt = (decimal.Decimal(979.18) * y + 1400) * y
378 ESt = (decimal.Decimal(192.59) * y + 2397) * y + decimal.Decimal(966.53)
380 ESt = decimal.Decimal(0.42) * (zvE - decimal.Decimal(62809)) + decimal.Decimal(16405.54)
382 ESt = decimal.Decimal(0.45) * (zvE - decimal.Decimal(277825)) + decimal.Decimal(106713.52)
383 ESt_this_month = (ESt + last_monthbreak_est - est_expenses) / (12 - months_passed)
384 left_over = needed_income_before_kk - ESt_this_month
385 if abs(left_over - expenses_so_far) < 0.001:
387 elif left_over < expenses_so_far:
388 too_low = needed_income_before_kk
389 elif left_over > expenses_so_far:
390 too_high = needed_income_before_kk
391 needed_income_before_kk = too_low + (too_high - too_low)/2
392 ESt_this_month = ESt_this_month.quantize(decimal.Decimal('0.00'))
393 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}€']
394 kk_minimum_income = 1131.67
395 if date < '2023-02-01':
396 kk_minimum_income = decimal.Decimal(1096.67)
397 kk_factor = decimal.Decimal(0.189)
398 kk_minimum_tax = decimal.Decimal(207.27).quantize(decimal.Decimal('0.00'))
399 elif date < '2023-08-01':
400 kk_factor = decimal.Decimal(0.191)
401 kk_minimum_tax = decimal.Decimal(216.15).quantize(decimal.Decimal('0.00'))
403 kk_factor = decimal.Decimal(0.197)
404 kk_minimum_tax = decimal.Decimal(222.94).quantize(decimal.Decimal('0.00'))
405 kk_add_so_far = account_sums[acc_kk_add]['€'] if acc_kk_add in account_sums.keys() else 0
406 kk_add = needed_income_before_kk / (1 - kk_factor) - needed_income_before_kk - kk_minimum_tax
407 hit_kk_minimum_income_limit = False
408 if kk_add_so_far + kk_add < 0:
409 hit_kk_minimum_income_limit = True
410 kk_add_uncorrect = kk_add
411 kk_add = -(kk_add + kk_add_so_far)
412 kk_add = decimal.Decimal(kk_add).quantize(decimal.Decimal('0.00'))
414 ret += [f' {acc_kk_add} {-last_monthbreak_kk_add}€ ; for old assumption of needed income']
416 ret += [f' {acc_kk_minimum} {kk_minimum_tax}€ ; assumed minimum income {kk_minimum_income:.2f}€ * {kk_factor:.3f}']
417 if hit_kk_minimum_income_limit:
418 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']
420 ret += [f' {acc_kk_add} {kk_add}€ ; {needed_income_before_kk:.2f}€ / (1 - {kk_factor:.3f}) - {needed_income_before_kk:.2f}€ - {kk_minimum_tax}€']
421 diff = - last_monthbreak_est + ESt_this_month - last_monthbreak_kk_add + kk_add
423 diff += kk_minimum_tax
424 final_minus = expenses_so_far - old_needed_income_before_anything + diff
425 ret += [f' {acc_assets} {-diff} €']
426 ret += [f' {acc_assets} {final_minus} €']
427 year_needed = buffer_expenses + final_minus + (12 - months_passed - 1) * final_minus
429 ret += [f' {acc_buffer} {-final_minus} €']
431 ret += [f' {acc_buffer} {-final_minus} € ; assume as to earn in year: {acc_buffer} + {12 - months_passed - 1} * this = {year_needed}']
435 class LedgerServer(PlomServer):
437 <meta charset="UTF-8">
439 body { color: #000000; }
440 table { margin-bottom: 2em; }
441 th, td { text-align: left }
442 input[type=number] { text-align: right; font-family: monospace; }
443 .money { font-family: monospace; text-align: right; }
444 .comment { font-style: italic; color: #777777; }
445 .meta { font-size: 0.75em; color: #777777; }
446 .full_line_comment { display: block; white-space: nowrap; width: 0; }
449 <a href="/">ledger</a>
450 <a href="/balance">balance</a>
451 <a href="/add_free">add free</a>
452 <a href="/add_structured">add structured</a>
455 booking_tmpl = jinja2.Template("""
456 <p id="{{nth}}"><a href="#{{nth}}">{{date}}</a> {{desc}} <span class="comment">{{head_comment|e}}</span><br />
457 <span class="meta">[edit: <a href="/add_structured?start={{start}}&end={{end}}">structured</a>
458 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
459 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
460 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
461 | 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 %}
462 | <a href="/balance?stop={{nth+1}}">balance after</a>
465 {% for l in booking_lines %}
467 <tr><td>{{l.acc|e}}</td><td class="money">{{l.money|e}}</td><td class="comment">{{l.comment|e}}</td></tr>
469 <tr><td><div class="comment full_line_comment">{{l.comment|e}}</div></td></tr>
474 add_form_header = """<form method="POST" action="{{action|e}}">
475 <input type="submit" name="check" value="check" />
476 <input type="submit" name="revert" value="revert" />
478 add_form_footer = """
479 <input type="hidden" name="start" value={{start}} />
480 <input type="hidden" name="end" value={{end}} />
481 <input type="submit" name="save" value="save!">
484 footer = "</body>\n<html>"
488 parsed_url = urlparse(self.path)
489 length = int(self.headers['content-length'])
490 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
491 start = int(postvars['start'][0])
492 end = int(postvars['end'][0])
494 add_empty_line = None
497 if '/add_structured' == parsed_url.path and not 'revert' in postvars.keys():
498 lines, add_empty_line = self.booking_lines_from_postvars(postvars, db)
499 elif '/add_free' == parsed_url.path and not 'revert' in postvars.keys():
500 lines = postvars['booking'][0].splitlines()
501 # validate where appropriate
502 if ('save' in postvars.keys()) or ('check' in postvars.keys()):
503 _, _ = parse_lines(lines)
504 # if saving, process where to and where to redirect after
505 if 'save' in postvars.keys():
506 last_date = str(datetime.now())[:10]
507 if len(db.bookings) > 0:
508 last_date = db.bookings[-1].date_string
509 target_date = last_date[:]
510 first_line_tokens = lines[0].split() if len(lines) > 0 else ''
511 first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
513 datetime.strptime(first_token, '%Y-%m-%d')
514 target_date = first_token
517 if start == end == 0:
518 start = db.insert_at_date(lines, target_date)
519 nth = db.get_nth_for_booking_of_start_line(start)
521 new_start = db.update(start, end, lines, target_date)
522 nth = db.get_nth_for_booking_of_start_line(new_start)
523 if new_start > start:
525 redir_url = f'/#{nth}'
526 self.send_code_and_headers(302, [('Location', redir_url)])
527 # otherwise just re-build editing form
529 if '/add_structured' == parsed_url.path:
530 edit_content = self.add_structured(db, start, end, temp_lines=lines, add_empty_line=add_empty_line)
532 edit_content = self.add_free(db, start, end)
533 self.send_HTML(self.header + edit_content + self.footer)
534 except PlomException as e:
539 parsed_url = urlparse(self.path)
540 params = parse_qs(parsed_url.query)
541 start = int(params.get('start', ['0'])[0])
542 end = int(params.get('end', ['0'])[0])
545 if parsed_url.path == '/balance':
546 stop = params.get('stop', [None])[0]
547 page += self.balance_as_html(db, stop)
548 elif parsed_url.path == '/add_free':
549 page += self.add_free(db, start, end)
550 elif parsed_url.path == '/add_structured':
551 page += self.add_structured(db, start, end)
552 elif parsed_url.path == '/copy_free':
553 page += self.add_free(db, start, end, copy=True)
554 elif parsed_url.path == '/copy_structured':
555 page += self.add_structured(db, start, end, copy=True)
556 elif parsed_url.path == '/move_up':
557 nth = self.move_up(db, start, end)
558 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
560 elif parsed_url.path == '/move_down':
561 nth = self.move_down(db, start, end)
562 self.send_code_and_headers(302, [('Location', f'/#{nth}')])
565 page += self.ledger_as_html(db)
568 except PlomException as e:
571 def booking_lines_from_postvars(self, postvars, db):
572 add_empty_line = None
573 date = postvars['date'][0]
574 description = postvars['description'][0]
575 start_comment = postvars['line_0_comment'][0]
576 start_line = f'{date} {description}'
577 if start_comment.rstrip() != '':
578 start_line += f' ; {start_comment}'
580 if 'line_0_add' in postvars.keys():
583 while f'line_{i}_comment' in postvars.keys():
584 if f'line_{i}_delete' in postvars.keys():
587 elif f'line_{i}_delete_after' in postvars.keys():
589 elif f'line_{i}_add' in postvars.keys():
591 account = postvars[f'line_{i}_account'][0]
592 amount = postvars[f'line_{i}_amount'][0]
593 currency = postvars[f'line_{i}_currency'][0]
594 comment = postvars[f'line_{i}_comment'][0]
596 new_main = f' {account} {amount}'
597 if '' == new_main.rstrip() == comment.rstrip(): # don't write empty lines, ignore currency if nothing else set
599 if len(amount.rstrip()) > 0:
600 new_main += f' {currency}'
603 if comment.rstrip() != '':
604 new_line += f' ; {comment}'
606 if 'add_sink' in postvars.keys():
607 temp_lines = lines.copy() + ['_']
609 temp_bookings, _ = parse_lines(temp_lines)
610 for currency in temp_bookings[0].sink:
611 amount = temp_bookings[0].sink[currency]
612 lines += [f'Assets {amount:.2f} {currency}']
613 except PlomException:
615 if 'add_taxes' in postvars.keys():
616 lines += db.add_taxes(lines, finish=False)
617 elif 'add_taxes2' in postvars.keys():
618 lines += db.add_taxes(lines, finish=True)
619 return lines, add_empty_line
621 def balance_as_html(self, db, until=None):
622 bookings = db.bookings[:until if until is None else int(until)]
624 account_tree, account_sums = bookings_to_account_tree(bookings)
625 def print_subtree(lines, indent, node, subtree, path):
626 line = f"{indent}{node}"
627 n_tabs = 5 - (len(line) // 8)
628 line += n_tabs * "\t"
629 if "€" in account_sums[path + node].keys():
630 amount = account_sums[path + node]["€"]
631 line += f"{amount:9.2f} €\t"
634 for currency, amount in account_sums[path + node].items():
635 if currency != '€' and amount > 0:
636 line += f"{amount:5.2f} {currency}\t"
639 for k, v in sorted(subtree.items()):
640 print_subtree(lines, indent, k, v, path + node + ":")
641 for k, v in sorted(account_tree.items()):
642 print_subtree(lines, "", k, v, "")
643 content = "\n".join(lines)
644 return f"<pre>{content}</pre>"
646 def ledger_as_html(self, db):
647 single_c_tmpl = jinja2.Template('<span class="comment">{{c|e}}</span><br />') ##
648 elements_to_write = []
650 for nth, booking in enumerate(db.bookings):
651 move_up = nth > 0 and db.bookings[nth - 1].date_string == booking.date_string
652 move_down = nth < len(db.bookings) - 1 and db.bookings[nth + 1].date_string == booking.date_string
653 booking_end = last_i = booking.start_line + len(booking.lines)
655 i = booking.start_line ##
656 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:i] if c != ''] ##
657 for booking_line in booking.lines[1:]:
659 comment = db.comments[i] ##
660 if booking_line == '':
661 booking_lines += [{'acc': None, 'money': None, 'comment': comment}] ##
663 account = booking_line[0]
665 if booking_line[1] is not None:
666 money = f'{booking_line[1]} {booking_line[2]}'
667 booking_lines += [{'acc': booking_line[0], 'money':money, 'comment':comment}] ##
668 elements_to_write += [self.booking_tmpl.render(
670 start=booking.start_line,
672 date=booking.date_string,
673 desc=booking.description,
674 head_comment=db.comments[booking.start_line],
677 booking_lines = booking_lines)]
678 elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != ''] #
679 return '\n'.join(elements_to_write)
681 def add_free(self, db, start=0, end=0, copy=False):
682 tmpl = jinja2.Template(self.add_form_header + """<br />
683 <textarea name="booking" rows=10 cols=80>
684 {% for line in lines %}{{ line }}
687 """ + self.add_form_footer)
688 lines = db.get_lines(start, end)
691 return tmpl.render(action='add_free', start=start, end=end, lines=lines)
693 def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
694 tmpl = jinja2.Template(self.add_form_header + """
695 <input type="submit" name="add_taxes" value="add taxes" />
696 <input type="submit" name="add_taxes2" value="add taxes2" />
697 <input type="submit" name="add_sink" value="add sink" />
699 <input name="date" value="{{date|e}}" size=9 />
700 <input name="description" value="{{desc|e}}" list="descriptions" />
701 <textarea name="line_0_comment" rows=1 cols=20>{{head_comment|e}}</textarea>
702 <input type="submit" name="line_0_add" value="[+]" />
704 {% for line in booking_lines %}
705 <input name="line_{{line.i}}_account" value="{{line.acc|e}}" size=40 list="accounts" />
706 <input type="number" name="line_{{line.i}}_amount" step=0.01 value="{{line.amt}}" size=10 />
707 <input name="line_{{line.i}}_currency" value="{{line.curr|e}}" size=3 list="currencies" />
708 <input type="submit" name="line_{{line.i}}_delete" value="[x]" />
709 <input type="submit" name="line_{{line.i}}_delete_after" value="[XX]" />
710 <input type="submit" name="line_{{line.i}}_add" value="[+]" />
711 <textarea name="line_{{line.i}}_comment" rows=1 cols={% if line.comm_cols %}{{line.comm_cols}}{% else %}20{% endif %}>{{line.comment|e}}</textarea>
714 {% for name, items in datalist_sets.items() %}
715 <datalist id="{{name}}">
716 {% for item in items %}
717 <option value="{{item|e}}">{{item|e}}</option>
721 """ + self.add_form_footer)
722 lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
723 bookings, comments = parse_lines(lines, validate_bookings=False)
724 if len(bookings) > 1:
725 raise PlomException('can only structurally edit single Booking')
726 if add_empty_line is not None:
727 comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
728 booking = bookings[0]
729 booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
730 action = 'add_structured'
731 datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
732 for b in db.bookings:
733 datalist_sets['descriptions'].add(b.description)
734 for account, moneys in b.account_changes.items():
735 datalist_sets['accounts'].add(account)
736 for currency in moneys.keys():
737 datalist_sets['currencies'].add(currency)
739 today = str(datetime.now())[:10]
743 desc = head_comment = ''
744 if len(bookings) == 0:
745 for i in range(1, 3):
746 booking_lines += [{'i': i, 'acc': '', 'amt': '', 'curr': '€', 'comment': ''}]
749 booking = bookings[0]
750 desc = booking.description
751 date = today if copy else booking.date_string
752 head_comment=comments[0]
753 last_line = len(comments)
754 for i in range(1, len(comments)):
755 account = amount = currency = ''
756 if i < len(booking.lines) and booking.lines[i] != '':
757 account = booking.lines[i][0]
758 amount = booking.lines[i][1]
759 currency = booking.lines[i][2]
764 'curr': currency if currency else '€',
765 'comment': comments[i],
766 'comm_cols': len(comments[i])}]
767 content += tmpl.render(
771 head_comment=head_comment,
772 booking_lines=booking_lines,
773 datalist_sets=datalist_sets,
778 def move_up(self, db, start, end):
780 for redir_nth, b in enumerate(db.bookings):
781 if b.start_line >= start:
784 start_at = prev_booking.start_line
785 self.make_move(db, start, end, start_at)
788 def move_down(self, db, start, end):
790 for redir_nth, b in enumerate(db.bookings):
791 if b.start_line > start:
794 start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1
795 self.make_move(db, start, end, start_at)
798 def make_move(self, db, start, end, start_at):
799 lines = db.get_lines(start, end)
800 total_lines = db.real_lines[:start] + db.real_lines[end:]
801 db.write_lines_in_total_lines_at(total_lines, start_at, lines)
804 if __name__ == "__main__":
805 run_server(server_port, LedgerServer)