-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
239 lines (199 loc) · 8.72 KB
/
app.py
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
from flask import Flask, render_template, request, redirect, url_for, session, flash,jsonify
from datetime import datetime
import sqlite3
from collections import defaultdict
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# SQLite database setup
DATABASE = 'finance_tracker.db'
def init_db():
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT NOT NULL,
password TEXT NOT NULL
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
amount REAL NOT NULL,
category TEXT NOT NULL,
date TEXT NOT NULL,
description TEXT,
payment_method TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
conn.commit()
conn.close()
init_db()
@app.route('/')
def index():
if 'username' in session:
user_id = session['user_id']
username = session['username']
# Fetch transactions from the database
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT * FROM transactions WHERE user_id = ?", (user_id,))
transactions = c.fetchall()
# Compute the sum of transaction amounts for each payment method
total_amount = sum(transaction[2] for transaction in transactions)
total_upi = sum(transaction[2] for transaction in transactions if transaction[6] == 'UPI')
total_cash = sum(transaction[2] for transaction in transactions if transaction[6] == 'Cash')
conn.close()
return render_template('index.html', username=username, total_amount=total_amount, total_upi=total_upi, total_cash=total_cash)
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT id, username FROM users WHERE username = ? AND password = ?", (username, password))
user = c.fetchone()
conn.close()
if user:
session['user_id'] = user[0] # Store user_id in session
session['username'] = user[1] # Store username in session
return redirect(url_for('index'))
else:
flash('Invalid username or password. Please try again.', 'error')
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
phone = request.form['phone']
password = request.form['password']
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT * FROM users WHERE username = ?", (username,))
existing_user = c.fetchone()
if existing_user:
flash('Username already exists. Please choose a different one.', 'error')
else:
c.execute("INSERT INTO users (username, email, phone, password) VALUES (?, ?, ?, ?)",
(username, email, phone, password))
conn.commit()
conn.close()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/transactions')
def transactions():
if 'username' in session:
user_id = session['user_id'] # Assuming you store user_id in session
username = session['username']
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT * FROM transactions WHERE user_id = ?", (user_id,))
transactions = c.fetchall()
conn.close()
return render_template('transaction.html', transactions=transactions, username=username)
else:
return redirect(url_for('login'))
@app.route('/add_transaction', methods=['POST'])
def add_transaction():
if 'username' in session:
user_id = session['user_id'] # Assuming you store user_id in session
date = request.form['date']
category = request.form['category']
amount = request.form['amount']
payment_method = request.form['payment_method']
description = request.form['notes']
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("INSERT INTO transactions (user_id, date, category, amount, payment_method, description) VALUES (?, ?, ?, ?, ?, ?)",
(user_id, date, category, amount, payment_method, description))
conn.commit()
conn.close()
return redirect(url_for('transactions'))
else:
return redirect(url_for('login'))
@app.route('/delete_transaction/<int:transaction_id>', methods=['POST'])
def delete_transaction(transaction_id):
if 'username' in session:
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("DELETE FROM transactions WHERE id = ?", (transaction_id,))
conn.commit()
conn.close()
flash('Transaction deleted successfully.', 'success')
else:
flash('You must be logged in to delete a transaction.', 'error')
return redirect(url_for('transactions'))
@app.route('/daily_spending_data')
def daily_spending_data():
if 'username' in session:
user_id = session['user_id']
# Fetch daily spending data from the database
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT date, SUM(amount) FROM transactions WHERE user_id = ? GROUP BY date", (user_id,))
data = c.fetchall()
conn.close()
# Format data for Chart.js
labels = [row[0] for row in data]
amounts = [row[1] for row in data]
return jsonify({'labels': labels, 'amounts': amounts})
else:
return redirect(url_for('login'))
@app.route('/monthly_spending_data')
def monthly_spending_data():
if 'username' in session:
user_id = session['user_id']
# Fetch monthly spending data from the database
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute("SELECT strftime('%Y-%m', date) AS month, SUM(amount) FROM transactions WHERE user_id = ? GROUP BY month", (user_id,))
data = c.fetchall()
conn.close()
# Format data for Chart.js
labels = [datetime.strptime(row[0], '%Y-%m').strftime('%b %Y') for row in data]
amounts = [row[1] for row in data]
return jsonify({'labels': labels, 'amounts': amounts})
else:
return redirect(url_for('login'))
from flask import session
@app.route('/statistics')
def statistics():
# Retrieve the user's identifier from the session
user_id = session.get('user_id') # Assuming you store user ID in the session
if user_id:
# Fetch data for statistics page for the logged-in user from the database
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
# Fetch total expenses for the logged-in user
c.execute("SELECT SUM(amount) FROM transactions WHERE user_id = ?", (user_id,))
total_expenses_result = c.fetchone()
total_expenses = total_expenses_result[0] if total_expenses_result else 0
# Fetch expense breakdown by category for the logged-in user
c.execute("SELECT category, SUM(amount) FROM transactions WHERE user_id = ? GROUP BY category", (user_id,))
expense_by_category_result = c.fetchall()
expense_by_category = dict(expense_by_category_result) if expense_by_category_result else {}
# Fetch top spending categories for the logged-in user
c.execute("SELECT category, SUM(amount) FROM transactions WHERE user_id = ? GROUP BY category ORDER BY SUM(amount) DESC LIMIT 5", (user_id,))
top_spending_categories_result = c.fetchall()
top_spending_categories = dict(top_spending_categories_result) if top_spending_categories_result else {}
conn.close()
# Render the statistics page template with the fetched data
return render_template('statistics.html', total_expenses=total_expenses, expense_by_category=expense_by_category,
top_spending_categories=top_spending_categories)
else:
# Redirect to login page if user is not logged in
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)