Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
305 lines (199 loc) · 7.59 KB
/
Copy pathapp.py
File metadata and controls
305 lines (199 loc) · 7.59 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
from flask import Flask, Response, render_template, request, url_for, make_response, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, date as Date
from sqlalchemy import func
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///expenses.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'my-secret-key'
db = SQLAlchemy(app)
class Expense(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(120), nullable=False)
amount = db.Column(db.Float, nullable=False)
category = db.Column(db.String(50), nullable=False)
date = db.Column(db.Date, nullable=False, default=Date.today)
def __init__(self, description, amount, category, expense_date):
self.description = description
self.amount = amount
self.category = category
self.date = expense_date
with app.app_context():
db.create_all()
CATEGORIES = ["Food", "Transport", "Rent", "Utilities", "Health", "Work"]
def parse_date_or_not(s: str):
if not s:
return None
try:
return datetime.strptime(s, "%Y-%m-%d").date()
except ValueError:
return None
@app.route("/")
def index():
start_str = (request.args.get("start") or "").strip()
end_str = (request.args.get("end") or "").strip()
selected_category = (request.args.get("category") or "").strip()
start_date = parse_date_or_not(start_str)
end_date = parse_date_or_not(end_str)
if start_date and end_date and end_date < start_date:
flash("End date cannot be before start date.", "error")
start_date = end_date = None
start_str = end_str = ""
q = Expense.query
expense_date = getattr(Expense, "date")
if start_date:
q = q.filter(expense_date >= start_date)
if end_date:
q = q.filter(expense_date <= end_date)
if selected_category:
q = q.filter(Expense.category == selected_category)
expenses = q.order_by(expense_date.desc(), Expense.id.desc()).all()
total = round(sum(e.amount for e in expenses), 2)
cat_q = db.session.query(Expense.category, func.sum(Expense.amount))
if start_date:
cat_q = cat_q.filter(expense_date >= start_date)
if end_date:
cat_q = cat_q.filter(expense_date <= end_date)
if selected_category:
cat_q = cat_q.filter(Expense.category == selected_category)
cat_rows = cat_q.group_by(Expense.category).all()
cat_labels = [c for c, _ in cat_rows]
cat_values = [round(float(s or 0), 2) for _, s in cat_rows]
day_q = db.session.query(Expense.date, func.sum(Expense.amount))
if start_date:
day_q = day_q.filter(expense_date >= start_date)
if end_date:
day_q = day_q.filter(expense_date <= end_date)
if selected_category:
day_q = day_q.filter(Expense.category == selected_category)
day_rows = (
day_q
.group_by(Expense.date)
.order_by(Expense.date)
.all()
)
day_labels = [d.isoformat() for d, _ in day_rows]
day_values = [round(float(s or 0), 2) for _, s in day_rows]
return render_template(
"index.html",
expenses=expenses,
categories=CATEGORIES,
today=Date.today().isoformat(),
total=total,
start_str=start_str,
end_str=end_str,
selected_category=selected_category,
cat_labels=cat_labels,
cat_values=cat_values,
day_labels=day_labels,
day_values=day_values
)
@app.route("/add", methods=['POST'])
def add():
description = (request.form.get("description") or "").strip()
amount_str = (request.form.get("amount") or "").strip()
category = (request.form.get("category") or "").strip()
date_str = (request.form.get("date") or "").strip()
if not description or not amount_str or not category:
flash("Please fill description, amount, and category", "error")
return redirect(url_for("index"))
try:
amount = float(amount_str)
if amount <= 0:
raise ValueError
except ValueError:
flash("Amount must be a positive number", "error")
return redirect(url_for("index"))
try:
d = datetime.strptime(date_str, "%Y-%m-%d").date() if date_str else Date.today()
except ValueError:
d = Date.today()
e = Expense(description, amount, category, d)
db.session.add(e)
db.session.commit()
flash("Expense added successfully", "success")
return redirect(url_for("index"))
@app.route('/delete/<int:expense_id>', methods=['POST'])
def delete(expense_id):
e = Expense.query.get_or_404(expense_id)
db.session.delete(e)
db.session.commit()
flash("Expense deleted successfully", "success")
return redirect(url_for("index"))
@app.route('/edit/<int:expense_id>', methods=['GET'])
def edit(expense_id):
e = Expense.query.get_or_404(expense_id)
return render_template(
"edit.html",
expense=e,
categories=CATEGORIES,
today=Date.today().isoformat()
)
@app.route('/edit/<int:expense_id>', methods=['POST'])
def edit_post(expense_id):
e = Expense.query.get_or_404(expense_id)
description = (request.form.get("description") or "").strip()
amount_str = (request.form.get("amount") or "").strip()
category = (request.form.get("category") or "").strip()
date_str = (request.form.get("date") or "").strip()
if not description or not amount_str or not category:
flash("Please fill description, amount, and category", "error")
return redirect(url_for("edit", expense_id=expense_id))
try:
amount = float(amount_str)
if amount <= 0:
raise ValueError
except ValueError:
flash("Amount must be a positive number", "error")
return redirect(url_for("edit", expense_id=expense_id))
try:
d = datetime.strptime(date_str, "%Y-%m-%d").date() if date_str else Date.today()
except ValueError:
d = Date.today()
e.description = description
e.amount = amount
e.category = category
e.date = d
db.session.commit()
flash("Expense updated successfully", "success")
return redirect(url_for("index"))
return render_template(
"edit.html",
expense=e,
categories=CATEGORIES,
today=Date.today().isoformat()
)
@app.route("/export.csv")
def export_csv():
start_str = (request.args.get("start") or "").strip()
end_str = (request.args.get("end") or "").strip()
selected_category = (request.args.get("category") or "").strip()
start_date = parse_date_or_not(start_str)
end_date = parse_date_or_not(end_str)
q = Expense.query
expense_date = getattr(Expense, "date")
if start_date:
q = q.filter(expense_date >= start_date)
if end_date:
q = q.filter(expense_date <= end_date)
if selected_category:
q = q.filter(Expense.category == selected_category)
expenses = q.order_by(expense_date, Expense.id).all()
lines = ["date,description,amount,category"]
for e in expenses:
lines.append(
f"{e.date.isoformat()},{e.description},{e.amount:.2f},{e.category}"
)
csv_data = "\n".join(lines)
fname_start = start_str or "all"
fname_end = end_str or "all"
filename = f"expenses_{fname_start}_to_{fname_end}.csv"
return Response (
csv_data,
headers = {
"Content-Type": "text/csv",
"Content-Disposition": f"attachment; filename={filename}"
}
)
if __name__ == "__main__":
app.run(debug=True, port=5000)