- def balance_as_html(self, db):
- lines = []
- account_tree, account_sums = bookings_to_account_tree(db.bookings)
- def print_subtree(lines, indent, node, subtree, path):
- line = f"{indent}{node}"
- n_tabs = 5 - (len(line) // 8)
- line += n_tabs * "\t"
- if "€" in account_sums[path + node].keys():
- amount = account_sums[path + node]["€"]
- line += f"{amount:9.2f} €\t"
- else:
- line += f"\t\t"
- for currency, amount in account_sums[path + node].items():
- if currency != '€' and amount > 0:
- line += f"{amount:5.2f} {currency}\t"
- lines += [line]
- indent += " "
- for k, v in sorted(subtree.items()):
- print_subtree(lines, indent, k, v, path + node + ":")
- for k, v in sorted(account_tree.items()):
- print_subtree(lines, "", k, v, "")
- content = "\n".join(lines)
- return f"<pre>{content}</pre>"
-
- # def ledger_as_html(self, db):
- # lines = []
- # line_sep = '<br />'
- # for comment in db.comments:
- # line = f' ; {comment}' if comment != '' else ''
- # lines += [line + line_sep]
- # for booking in db.bookings:
- # i = booking.start_line
- # suffix = lines[i]
- # lines[i] = f'<p>{booking.date_string} {booking.description}{suffix}'
- # for booking_line in booking.lines[1:]:
- # i += 1
- # if booking_line == '':
- # continue
- # suffix = f' {lines[i]}' if len(lines[i]) > 0 else ''
- # value = f' {booking_line[1]} {booking_line[2]}' if booking_line[1] else ''
- # lines[i] = f'{booking_line[0]}{value}{suffix}'
- # lines[i] = lines[i][:-len(line_sep)] + f"""</p>
-# edit :
-# <a h ref="/add_structured?start={booking.start_line}&end={i+1}">structured</a>
-# / <a href="/add_free?start={booking.start_line}&end={i+1}">free</a>
-# | co py:
-# <a h ref="/copy_structured?start={booking.start_line}&end={i+1}">structured</a>
-# / <a href="/copy_free?start={booking.start_line}&end={i+1}">free</a>
-# <br />"""
-# return '\n'.join(lines)
-
- def ledger_as_html(self, db):
- lines = []
- for comment in db.comments:
- lines += [f'<span class="comment">{comment}</span>' if comment != '' else '']
- for booking in db.bookings:
- i = booking.start_line
- booking_end = booking.start_line + len(booking.lines)
- lines[i] = f"""{booking.date_string} {booking.description} {lines[i]}
-[edit: <a href="/add_structured?start={booking.start_line}&end={booking_end}">structured</a>
-/ <a href="/add_free?start={booking.start_line}&end={booking_end}">free</a>
-| copy:<a href="/copy_structured?start={booking.start_line}&end={booking_end}">structured</a>
-/ <a href="/copy_free?start={booking.start_line}&end={booking_end}">free</a>]
-<table>"""
- for booking_line in booking.lines[1:]:
- i += 1
- if booking_line == '':
- lines[i] = f'<tr><td><div class="full_line_comment">{lines[i]}</div></td></tr>'
- continue
- comment = f' {lines[i]}' if len(lines[i]) > 0 else ''
- money = ''
- if booking_line[1]:
- money = f'{booking_line[1]} {booking_line[2]}'
- account = booking_line[0]
- lines[i] = f'<tr><td>{booking_line[0]}</td><td class="money">{money}</td><td>{comment}</td></tr>'
- lines[i] = lines[i] + "\n" + '</table>'
- return '\n'.join(lines)
-
- def header_add_form(self, action):
- return f"<form method=\"POST\" action=\"/{action}\">\n"
-
- def footer_add_form(self, start, end, copy):
- if copy:
- start = end = 0
- return f"""
-<input type="hidden" name="start" value={start} />
-<input type="hidden" name="end" value={end} />
-<input type="submit" name="default">
-</form>"""
-
- def add_free(self, db, start=0, end=0, copy=False):
- content = html.escape(''.join(db.get_lines(start, end)))
- return f'{self.header_add_form("add_free")}<textarea name="booking" rows="8" cols="80">{content}</textarea>{self.footer_add_form(start, end, copy)}'
-
- def add_structured(self, db, start=0, end=0, bonus_lines=10, copy=False):
- import datetime
- lines = db.get_lines(start, end)
- bookings, comments = parse_lines(lines)
- if len(bookings) > 1:
- raise HandledException('can only edit single Booking')
- last_line = 0
- def inpu(name, val="", datalist="", input_type='text'):
- val = val if val is not None else ""
- safe_val = html.escape(str(val))
- datalist_string = '' if datalist == '' else f'list="{datalist}"'
- return f'<input type="{input_type}" name="{name}" value="{safe_val}" {datalist_string}/>'
- input_lines = inpu('add_income_tax', 'add income tax', '', 'submit') + '<br />'
- today = str(datetime.datetime.now())[:10]
- if len(bookings) == 0:
- input_lines += f'{inpu("date", today)} {inpu("description", "", "descriptions")} ; {inpu("line_0_comment")}<br />'
- last_line = 1
- else:
- booking = bookings[0]
- last_line = len(comments)
- date_string = today if copy else booking.date_string
- input_lines += f'{inpu("date", date_string)} {inpu("description", booking.description, "descriptions")} ; {inpu("line_0_comment", comments[0])}<br />'
- for i in range(1, len(comments)):
- account = amount = currency = ''
- if i < len(booking.lines) and booking.lines[i] != '':
- account = booking.lines[i][0]
- amount = booking.lines[i][1]
- currency = booking.lines[i][2]
- input_lines += f'{inpu(f"line_{i}_account", account, "accounts")} {inpu(f"line_{i}_amount", amount)} {inpu(f"line_{i}_currency", currency, "currencies")} ; {inpu(f"line_{i}_comment", comments[i])}<br />'
- for j in range(bonus_lines):
- i = j + last_line
- input_lines += f'{inpu(f"line_{i}_account", "", "accounts")} {inpu(f"line_{i}_amount", "", "amounts")} {inpu(f"line_{i}_currency", "", "currencies")} ; {inpu(f"line_{i}_comment")}<br />'
- datalist_sets = {'descriptions': set(), 'accounts': set(), 'currencies': set()}
- for b in db.bookings:
- datalist_sets['descriptions'].add(b.description)
- for account, moneys in b.account_changes.items():
- datalist_sets['accounts'].add(account)
- for currency in moneys.keys():
- datalist_sets['currencies'].add(currency)
- def build_datalist(name):
- datalist = f'<datalist id="{name}">' + "\n"
- for item in datalist_sets[name]:
- safe_item = html.escape(item)
- datalist += f'<option value="{safe_item}">{safe_item}</option>' + "\n"
- return f"{datalist}</datalist>\n"
- datalists = build_datalist('descriptions')
- datalists += build_datalist('accounts')
- datalists += build_datalist('currencies')
- return f'{self.header_add_form("add_structured")}{input_lines}{datalists}{self.footer_add_form(start, end, copy)}'
-
-
-if __name__ == "__main__":
- webServer = HTTPServer((hostName, serverPort), MyServer)
- print(f"Server started http://{hostName}:{serverPort}")
- try:
- webServer.serve_forever()
- except KeyboardInterrupt:
- pass
- webServer.server_close()
- print("Server stopped.")