home · contact · privacy
Add income tracker.
[misc] / income_progress_bars.py
1 # Python 3 server example
2 from http.server import BaseHTTPRequestHandler, HTTPServer
3 import os
4 import json
5
6 hostName = "localhost"
7 serverPort = 8080
8
9 header = """<html>
10 <meta charset="UTF-8">
11 <style>
12 body {
13   font-family: monospace;
14   background-color: #e0e0ff;
15 }
16 .countable {
17   font-family: monospace;
18   text-align: right;
19 }
20 td, th {
21   border: 1px solid black;
22 }
23 .progressbar {
24   width: 100px;
25   height: 20px;
26   background-color: black;
27   border: none;
28 }
29 .time_progress {
30   position: absolute;
31   height: 20px;
32   background-color: white;
33   width: 2px;
34   border-left: 1px solid black; 
35   border-right: 1px solid black; 
36   z-index: 2;
37 }
38 .progress {
39   height: 20px;
40   z-index: 1;
41 }
42 .surplus {
43   background-color: green;
44 }
45 input {
46   font-family: monospace;
47   text-align: right;
48 }
49 input.rate {
50   text-align: center;
51   width: 4em;
52 }
53 input.minutes {
54   width: 4em;
55 }
56 input.workdays {
57   width: 3em;
58 }
59 input.year_goal {
60   width: 5em;
61 }
62 .diff_goal {
63   position: absolute;
64   width: 7em;
65   text-align: right;
66   color: white;
67   z-index: 3;
68 }
69 table {
70   margin-bottom: 2em;
71 }
72 .input_container {
73   text-align: center;
74 }
75 </style>
76 <body>
77 <table>
78 <tr><th /><th>earned</th><th>progress</th><th>surplus</th></tr >
79 """
80 footer = """</table>
81 <form action="/" method="POST">
82 <table>
83 <tr><th>hourly rate</th><th>worked today</th></tr>
84 <tr><td class="input_container"><input type="number" min="1" class="rate" name="workday_hourly_rate_1" value="%s"/>€</td><td><input type="number" min="0" class="minutes" name="workday_minutes_worked_1" value="%s" step="5" /> minutes</td>
85 <tr><td class="input_container"><input type="number" min="1" class="rate" name="workday_hourly_rate_2" value="%s"/>€</td><td><input type="number" min="0" class="minutes" name="workday_minutes_worked_2" value="%s" step="5" /> minutes</td>
86 <tr><td class="input_container"><input type="number" min="1" class="rate" name="workday_hourly_rate_3" value="%s"/>€</td><td><input type="number" min="0" class="minutes" name="workday_minutes_worked_3" value="%s" step="5" /> minutes</td>
87 <table>
88 <tr><th>yearly income goal</th><td><input type="number" class="year_goal" min="1" name="year_goal" value="%s" />€</td></tr>
89 <tr><th>monthly income goal</th><td class="countable">%.2f€</td></tr>
90 <tr><th>weekly income goal</th><td class="countable">%.2f€</td></tr>
91 <tr><th>workdays per month</th><td class="input_container"><input type="number" class="workdays" min="1" max="28" name="workdays_per_month" value="%s" /></td></tr>
92 <tr><th>workday income goal</th><td class="countable">%.2f€</td></tr>
93 <tr><th>workdays per week</th><td class="countable">%.2f€</td></tr>
94 </table>
95 <input type="submit" name="update" value="update inputs" />
96 <input type="submit" name="finish" value="finish day" />
97 </form>
98 </body
99 </html>"""
100
101 db_default = {
102   "timestamp_year": 0,
103   "timestamp_month": 0,
104   "timestamp_week": 0,
105   "year_income": 0,
106   "month_income": 0,
107   "week_income": 0,
108   "workday_hourly_rate_1": 10,
109   "workday_minutes_worked_1": 0,
110   "workday_hourly_rate_2": 25,
111   "workday_minutes_worked_2": 0,
112   "workday_hourly_rate_3": 50,
113   "workday_minutes_worked_3": 0,
114   "year_goal": 20000,
115   "workdays_per_month": 16 
116 }
117 db_file = "db.json"
118 lock_file = "db.lock"
119 def load_db():
120     if os.path.exists(db_file):
121         with open(db_file, "r") as f:
122             return json.load(f)
123     else:
124         return db_default
125
126 class MyServer(BaseHTTPRequestHandler):
127
128     def do_POST(self):
129         from urllib.parse import parse_qs
130         length = int(self.headers['content-length'])
131         postvars = parse_qs(self.rfile.read(length), keep_blank_values=1)
132         db = load_db()
133         db["workday_minutes_worked_1"] = int(postvars[b'workday_minutes_worked_1'][0].decode()) 
134         db["workday_minutes_worked_2"] = int(postvars[b'workday_minutes_worked_2'][0].decode()) 
135         db["workday_minutes_worked_3"] = int(postvars[b'workday_minutes_worked_3'][0].decode()) 
136         db["workday_hourly_rate_1"] = int(postvars[b'workday_hourly_rate_1'][0].decode()) 
137         db["workday_hourly_rate_2"] = int(postvars[b'workday_hourly_rate_2'][0].decode()) 
138         db["workday_hourly_rate_3"] = int(postvars[b'workday_hourly_rate_3'][0].decode()) 
139         db["year_goal"] = int(postvars[b'year_goal'][0].decode()) 
140         db["workdays_per_month"] = int(postvars[b'workdays_per_month'][0].decode()) 
141         if b'finish' in postvars.keys():
142             day_income = (db["workday_minutes_worked_1"] / 60.0) * db["workday_hourly_rate_1"] 
143             day_income += (db["workday_minutes_worked_2"] / 60.0) * db["workday_hourly_rate_2"] 
144             day_income += (db["workday_minutes_worked_3"] / 60.0) * db["workday_hourly_rate_3"] 
145             db["year_income"] += day_income 
146             db["month_income"] += day_income 
147             db["week_income"] += day_income 
148             db["workday_minutes_worked_1"] = 0
149             db["workday_minutes_worked_2"] = 0
150             db["workday_minutes_worked_3"] = 0
151         if not os.path.exists(lock_file):
152             with open(lock_file, "w+"): pass
153             with open(db_file, "w") as f:
154                 json.dump(db, f)
155             os.remove(lock_file)
156             self.send_response(302)
157             self.send_header('Location', '/')
158             self.end_headers()
159         else:
160             self.send_response(400)
161             self.end_headers()
162             self.wfile.write(bytes("Sorry, lock file!", "utf-8"))
163
164     def do_GET(self):
165         import datetime
166         import calendar 
167         self.send_response(200)
168         self.send_header("Content-type", "text/html")
169         self.end_headers()
170         db = load_db()
171         today = datetime.datetime.now()
172         if not os.path.exists(lock_file):
173             update_db = False
174             if today.year != db["timestamp_year"]:
175                 db["timestamp_year"] = today.year
176                 db["year_income"] = 0
177                 update_db = True 
178             if today.month != db["timestamp_month"]:
179                 db["timestamp_month"] = today.month
180                 db["month_income"] = 0
181                 update_db = True 
182             if today.isocalendar()[1] != db["timestamp_week"]:
183                 db["timestamp_week"] = today.isocalendar()[1]
184                 db["week_income"] = 0
185                 update_db = True 
186             if update_db:
187                 print("Resetting timestamp")
188                 with open(lock_file, "w+"): pass
189                 with open(db_file, "w") as f:
190                     json.dump(db, f)
191                 os.remove(lock_file)
192         else:
193             self.send_response(400)
194             self.end_headers()
195             self.wfile.write(bytes("Sorry, lock file!", "utf-8"))
196             return
197         day_of_year = today.toordinal() - datetime.date(today.year, 1, 1).toordinal() + 1
198         year_length = 365 + calendar.isleap(today.year)
199         workday_goal = db["year_goal"] / 12 / db["workdays_per_month"] 
200         workdays_per_week = (db["workdays_per_month"] * 12) / (year_length / 7) 
201         month_goal = db["year_goal"] / 12 
202         week_goal = db["year_goal"] / (year_length / 7) 
203         def success_color(success):
204             if success < 0.5:
205                 return "red";
206             elif success < 1:
207                 return "yellow";
208             else: 
209                 return "green"
210         def progressbar(title, earned, goal, time_progress=-1):
211             time_progress_indicator = ""
212             success_income = earned / goal 
213             success_income_cut = min(success_income, 1.0) 
214             success_income_bonus = max(success_income - 1.0, 0) 
215             success = success_income + 0
216             diff_goal = earned - goal 
217             if time_progress >= 0:
218                 success = success_income / time_progress
219                 time_progress_indicator = "<div class=\"time_progress\" style=\"margin-left: %spx\"></div>" % int(time_progress * 100) 
220             return "<tr><th>%s</th>" \
221                     "<td class=\"countable\">%.2f€</td>" \
222                     "<td class=\"progressbar\">%s<div class=\"progress\" style=\"background-color: %s; width: %s\"></div></td>" \
223                     "<td class=\"progressbar\"><div class=\"diff_goal\">%.2f€</div><div class=\"progress surplus\" style=\"width: %s\"></div></td></tr>" % (
224                     title, earned, time_progress_indicator, success_color(success), int(success_income_cut * 100), diff_goal, int(success_income_bonus * 100))
225         day_income = (db["workday_minutes_worked_1"] / 60.0) * db["workday_hourly_rate_1"] 
226         day_income += (db["workday_minutes_worked_2"] / 60.0) * db["workday_hourly_rate_2"] 
227         day_income += (db["workday_minutes_worked_3"] / 60.0) * db["workday_hourly_rate_3"] 
228         year_plus = db["year_income"] + day_income 
229         month_plus = db["month_income"] + day_income 
230         week_plus = db["week_income"] + day_income
231         progress_time_year = day_of_year / year_length 
232         progress_time_month = today.day / calendar.monthrange(today.year, today.month)[1] 
233         progress_time_week = today.weekday() / 7 
234         year_line = progressbar("year", year_plus, db["year_goal"], progress_time_year)
235         month_line = progressbar("month", month_plus, month_goal, progress_time_month)
236         week_line = progressbar("week", week_plus, week_goal, progress_time_week)
237         day_line = progressbar("workday", day_income, workday_goal)
238         body = year_line + "\n" + month_line + "\n" + week_line + "\n" + day_line
239         page = header + body + footer % (
240                 db["workday_hourly_rate_1"], db["workday_minutes_worked_1"],
241                 db["workday_hourly_rate_2"], db["workday_minutes_worked_2"],
242                 db["workday_hourly_rate_3"], db["workday_minutes_worked_3"],
243                 db["year_goal"],
244                 month_goal,
245                 week_goal,
246                 db["workdays_per_month"],
247                 workday_goal,
248                 workdays_per_week,
249                 )
250         self.wfile.write(bytes(page, "utf-8"))
251
252 if __name__ == "__main__":        
253     webServer = HTTPServer((hostName, serverPort), MyServer)
254     print("Server started http://%s:%s" % (hostName, serverPort))
255     try:
256         webServer.serve_forever()
257     except KeyboardInterrupt:
258         pass
259     webServer.server_close()
260     print("Server stopped.")