-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
365 lines (297 loc) · 11.3 KB
/
Copy pathapp.py
File metadata and controls
365 lines (297 loc) · 11.3 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import os
import sys
from datetime import datetime
import click
from flask import Flask, render_template, request, redirect, url_for, flash, abort
from flask_sqlalchemy import SQLAlchemy
WIN = sys.platform.startswith('win')
if WIN: # If it's a Windows system, use three slashes
prefix = 'sqlite:///'
else: # Otherwise, use four slashes
prefix = 'sqlite:////'
app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = 'BW1002'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Disable modification tracking for models
# Initializing the SQLAlchemy extension
db = SQLAlchemy(app)
@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
"""Initialize the database."""
if drop:
db.drop_all()
db.create_all()
click.echo('Database initialized!')
# Define the Base class
class Base(db.Model):
__abstract__ = True
# Setting Base to an abstract class
# no corresponding table is created in the database
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
date = db.Column(db.Date)
amount = db.Column(db.Float)
description = db.Column(db.Text, nullable=True)
# Define the Expense model
class Expense(Base):
pass
# Define the Income model
class Income(Base):
pass
# Define the Goal model
class Goal(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=True)
amount = db.Column(db.Float)
@app.errorhandler(404)
def page_not_found(_):
"""Error handler for 404 page not found."""
return render_template('404.html'), 404
@app.route('/')
def index():
incomes = Income.query.all()
expenses = Expense.query.all()
goal = Goal.query.first()
total_income = sum([income.amount for income in incomes]) if incomes else 0
total_expense = sum([expense.amount for expense in expenses]) if expenses else 0
goal_amount = goal.amount if goal else 0 # Check if goal is None
return render_template('index.html', total_expense=total_expense, total_income=total_income, goal=goal_amount)
@app.route('/all_list')
def all_list():
# Query all records
expenses = Expense.query.all()
incomes = Income.query.all()
return render_template('all_list.html', expenses=expenses, incomes=incomes)
@app.route('/expense_list')
def expense_list():
# Example Query all Expense records
expenses = Expense.query.all()
return render_template('expense_list.html', expenses=expenses)
@app.route('/expense_list/expenses_asc')
def expenses_asc():
expenses = Expense.query.all()
sorted_expenses = sorted(expenses, key=lambda x: x.amount, reverse=False)
return render_template('expense_list.html', expenses=sorted_expenses)
@app.route('/expense_list/expenses_desc')
def expenses_desc():
expenses = Expense.query.all()
sorted_expenses = sorted(expenses, key=lambda x: x.amount, reverse=True)
return render_template('expense_list.html', expenses=sorted_expenses)
def insert(title, amount_0, description, date_0, id_0, exin):
# Check if the title already exists in the database
new_id = 0
if exin == 1:
existing = Expense.query.filter_by(title=title).first()
else:
existing = Income.query.filter_by(title=title).first()
if id_0 == -1:
if existing:
flash('Expense with the same title already exists.')
return -1
# Query the last id in the database
if exin == 1:
last = Expense.query.order_by(Expense.id.desc()).first()
else:
last = Income.query.order_by(Income.id.desc()).first()
# If there is data in the database, get the next id, otherwise set the id to 1
if last:
new_id = last.id + 1
else:
new_id = 1
# Validate amount_0
if amount_0 is None:
flash('Amount cannot be empty.')
return -1
# Try to convert the amount string to a float
try:
amount = float(amount_0)
# Validate that the amount is non-zero and has at most two decimal places
if amount == 0:
raise ValueError
except ValueError:
flash('Amount should be non-zero.')
return -1
# Validate description is a string of appropriate length and format
if (len(description) > 50 or
not isinstance(description, str)):
flash('Description should be an appropriate length string.')
return -1
# Validate the date
if date_0:
try:
date1 = datetime.strptime(date_0, '%Y-%m-%d').date()
# Check that the date is not in the future
current_date = datetime.today().date()
if date1 > current_date:
flash('Date cannot belong to the future.')
return -1
except ValueError:
flash('Invalid date format.')
return -1
else:
date1 = None
if id_0 != -1:
if exin == 1:
expense = Expense.query.get(id_0)
expense.title = title
expense.date = date1
expense.amount = amount
expense.description = description
flash('Expense updated!')
else:
income = Income.query.get(id_0)
income.title = title
income.date = date1
income.amount = amount
income.description = description
flash('Income updated!')
else:
if exin == 1:
tran = Expense(id=new_id, title=title, date=date1, amount=amount, description=description)
flash('Expense added!')
else:
tran = Income(id=new_id, title=title, date=date1, amount=amount, description=description)
flash('Income added!')
# Add the transaction to the database
db.session.add(tran)
db.session.commit()
return 0
@app.route('/expense_add', methods=['GET', 'POST'])
def expense_add():
# Check if method is POST, which means data has been submitted
if request.method == 'POST':
# Retrieve form values
title = request.form.get('title')
date_0 = request.form.get('date')
amount_0 = request.form.get('amount')
description = request.form.get('description')
if insert(title, amount_0, description, date_0, -1, 1) == 0:
return redirect(url_for('expense_list'))
else:
return redirect(url_for('expense_add'))
return render_template('expense_add.html')
@app.route('/expense_edit/<int:expense_id>', methods=['GET', 'POST'])
def expense_edit(expense_id):
expense = Expense.query.get(expense_id)
if not expense:
abort(404)
if request.method == 'POST':
title = request.form.get('title')
date_0 = request.form.get('date')
amount_0 = request.form.get('amount')
description = request.form.get('description')
if insert(title, amount_0, description, date_0, expense_id, 1) == 0:
return redirect(url_for('expense_list'))
else:
return redirect(url_for('expense_edit', expense_id=expense_id))
return render_template('expense_edit.html', expense=expense)
@app.route('/expense_delete/<int:expense_id>', methods=['POST'])
def expense_delete(expense_id):
expense = Expense.query.get(expense_id)
if not expense:
abort(404)
db.session.delete(expense)
db.session.commit()
flash('Transaction deleted!')
return redirect(url_for('expense_list'))
@app.route('/income_list')
def income_list():
# Check all Income records
incomes = Income.query.all()
return render_template('income_list.html', incomes=incomes)
@app.route('/income_list/incomes_asc')
def incomes_asc():
incomes = Income.query.all()
sorted_incomes = sorted(incomes, key=lambda x: x.amount, reverse=False)
return render_template('income_list.html', incomes=sorted_incomes)
@app.route('/income_list/incomes_desc')
def incomes_desc():
incomes = Income.query.all()
sorted_incomes = sorted(incomes, key=lambda x: x.amount, reverse=True)
return render_template('income_list.html', incomes=sorted_incomes)
@app.route('/income_add', methods=['GET', 'POST'])
def income_add():
# Check if method is POST, which means data has been submitted
if request.method == 'POST':
# Retrieve form values
title = request.form.get('title')
date_0 = request.form.get('date')
amount_0 = request.form.get('amount')
description = request.form.get('description')
if insert(title, amount_0, description, date_0, -1, 2) == 0:
return redirect(url_for('income_list'))
else:
return redirect(url_for('income_add'))
return render_template('income_add.html')
@app.route('/income_edit/<int:income_id>', methods=['GET', 'POST'])
def income_edit(income_id):
income = Income.query.get(income_id)
if not income:
abort(404)
if request.method == 'POST':
title = request.form.get('title')
date_0 = request.form.get('date')
amount_0 = request.form.get('amount')
description = request.form.get('description')
if insert(title, amount_0, description, date_0, income_id, 2) == 0:
return redirect(url_for('income_list'))
else:
return redirect(url_for('income_edit', income_id=income_id))
return render_template('income_edit.html', income=income)
@app.route('/income_delete/<int:income_id>', methods=['POST'])
def income_delete(income_id):
income = Income.query.get(income_id)
if not income:
abort(404)
db.session.delete(income)
db.session.commit()
flash('Transaction deleted!')
return redirect(url_for('income_list'))
@app.route('/goal_list')
def goal_list():
# Query all Goal records
goals = Goal.query.all()
return render_template('goal_list.html', goals=goals)
@app.route('/goal_add', methods=['GET', 'POST'])
def goal_add():
goal0 = Goal.query.first()
if request.method == 'POST':
# Retrieve form values
title = request.form.get('title')
amount_0 = request.form.get('amount')
if amount_0 is None or amount_0.strip() == "":
flash('Amount cannot be empty.')
return redirect(url_for('goal_add'))
try:
amount = float(amount_0)
if amount == 0:
raise ValueError
except ValueError:
flash('Amount should be a non-zero number.')
return redirect(url_for('goal_add'))
# Update existing goal or create new goal
goal = Goal.query.first()
if goal:
goal.id = 1
goal.title = title
goal.amount = amount
flash('Saving goal updated!')
else:
new_goal = Goal(id=1, title=title, amount=amount)
db.session.add(new_goal)
flash('Saving goal created!')
# Commit the changes to the database
db.session.commit()
return redirect(url_for('goal_list'))
return render_template('goal_add.html', goal=goal0)
@app.route('/goal_delete/', methods=['POST'])
def goal_delete():
goal = Goal.query.first()
db.session.delete(goal)
db.session.commit()
flash('Saving goal deleted!')
return redirect(url_for('goal_list'))
if __name__ == '__main__':
app.run(debug=True)
# flask initdb --drop