home · contact · privacy
Improve ledger.py.
authorChristian Heller <c.heller@plomlompom.de>
Sun, 12 Nov 2023 02:38:01 +0000 (03:38 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Sun, 12 Nov 2023 02:38:01 +0000 (03:38 +0100)
income_progress_bars.py
ledger.py

index 2093a241ebfde5f9cde3b26436b8709e34cbb77d..bccfc24142896db7d4bf945a8ec37d80f90564b7 100644 (file)
@@ -187,7 +187,7 @@ class MyServer(BaseHTTPRequestHandler):
         db["workday_hourly_rate_3"] = int(postvars['workday_hourly_rate_3'][0])
         db["year_goal"] = int(postvars['year_goal'][0])
         db["workdays_per_month"] = int(postvars['workdays_per_month'][0])
         db["workday_hourly_rate_3"] = int(postvars['workday_hourly_rate_3'][0])
         db["year_goal"] = int(postvars['year_goal'][0])
         db["workdays_per_month"] = int(postvars['workdays_per_month'][0])
-        if b'finish' in postvars.keys():
+        if 'finish' in postvars.keys():
             day_income = (db["workday_minutes_worked_1"] / 60.0) * db["workday_hourly_rate_1"]
             day_income += (db["workday_minutes_worked_2"] / 60.0) * db["workday_hourly_rate_2"]
             day_income += (db["workday_minutes_worked_3"] / 60.0) * db["workday_hourly_rate_3"]
             day_income = (db["workday_minutes_worked_1"] / 60.0) * db["workday_hourly_rate_1"]
             day_income += (db["workday_minutes_worked_2"] / 60.0) * db["workday_hourly_rate_2"]
             day_income += (db["workday_minutes_worked_3"] / 60.0) * db["workday_hourly_rate_3"]
index 02e0273c74f26590e426e7860d72576e0721073f..4a6a071833311493636a7f36b870e32d722dd45d 100755 (executable)
--- a/ledger.py
+++ b/ledger.py
@@ -67,7 +67,6 @@ def bookings_to_account_tree(bookings):
 
 
 def parse_lines(lines, validate_bookings=True):
 
 
 def parse_lines(lines, validate_bookings=True):
-    import datetime
     inside_booking = False
     date_string, description = None, None
     booking_lines = []
     inside_booking = False
     date_string, description = None, None
     booking_lines = []
@@ -332,19 +331,45 @@ class Database:
             f.write(text);
         os.remove(self.lock_file)
 
             f.write(text);
         os.remove(self.lock_file)
 
-    def replace(self, start, end, lines):
-        total_lines = self.real_lines[:start] + lines + self.real_lines[end:]
+    def insert_at_date(self, lines, date):
+        start_at = len(self.real_lines)
+        for b in self.bookings:
+            if b.date_string == date:
+                start_at = b.start_line 
+                break
+            elif b.date_string > date:
+                break
+        if start_at == len(self.real_lines):
+            lines = [''] + lines
+        return self.write_lines_in_total_lines_at(self.real_lines, start_at, lines)
+
+    def update(self, start, end, lines, date):
+        total_lines = self.real_lines[:start] + self.real_lines[end:]
+        n_original_lines = end - start
+        start_at = len(total_lines)
+        for b in self.bookings:
+            if b.date_string == date:
+                if start_at == len(total_lines) or b.start_line == start:
+                    start_at = b.start_line 
+                    if b.start_line > start:
+                        start_at -= n_original_lines
+            elif b.date_string > date:
+                break
+        if start_at == len(total_lines):
+            lines = [''] + lines
+        return self.write_lines_in_total_lines_at(total_lines, start_at, lines)
+
+    def write_lines_in_total_lines_at(self, total_lines, start_at, lines):
+        total_lines = total_lines[:start_at] + lines + [''] + total_lines[start_at:]
+        _, _ = parse_lines(lines)
         text = '\n'.join(total_lines)
         self.write_db(text)
         text = '\n'.join(total_lines)
         self.write_db(text)
-
-    def append(self, lines):
-        text = '\n\n' + '\n'.join(lines) + '\n\n'
-        self.write_db(text, 'a')
+        return start_at
 
     def get_nth_for_booking_of_start_line(self, start_line):
         nth = 0
         for b in self.bookings:
 
     def get_nth_for_booking_of_start_line(self, start_line):
         nth = 0
         for b in self.bookings:
-            if b.start_line == start_line:
+            if b.start_line >= start_line:
                 break
             nth += 1
         return nth
                 break
             nth += 1
         return nth
@@ -494,6 +519,7 @@ input[type=number] { text-align: right; font-family: monospace; }
 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
 / <a href="/add_free?start={{start}}&end={{end}}">free</a>
 | copy:<a href="/copy_structured?start={{start}}&end={{end}}">structured</a>
 / <a href="/copy_free?start={{start}}&end={{end}}">free</a>
+| 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 %}
 | <a href="/balance?stop={{nth+1}}">balance after</a>
 ]</span>
 <table>
 | <a href="/balance?stop={{nth+1}}">balance after</a>
 ]</span>
 <table>
@@ -538,14 +564,27 @@ input[type=number] { text-align: right; font-family: monospace; }
                 _, _ = parse_lines(lines)
             # if saving, process where to and where to redirect after
             if 'save' in postvars.keys():
                 _, _ = parse_lines(lines)
             # if saving, process where to and where to redirect after
             if 'save' in postvars.keys():
+                last_date = str(datetime.datetime.now())[:10]
+                if len(db.bookings) > 0:
+                    last_date = db.bookings[-1].date_string
+                target_date = last_date[:] 
+                first_line_tokens = lines[0].split() if len(lines) > 0 else ''
+                first_token = first_line_tokens[0] if len(first_line_tokens) > 0 else ''
+                try:
+                    datetime.datetime.strptime(first_token, '%Y-%m-%d')
+                    target_date = first_token
+                except ValueError:
+                     pass
                 if start == end == 0:
                 if start == end == 0:
-                    db.append(lines)
-                    redir_url = f'/#last'
+                        start = db.insert_at_date(lines, target_date)
+                        nth = db.get_nth_for_booking_of_start_line(start) 
                 else:
                 else:
-                    db.replace(start, end, lines)
-                    nth = db.get_nth_for_booking_of_start_line(start) 
-                    redir_url = f'/#{nth}'
-                self.send_code_and_headers(301, [('Location', redir_url)])
+                    new_start = db.update(start, end, lines, target_date)
+                    nth = db.get_nth_for_booking_of_start_line(new_start)
+                    if new_start > start: 
+                        nth -= 1 
+                redir_url = f'/#{nth}'
+                self.send_code_and_headers(302, [('Location', redir_url)])
             # otherwise just re-build editing form
             else:
                 if '/add_structured' == parsed_url.path: 
             # otherwise just re-build editing form
             else:
                 if '/add_structured' == parsed_url.path: 
@@ -575,6 +614,14 @@ input[type=number] { text-align: right; font-family: monospace; }
                 page += self.add_free(db, start, end, copy=True)
             elif parsed_url.path == '/copy_structured':
                 page += self.add_structured(db, start, end, copy=True)
                 page += self.add_free(db, start, end, copy=True)
             elif parsed_url.path == '/copy_structured':
                 page += self.add_structured(db, start, end, copy=True)
+            elif parsed_url.path == '/move_up':
+                nth = self.move_up(db, start, end)
+                self.send_code_and_headers(302, [('Location', f'/#{nth}')])
+                return
+            elif parsed_url.path == '/move_down':
+                nth = self.move_down(db, start, end)
+                self.send_code_and_headers(302, [('Location', f'/#{nth}')])
+                return
             else:
                 page += self.ledger_as_html(db)
             page += self.footer
             else:
                 page += self.ledger_as_html(db)
             page += self.footer
@@ -676,6 +723,8 @@ input[type=number] { text-align: right; font-family: monospace; }
         elements_to_write = []
         last_i = i = 0  ##
         for nth, booking in enumerate(db.bookings):
         elements_to_write = []
         last_i = i = 0  ##
         for nth, booking in enumerate(db.bookings):
+            move_up = nth > 0 and db.bookings[nth - 1].date_string == booking.date_string
+            move_down = nth < len(db.bookings) - 1 and db.bookings[nth + 1].date_string == booking.date_string
             booking_end = last_i = booking.start_line + len(booking.lines)
             booking_lines = []
             i = booking.start_line  ##
             booking_end = last_i = booking.start_line + len(booking.lines)
             booking_lines = []
             i = booking.start_line  ##
@@ -698,6 +747,8 @@ input[type=number] { text-align: right; font-family: monospace; }
                 date=booking.date_string,
                 desc=booking.description,
                 head_comment=db.comments[booking.start_line],
                 date=booking.date_string,
                 desc=booking.description,
                 head_comment=db.comments[booking.start_line],
+                move_up=move_up,
+                move_down=move_down,
                 booking_lines = booking_lines)]
         elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']  #
         return '\n'.join(elements_to_write)
                 booking_lines = booking_lines)]
         elements_to_write += [single_c_tmpl.render(c=c) for c in db.comments[last_i:] if c != '']  #
         return '\n'.join(elements_to_write)
@@ -799,6 +850,31 @@ input[type=number] { text-align: right; font-family: monospace; }
                 end=end)
         return content
 
                 end=end)
         return content
 
+    def move_up(self, db, start, end):
+        prev_booking = None
+        for redir_nth, b in enumerate(db.bookings):
+            if b.start_line >= start:
+                break
+            prev_booking = b
+        start_at = prev_booking.start_line 
+        self.make_move(db, start, end, start_at)
+        return redir_nth - 1
+
+    def move_down(self, db, start, end):
+        next_booking = None
+        for redir_nth, b in enumerate(db.bookings):
+            if b.start_line > start:
+                next_booking = b
+                break
+        start_at = next_booking.start_line + len(next_booking.lines) - (end - start) + 1 
+        self.make_move(db, start, end, start_at)
+        return redir_nth
+
+    def make_move(self, db, start, end, start_at):
+        lines = db.get_lines(start, end)
+        total_lines = db.real_lines[:start] + db.real_lines[end:]
+        db.write_lines_in_total_lines_at(total_lines, start_at, lines)
+
 
 if __name__ == "__main__":  
     webServer = HTTPServer((hostName, serverPort), MyServer)
 
 if __name__ == "__main__":  
     webServer = HTTPServer((hostName, serverPort), MyServer)