- 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 = []
- 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"""<p>{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></p>'
- 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="save" value="save!">
-</form>"""
-
- def textarea(self, name, lines, min_rows=1, min_cols=20):
- safe_content = html.escape(''.join(lines))
- n_rows = max(min_rows, len(lines))
- n_cols = min_cols
- for line in lines:
- n_cols = len(line) if len(line) > n_cols else n_cols
- return f'<textarea name="{name}" rows={n_rows} cols={n_cols}>{safe_content}</textarea>'
-
- def add_free(self, db, start=0, end=0, copy=False):
- lines = db.get_lines(start, end)
- return f'{self.header_add_form("add_free")}{self.textarea("booking",lines,10,80)}{self.footer_add_form(start, end, copy)}'
-
- def add_structured(self, db, start=0, end=0, copy=False, temp_lines=[], add_empty_line=None):
- import datetime
- lines = temp_lines if len(''.join(temp_lines)) > 0 else db.get_lines(start, end)
- bookings, comments = parse_lines(lines)
- if len(bookings) > 1:
- raise HandledException('can only edit single Booking')
- if add_empty_line is not None:
- comments = comments[:add_empty_line+1] + [''] + comments[add_empty_line+1:]
- booking = bookings[0]
- booking.lines = booking.lines[:add_empty_line+1] + [''] + booking.lines[add_empty_line+1:]
- def inpu(name, val="", datalist="", input_type='text', size=-1):
- val = val if val is not None else ""
- safe_val = html.escape(str(val))
- datalist_string = '' if datalist == '' else f'list="{datalist}"'
- number_step = '' if input_type != 'number' else ' step=0.01'
- size_string = '' if size < 0 else f' size={size}'
- return f'<input type="{input_type}"{number_step} name="{name}"{size_string} value="{safe_val}" {datalist_string}/>'
- input_lines = inpu('check', 'check', '', 'submit') +\
- inpu('revert', 'revert', '', 'submit') +\
- inpu('add_taxes', 'add taxes', '', 'submit') +\
- '<br />'
- today = str(datetime.datetime.now())[:10]
- if len(bookings) == 0:
- input_lines += f'{inpu("date", today, size=9)} {inpu("description", "", "descriptions")} ; {inpu("line_0_comment")} {inpu(f"line_0_add", "[+]", "", "submit")}<br />'
- for i in range(1, 3):
- input_lines += f'{inpu(f"line_{i}_account", "", "accounts", size=40)} {inpu(f"line_{i}_amount", "", "", "number", size=10)} {inpu(f"line_{i}_currency", "", "currencies", size=3)} ; {self.textarea(f"line_{i}_comment", "")} {inpu(f"line_{i}_delete", "[x]", "", "submit")} {inpu(f"line_{i}_add", "[+]", "", "submit")}<br />'
- else:
- booking = bookings[0]
- last_line = len(comments)
- date_string = today if copy else booking.date_string
- input_lines += f'{inpu("date", date_string, size=9)} {inpu("description", booking.description, "descriptions")} ; {self.textarea("line_0_comment", [comments[0]])} {inpu(f"line_0_add", "[+]", "", "submit")}<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", size=40)} {inpu(f"line_{i}_amount", amount, "", "number", size=10)} {inpu(f"line_{i}_currency", currency, "currencies", size=3)} ; {self.textarea(f"line_{i}_comment", [comments[i]])} {inpu(f"line_{i}_delete", "[x]", "", "submit")} {inpu(f"line_{i}_add", "[+]", "", "submit")}<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.")