-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
274 lines (212 loc) · 9.63 KB
/
app.py
File metadata and controls
274 lines (212 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
from datetime import datetime
from flask import Flask, render_template, request, redirect, session
from flask_session import Session
from account import account_page
from report import report_page
from export import export_page
from helpers import login_required, connect_db, idr, get_date_now, get_time_now, date_validation, time_validation, id_generator, account_name_list
# Configure app
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Blueprints
app.register_blueprint(account_page)
app.register_blueprint(report_page)
app.register_blueprint(export_page)
# Configure session
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route("/", methods=["GET", "POST"])
def index():
# If user has not been loged in
if session.get("user_id") is None:
return render_template("index.html")
# If user logged in
# Connect to database
con, cur = connect_db()
# User reached route via GET or 'This Month' button was clicked (POST)
if request.method == "GET" or request.form.get('filter_btn') == 'This Month':
year_now = str(datetime.now().year)
month_now = str(datetime.now().month)
date_filter = year_now + '%' + month_now + '%'
label = 'This Month'
# User reached route via POST
else:
# If all time button was clicked
if request.form.get('filter_btn') == 'All Time':
date_filter = '%'
label = 'All Time'
# If all this year button was clicked
elif request.form.get('filter_btn') == 'This Year':
year_now = str(datetime.now().year)
date_filter = year_now + '%'
label = 'This Year'
# If user select the date to filter
elif request.form.get('filter_btn') == 'between':
start_date = request.form.get('start_date')
end_date = request.form.get('end_date')
label = 'Between ' + start_date + ' and ' + end_date
# If user filters by category OR date
elif request.form.get('filter_btn') == 'filter_by_category':
account_name = request.form.get('account_name')
start_date = request.form.get('start_date')
end_date = request.form.get('end_date')
# If user submitted date
if start_date and end_date:
label = f'Filtered by "{account_name}"' + ' between ' + start_date + ' and ' + end_date
# If not
else:
start_date = '0000-00-00'
end_date = '9999-99-99'
label = f'Filtered by "{account_name}"'
# If user using search form
elif request.form.get('search_btn') == 'search_btn':
keyword = request.form.get('search_vield').strip()
label = f'Keyword : "{keyword}"'
# Prevent error 500 for magical reason
else:
date_filter = '0'
label = None
# Query records
if request.form.get('filter_btn') == 'between':
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND date BETWEEN ? AND ? ORDER BY date",
(session["user_id"], start_date, end_date))
elif request.form.get('filter_btn') == 'filter_by_category':
if request.form.get('account_name') == 'All Income':
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND account_category = 'Income' AND date BETWEEN ? AND ? ORDER BY date",
(session["user_id"], start_date, end_date))
elif request.form.get('account_name') == 'All Expense':
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND account_category = 'Expense' AND date BETWEEN ? AND ? ORDER BY date",
(session["user_id"], start_date, end_date))
else:
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND account_name = ? AND date BETWEEN ? AND ? ORDER BY date",
(session["user_id"], request.form.get('account_name'), start_date, end_date))
elif request.form.get('search_btn') == 'search_btn':
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND (account_name LIKE ? OR description LIKE ?) ORDER BY date",
(session["user_id"], f"%{keyword}%", f"%{keyword}%"))
else:
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND date LIKE ? ORDER BY date", (session["user_id"], date_filter))
res = list(res)
# Sum income and expenses
income = 0
expense = 0
for i in res:
if i[3] == 'Income':
income += i[7]
else:
expense += i[7]
# Format amount as IDR
records = []
for i in res:
i = list(i)
i[7] = idr(i[7])
records.append(i)
income = idr(income)
expense = idr(expense)
# List of account_name (category)
income_list, expense_list = account_name_list()
default_selected = "selected"
con.close()
return render_template("home.html", records=records, income=income, expense=expense, label=label, date_now=get_date_now(), time_now=get_time_now(), income_list=income_list, expense_list=expense_list, default_selected=default_selected)
@app.route("/record", methods=["GET", "POST"])
@login_required
def record():
# User reached route via POST
if request.method == 'POST':
# Ensure that user is editing or recording an account
random_id = request.form.get('edit_error_code')
if not random_id == None:
edit_mode = True
else:
edit_mode = False
btnradio = request.form.get('btnradio')
account_name = request.form.get('account_name')
amount = request.form.get('amount')
date = request.form.get('date')
time = request.form.get('time')
description = request.form.get('description')
# Ensure input is a valid value
# Check type (Income or Expense)
if btnradio not in ['Income', 'Expense']:
return render_template("error.html", error="invalid type")
# Check category / account_name
income_list, expense_list = account_name_list(normal_mode=True)
print(income_list)
# Ensure account type is appropriate to account category
if btnradio == 'Income':
if account_name not in income_list:
return render_template("error.html", error="invalid account name")
else:
if account_name not in expense_list:
return render_template("error.html", error="invalid account name")
# Check amount
if float(amount) < 0:
return render_template("error.html", error="invalid amount")
# Check date and time
if date_validation(date) == 1:
return render_template("error.html", error="invalid value")
elif time_validation(time) == 1:
return render_template("error.html", error="invalid value")
# Set max length of description
if len(description) > 50:
return render_template("error.html", error="too long")
# Store to database
con, cur = connect_db()
if edit_mode == False:
cur.execute("INSERT INTO records (user_id,account_name,account_category,date,time,description,amount,random_id) VALUES (?,?,?,?,?,?,?,?)",
(session["user_id"], account_name, btnradio, date, time, description, amount, id_generator()))
else:
cur.execute("UPDATE records SET account_name = ?, account_category = ?, date = ?, time = ?, description = ?, amount = ? WHERE user_id = ? AND random_id = ?",
(account_name, btnradio, date, time, description, amount, session["user_id"], random_id))
con.commit()
con.close()
return redirect("/")
# User reached route via GET
else:
return redirect("/")
@app.route("/delete", methods=["POST"])
@login_required
def delete():
"""Delete record"""
random_id = request.form.get("error_code")
# Delete row from database
con, cur = connect_db()
cur.execute("DELETE FROM records WHERE user_id = ? AND random_id = ?", (session["user_id"], random_id))
con.commit()
con.close()
return redirect("/")
@app.route("/edit", methods=["POST"])
@login_required
def edit():
"""Edit record"""
random_id = request.form.get("edit_error_code")
con, cur = connect_db()
# Query 1 row of record that want to edit
res = cur.execute("SELECT * FROM records WHERE user_id = ? AND random_id = ?", (session["user_id"], random_id))
res = list(res)
# Format amount as IDR
# records is a list of a list ---> [[id, user_id, 'Food', 'Expense', date, ...]]
# record is a list of a data ---> [id, user_id, 'Food', 'Expense', date, ...]
records = []
for i in res:
i = list(i)
i[7] = idr(i[7])
records.append(i)
record = records[0]
# Set default values, selected option, and checked radio button
if record[3] == 'Income':
income_checked = 'checked'
expense_checked = ''
else:
income_checked = ''
expense_checked = 'checked'
income_list, expense_list = account_name_list(record[2])
date_now = record[4]
time_now = record[5]
decs_now = record[6]
amount_now = res[0][7]
con.close()
return render_template("edit.html", record=record, random_id=random_id, amount_now=amount_now, decs_now=decs_now, time_now=time_now, date_now=date_now, expense_checked=expense_checked, income_checked=income_checked, income_list=income_list, expense_list=expense_list)
@app.errorhandler(404)
def page_not_found(error):
return render_template("error.html", error="404 Page not found"), 404