home · contact · privacy
To ledger.py add structured next to free textarea editing of bookings.
[misc] / ledger.py
1 from http.server import BaseHTTPRequestHandler, HTTPServer
2 import sys
3 import os
4 import html
5 from urllib.parse import parse_qs, urlparse
6 hostName = "localhost"
7 serverPort = 8082
8
9
10 class HandledException(Exception):
11     pass
12
13
14 def handled_error_exit(msg):
15     print(f"ERROR: {msg}")
16     sys.exit(1)
17
18
19 def apply_booking_to_account_balances(account_sums, account, currency, amount):
20     if not account in account_sums:
21         account_sums[account] = {currency: amount}
22     elif not currency in account_sums[account].keys():
23         account_sums[account][currency] = amount
24     else:
25         account_sums[account][currency] += amount
26
27
28 def parse_lines(lines):
29     import datetime
30     import decimal
31     inside_booking = False
32     date_string, description = None, None
33     booking_lines = []
34     start_line = 0
35     bookings = []
36     comments = []
37     lines += [''] # to ensure a booking-ending last line
38     for i, line in enumerate(lines):
39         prefix = f"line {i}"
40         # we start with the case of an utterly empty line
41         comments += [""]
42         stripped_line = line.rstrip()
43         if stripped_line == '':
44             if inside_booking:
45                 # assume we finished a booking, finalize, and commit to DB
46                 if len(booking_lines) < 2:
47                     raise HandledException(f"{prefix} booking ends to early")
48                 booking = Booking(date_string, description, booking_lines, start_line)
49                 bookings += [booking]
50             # expect new booking to follow so re-zeroall booking data
51             inside_booking = False
52             date_string, description = None, None
53             booking_lines = []
54             continue
55         # if non-empty line, first get comment if any, and commit to DB
56         split_by_comment = stripped_line.split(sep=";", maxsplit=1)
57         if len(split_by_comment) == 2:
58             comments[i] = split_by_comment[1]
59         # 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
60         non_comment = split_by_comment[0].rstrip()
61         if non_comment.rstrip() == '':
62              if inside_booking:
63                  booking_lines += ['']
64              continue
65         # if we're starting a booking, parse by first-line pattern
66         if not inside_booking:
67             start_line = i
68             toks = non_comment.split(maxsplit=1)
69             date_string = toks[0]
70             try:
71                 datetime.datetime.strptime(date_string, '%Y-%m-%d')
72             except ValueError:
73                 raise HandledException(f"{prefix} bad date string: {date_string}")
74             try:
75                 description = toks[1]
76             except IndexError:
77                 raise HandledException(f"{prefix} bad description: {description}")
78             inside_booking = True
79             booking_lines += [non_comment]
80             continue
81         # otherwise, read as transfer data
82         toks = non_comment.split()  # ignore specification's allowance of single spaces in names
83         if len(toks) > 3:
84             raise HandledException(f"{prefix} too many booking line tokens: {toks}")
85         amount, currency = None, None
86         account_name = toks[0]
87         if account_name[0] == '[' and account_name[-1] == ']':
88             # ignore specification's differentiation of "virtual" accounts
89             account_name = account_name[1:-1]
90         decimal_chars = ".-0123456789"
91         if len(toks) == 3:
92             i_currency = 1
93             try:
94                 amount = decimal.Decimal(toks[1])
95                 i_currency = 2
96             except decimal.InvalidOperation:
97                 try:
98                     amount = decimal.Decimal(toks[2])
99                 except decimal.InvalidOperation:
100                     raise HandledException(f"{prefix} no decimal number in: {toks[1:]}")
101             currency = toks[i_currency]
102             if currency[0] in decimal_chars:
103                 raise HandledException(f"{prefix} currency starts with int, dot, or minus: {currency}")
104         elif len(toks) == 2:
105             value = toks[1]
106             inside_amount = False
107             inside_currency = False
108             amount_string = ""
109             currency = ""
110             dots_counted = 0
111             for i, c in enumerate(value):
112                 if i == 0:
113                     if c in decimal_chars:
114                         inside_amount = True
115                     else:
116                         inside_currency = True
117                 if inside_currency:
118                     if c in decimal_chars and len(amount_string) == 0:
119                         inside_currency = False
120                         inside_amount = True
121                     else:
122                         currency += c
123                         continue
124                 if inside_amount:
125                     if c not in decimal_chars:
126                         if len(currency) > 0:
127                             raise HandledException(f"{prefix} amount has non-decimal chars: {value}")
128                         inside_currency = True
129                         inside_amount = False
130                         currency += c
131                         continue
132                     if c == '-' and len(amount_string) > 1:
133                         raise HandledException(f"{prefix} amount has non-start '-': {value}")
134                     if c == '.':
135                         if dots_counted > 1:
136                             raise HandledException(f"{prefix} amount has multiple dots: {value}")
137                         dots_counted += 1
138                     amount_string += c
139             if len(amount_string) == 0:
140                 raise HandledException(f"{prefix} amount missing: {value}")
141             if len(currency) == 0:
142                 raise HandledException(f"{prefix} currency missing: {value}")
143             amount = decimal.Decimal(amount_string)
144         booking_lines += [(account_name, amount, currency)]
145     if inside_booking:
146         raise HandledException(f"{prefix} last booking unfinished")
147     return bookings, comments
148
149 class Booking:
150
151     def __init__(self, date_string, description, booking_lines, start_line):
152         self.date_string = date_string
153         self.description = description
154         self.lines = booking_lines
155         self.start_line = start_line
156         self.validate_booking_lines()
157         self.account_changes = self.parse_booking_lines_to_account_changes()
158
159     def validate_booking_lines(self):
160         prefix = f"booking at line {self.start_line}"
161         sums = {}
162         empty_values = 0
163         for line in self.lines[1:]:
164             if line == '':
165                 continue
166             _, amount, currency = line
167             if amount is None:
168                 if empty_values > 0:
169                     raise HandledException(f"{prefix} relates more than one empty value of same currency {currency}")
170                 empty_values += 1
171                 continue
172             if currency not in sums:
173                 sums[currency] = 0
174             sums[currency] += amount
175         if empty_values == 0:
176             for k, v in sums.items():
177                 if v != 0:
178                     raise HandledException(f"{prefix} does not sum up to zero")
179         else:
180             sinkable = False
181             for k, v in sums.items():
182                 if v != 0:
183                     sinkable = True
184             if not sinkable:
185                 raise HandledException(f"{prefix} has empty value that cannot be filled")
186
187     def parse_booking_lines_to_account_changes(self):
188         account_changes = {}
189         debt = {}
190         sink_account = None
191         for line in self.lines[1:]:
192             if line == '':
193                 continue
194             account, amount, currency = line
195             if amount is None:
196                 sink_account = account
197                 continue
198             apply_booking_to_account_balances(account_changes, account, currency, amount)
199             if currency not in debt:
200                 debt[currency] = amount
201             else:
202                 debt[currency] += amount
203         if sink_account:
204             for currency, amount in debt.items():
205                 apply_booking_to_account_balances(account_changes, sink_account, currency, -amount)
206         return account_changes
207
208
209
210 class Database:
211
212     def __init__(self):
213         db_name = "_ledger"
214         self.db_file = db_name + ".json"
215         self.lock_file = db_name+ ".lock"
216         self.bookings = []
217         self.comments = []
218         self.real_lines = []
219         if os.path.exists(self.db_file):
220             with open(self.db_file, "r") as f:
221                 self.real_lines += f.readlines()
222         ret = parse_lines(self.real_lines)
223         self.bookings += ret[0]
224         self.comments += ret[1]
225
226     def replace(self, start, end, lines):
227         import shutil
228         if os.path.exists(self.lock_file):
229             raise HandledException('Sorry, lock file!')
230         if os.path.exists(self.db_file):
231             shutil.copy(self.db_file, self.db_file + ".bak")
232         f = open(self.lock_file, 'w+')
233         f.close()
234         text = ''.join(self.real_lines[:start]) + '\n'.join(lines) + ''.join(self.real_lines[end:])
235         with open(self.db_file, 'w') as f:
236             f.write(text);
237         os.remove(self.lock_file)
238
239     def append(self, lines):
240         import shutil
241         if os.path.exists(self.lock_file):
242             raise HandledException('Sorry, lock file!')
243         if os.path.exists(self.db_file):
244             shutil.copy(self.db_file, self.db_file + ".bak")
245         f = open(self.lock_file, 'w+')
246         f.close()
247         with open(self.db_file, 'a') as f:
248             f.write('\n' + '\n'.join(lines) + '\n');
249         os.remove(self.lock_file)
250
251
252 class MyServer(BaseHTTPRequestHandler):
253     header = '<html><meta charset="UTF-8"><body><a href="/ledger">ledger</a> <a href="/balance">balance</a> <a href="/add_free">add free</a> <a href="/add_structured">add structured</a><hr />'
254     footer = '</body><html>'
255
256     def do_POST(self):
257         length = int(self.headers['content-length'])
258         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
259         parsed_url = urlparse(self.path)
260
261         if '/add_structured' == parsed_url.path:
262             n_lines = int(len(postvars) / 4) 
263             date = postvars['date'][0] 
264             description = postvars['description'][0]
265             start_comment = postvars['line_0_comment'][0]
266             lines = [f'{date} {description} ; {start_comment}']
267             for i in range(1, n_lines):
268                 account = postvars[f'line_{i}_account'][0]
269                 amount = postvars[f'line_{i}_amount'][0]
270                 currency = postvars[f'line_{i}_currency'][0]
271                 comment = postvars[f'line_{i}_comment'][0]
272                 new_main = f'{account} {amount} {currency}'
273                 if '' == new_main.rstrip() == comment.rstrip():
274                     continue
275                 lines += [f'{new_main} ; {comment}'] 
276         elif '/add_free' == parsed_url.path:
277             lines = postvars['booking'][0].splitlines()
278         start = int(postvars['start'][0])
279         end = int(postvars['end'][0])
280         try:
281             _, _ = parse_lines(lines)
282             if start == end == 0:
283                 db.append(lines)
284             else:
285                 db.replace(start, end, lines)
286             self.send_response(200)
287             self.end_headers()
288             page = f'{self.header}Success!{self.footer}'
289             self.wfile.write(bytes(page, "utf-8"))
290         except HandledException as e:
291             self.send_response(400)
292             self.end_headers()
293             page = f'{self.header}{e}{self.footer}'
294             self.wfile.write(bytes(page, "utf-8"))
295
296     def do_GET(self):
297         self.send_response(200)
298         self.send_header("Content-type", "text/html")
299         self.end_headers()
300         db = Database()
301         parsed_url = urlparse(self.path)
302         page = self.header + ''
303         if parsed_url.path == '/balance':
304             page += self.balance_as_html(db)
305         elif parsed_url.path == '/add_free':
306             params = parse_qs(parsed_url.query)
307             start = int(params.get('start', ['0'])[0])
308             end = int(params.get('end', ['0'])[0])
309             page += self.add_free(db, start, end)
310         elif parsed_url.path == '/add_structured':
311             params = parse_qs(parsed_url.query)
312             start = int(params.get('start', ['0'])[0])
313             end = int(params.get('end', ['0'])[0])
314             bonus_lines = int(params.get('bonus_lines', ['0'])[0])
315             page += self.add_structured(db, start, end)
316         else:
317             page += self.ledger_as_html(db)
318         page += self.footer
319         self.wfile.write(bytes(page, "utf-8"))
320
321     def balance_as_html(self, db):
322         account_sums = {}
323         for booking in db.bookings:
324             for account, changes in booking.account_changes.items():
325                 for currency, amount in changes.items():
326                     apply_booking_to_account_balances(account_sums, account, currency, amount)
327         account_tree = {}
328         def collect_branches(account_name, path):
329             node = account_tree
330             path_copy = path[:]
331             while len(path_copy) > 0:
332                 step = path_copy.pop(0)
333                 node = node[step]
334             toks = account_name.split(":", maxsplit=1)
335             parent = toks[0]
336             if parent in node.keys():
337                 child = node[parent]
338             else:
339                 child = {}
340                 node[parent] = child
341             if len(toks) == 2:
342                 k, v = collect_branches(toks[1], path + [parent])
343                 if k not in child.keys():
344                     child[k] = v
345                 else:
346                     child[k].update(v)
347             return parent, child
348         for account_name in sorted(account_sums.keys()):
349             k, v = collect_branches(account_name, [])
350             if k not in account_tree.keys():
351                 account_tree[k] = v
352             else:
353                 account_tree[k].update(v)
354         def collect_totals(parent_path, tree_node):
355             for k, v in tree_node.items():
356                 child_path = parent_path + ":" + k
357                 for currency, amount in collect_totals(child_path, v).items():
358                     apply_booking_to_account_balances(account_sums, parent_path, currency, amount)
359             return account_sums[parent_path]
360         for account_name in account_tree.keys():
361             account_sums[account_name] = collect_totals(account_name, account_tree[account_name])
362         lines = []
363         def print_subtree(lines, indent, node, subtree, path):
364             line = f"{indent}{node}"
365             n_tabs = 5 - (len(line) // 8)
366             line += n_tabs * "\t"
367             if "€" in account_sums[path + node].keys():
368                 amount = account_sums[path + node]["€"]
369                 line += f"{amount:9.2f} €\t"
370             else:
371                 line += f"\t\t"
372             for currency, amount in account_sums[path + node].items():
373                 if currency != '€' and amount > 0:
374                     line += f"{amount:5.2f} {currency}\t"
375             lines += [line]
376             indent += "  "
377             for k, v in sorted(subtree.items()):
378                 print_subtree(lines, indent, k, v, path + node + ":")
379         for k, v in sorted(account_tree.items()):
380             print_subtree(lines, "", k, v, "")
381         content = "\n".join(lines)
382         return f"<pre>{content}</pre>"
383
384     def ledger_as_html(self, db):
385         lines = []
386         line_sep = '<br />'
387         for comment in db.comments:
388             line = f'; {comment}' if comment != '' else ''
389             lines += [line + line_sep]
390         for booking in db.bookings:
391             i = booking.start_line
392             suffix = lines[i]
393             lines[i] = f'<p>{booking.date_string} {booking.description}{suffix}'
394             for booking_line in booking.lines[1:]:
395                 i += 1
396                 if booking_line == '':
397                     continue
398                 suffix = f' {lines[i]}' if len(lines[i]) > 0 else ''
399                 value = f' {booking_line[1]} {booking_line[2]}' if booking_line[1] else ''
400                 lines[i] = f'{booking_line[0]}{value}{suffix}'
401             lines[i] = lines[i][:-len(line_sep)] + f'</p>edit: <a href="/add_structured?start={booking.start_line}&end={i+1}">structured</a> / <a href="/add_free?start={booking.start_line}&end={i+1}">free</a><br />'
402         return '\n'.join(lines)
403
404     def add_free(self, db, start=0, end=0):
405         if start == end == 0:
406             content = ''
407         else:
408             content = html.escape(''.join(db.real_lines[start:end]))
409         return f'<form method="POST" action="/add_free"><textarea name="booking" rows="8" cols="80">{content}</textarea><input type="hidden" name="start" value={start} /><input type="hidden" name="end" value={end} /><input type="submit"></form>'
410
411     def add_structured(self, db, start=0, end=0, bonus_lines=10):
412         if start == end == 0:
413             lines = []
414         else:
415             lines= db.real_lines[start:end]
416         bookings, comments = parse_lines(lines) 
417         if len(bookings) > 1:
418             raise HandledException('can only edit single Booking')
419         input_lines = ''
420         if len(bookings) == 0:
421             input_lines += f'<input name="date" /> <input name="description" /> ; <input name="line_0_comment" /><br />'
422             comments = [''] 
423         else:
424             booking = bookings[0]
425             if booking.start_line != 0:
426                 raise HandledException('need to start on first Booking line')
427             for i, comment in enumerate(comments):
428                 if i == 0:
429                     safe_date_string = html.escape(booking.date_string)
430                     safe_description = html.escape(booking.description)
431                     safe_comment = html.escape(comment)
432                     input_lines += f'<input name="date" value="{safe_date_string}" /> <input name="description" value="{safe_description}" /> ; <input name="line_{i}_comment" value="{safe_comment}" /><br />'
433                     continue
434                 safe_account = safe_amount = safe_currency = ''
435                 safe_comment = html.escape(comment)
436                 if i < len(booking.lines):
437                     main = booking.lines[i]
438                     if main != '':
439                         safe_account = html.escape(main[0]) 
440                         safe_amount = '' if main[1] is None else html.escape(str(main[1]))
441                         safe_currency = '' if main[2] is None else html.escape(main[2]) 
442                 input_lines += f'<input name="line_{i}_account" value="{safe_account}" /> <input name="line_{i}_amount" value="{safe_amount}" /> <input name="line_{i}_currency" value="{safe_currency}" /> ; <input name="line_{i}_comment" value="{safe_comment}" /><br />'
443         for j in range(bonus_lines):
444             i = j + len(comments)
445             input_lines += f'<input name="line_{i}_account"/> <input name="line_{i}_amount"/> <input name="line_{i}_currency"/> ; <input name="line_{i}_comment" /><br />'
446         return f'<form method="POST" action="/add_structured">{input_lines}<input type="hidden" name="start" value={start} /><input type="hidden" name="end" value={end} /><input type="submit"></form>'
447
448
449 db = Database()
450 if __name__ == "__main__":     
451     webServer = HTTPServer((hostName, serverPort), MyServer)
452     print(f"Server started http://{hostName}:{serverPort}")
453     try:
454         webServer.serve_forever()
455     except KeyboardInterrupt:
456         pass
457     webServer.server_close()
458     print("Server stopped.")