-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
434 lines (347 loc) · 16.4 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#the brain
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for, jsonify
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime
from helpers import apology, login_required
# Configure application
app = Flask(__name__)
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finale_refined.db")
@app.route("/")
def home():
"""Render home page"""
return render_template("home.html")
#registration {step 1}
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("user_name"):
return apology("must provide username", 400)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 400)
# Ensure password and confirmation match
elif not request.form.get("password") == request.form.get("confirmation"):
return apology("passwords do not match", 400)
# hash the password and insert a new user in the database
if not request.form.get("preferences") and request.form.get("user_type") == "receive":
return apology("Receiver should select at least one item type", 400)
hash = generate_password_hash(request.form.get("password"))
new_user_id = db.execute("INSERT INTO User (user_name, name, password, address_line1, address_line2, city, pincode, state, country, user_type, email_id) VALUES(:user_name, :name, :hash, :address_line1, :address_line2, :city, :pincode, :state, :country, :user_type, :email_id)",
user_name=request.form.get("user_name"),
name=request.form.get("name"),
hash=hash,
address_line1=request.form.get("address_line1"),
address_line2=request.form.get("address_line2"),
city=request.form.get("city"),
pincode=request.form.get("pincode"),
state=request.form.get("state"),
country=request.form.get("country"),
user_type=request.form.get("user_type"),
email_id=request.form.get("email"))
# unique username constraint violated?
if not new_user_id:
return apology("username taken", 400)
if request.form.get("preferences"):
preferences = map(int, request.form.get("preferences").split(','))
for item_id in preferences:
db.execute("INSERT INTO Preference (user_id, item_id, create_date) VALUES(:user_id, :item_id, :create_date)",
user_id=new_user_id,
item_id=item_id,
create_date=datetime.now())
# Remember which user has logged in
session["user_id"] = new_user_id
session["user_name"] = request.form.get("user_name")
session["user_type"] = request.form.get("user_type")
# Display a flash message
flash("Registered!")
# Redirect user to home page
return redirect(url_for("home"))
else:
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("user_name"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
rows = db.execute("SELECT * FROM User WHERE user_name = :user_name",
user_name=request.form.get("user_name"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["password"], request.form.get("password")):
return apology("invalid username and/or password")
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
session["user_name"] = rows[0]["user_name"]
session["user_type"] = rows[0]["user_type"]
# Redirect user to home page
if session["user_type"] == "donate":
return redirect(url_for("donations",user_id=session["user_id"]))
else:
return redirect(url_for("view_open_donations_receiver",user_id=session["user_id"] ))
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect(url_for("home"))
@app.route("/users/<int:user_id>/donations", methods=["GET", "POST"])
@login_required
def donations(user_id):
"""Donate"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
itemtype_id = request.form.get("itemtype_id")
title = request.form.get("title")
note = request.form.get("note")
intended_receipients = map(int, request.form.get("intended_receipients").split(','))
# Ensure item was submitted
if not request.form.get("itemtype_id"):
return apology("must provide item type", 403)
# Ensure description was submitted
elif not request.form.get("title"):
return apology("must provide title", 403)
# Ensure recipient was selected <NOT WORKING>
elif not request.form.get("intended_receipients"):
return apology("must select atleast one receipient", 403)
# Query database for username
donation_id = db.execute("INSERT INTO Donation (user_id, title, note, item_id, status, create_date, modified_date) VALUES(:user_id, :title, :note, :item_id, :status, :create_date, :modified_date)",
user_id=user_id,
title=title,
note=note,
item_id=itemtype_id,
status="Open",
create_date=datetime.now(),
modified_date=datetime.now()
)
for rank,receipient_id in enumerate(intended_receipients):
db.execute("INSERT INTO IntendedReceipients (donation_id, rank, status, user_id, create_date, modified_date) VALUES(:donation_id, :rank, :status, :user_id,:create_date, :modified_date)",
donation_id=donation_id,
rank=rank,
status="Close" if rank > 0 else "Open",
user_id=receipient_id,
create_date=datetime.now(),
modified_date=datetime.now()
)
flash("Donated!")
return redirect(url_for("home"))
else:
return render_template("donations.html")
@app.route("/timeline_give")
@login_required
def timeline_give():
"""Show history of Donation"""
donations = db.execute(
"""SELECT
u.name AS user_name,
d.id AS donation_id,
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
d.modified_date AS donation_last_modified_date,
d.status AS donation_status,it.title AS item_type
FROM
user AS u inner JOIN donation d on d.user_id = u.id
And d.status IN ('Complete', 'Rejected')AND u.id=:user_id
inner JOIN ItemType AS it on it.id=d.item_id
ORDER BY d.modified_date DESC""",user_id=session["user_id"])
return render_template("timeline_give.html", donations=donations)
@app.route("/users/<int:user_id>/new-donations")
@login_required
def view_open_donations_receiver(user_id):
"""Show Open donations to receivers"""
# Place View Donations SQL Here
donations = db.execute("""
SELECT
u.name AS user_name,
u.address_line1 AS address_line1,
u.city AS user_city,
u.pincode AS user_pincode,
d.id AS donation_id,
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
d.modified_date AS donation_modified_date,
d.status AS donation_status,
ir.status AS recipient_status,
ir.modified_date AS recipient_modified_date_date
FROM
user AS u inner JOIN donation d on d.user_id = u.id And d.status='Open'
left outer join IntendedReceipients as ir on d.id = ir.donation_id AND ir.status='Open'
inner join user as iru on ir.user_id = iru.id AND iru.id=:user_id
ORDER BY d.modified_date DESC""",
user_id=user_id)
print(donations)
return render_template("view_open_donations_receiver.html", donations=donations)
@app.route("/users/<int:user_id>/pending-donations")
@login_required
def view_pending_donations_receiver(user_id):
"""Show Pending donations to receivers"""
donations = db.execute("""
SELECT
u.name AS user_name,
u.address_line1 AS address_line1,
u.city AS user_city,
u.pincode AS user_pincode,
d.id AS donation_id,
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
d.modified_date AS donation_modified_date,
d.status AS donation_status,
ir.status AS recipient_status,
ir.modified_date AS recipient_modified_date_date
FROM
user AS u inner JOIN donation d on d.user_id = u.id And d.status='Open'
left outer join IntendedReceipients as ir on d.id = ir.donation_id AND ir.status='Accept'
inner join user as iru on ir.user_id = iru.id AND iru.id=:user_id
ORDER BY d.modified_date DESC""",
user_id=user_id)
return render_template("view_pending_donations_receiver.html", donations=donations)
@app.route("/users/<int:user_id>/complete-donations")
@login_required
def view_complete_donations_receiver(user_id):
"""Show Complete donations to receivers"""
donations = db.execute("""
SELECT
u.name AS user_name,
u.address_line1 AS address_line1,
u.city AS user_city,
u.pincode AS user_pincode,
d.id AS donation_id,
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
d.modified_date AS donation_modified_date,
d.status AS donation_status,
ir.status AS recipient_status,
ir.modified_date AS recipient_modified_date_date
FROM
user AS u inner JOIN donation d on d.user_id = u.id And d.status='Complete'
left outer join IntendedReceipients as ir on d.id = ir.donation_id AND ir.status='Accept'
inner join user as iru on ir.user_id = iru.id AND iru.id=:user_id
ORDER BY d.modified_date DESC""",
user_id=user_id)
return render_template("view_complete_donations_receiver.html", donations=donations)
@app.route("/users/<int:user_id>/donations/<int:donation_id>/accept", methods=["POST"])
@login_required
def accept_donation(user_id, donation_id):
# NGO accept
if request.method == "POST":
db.execute("UPDATE IntendedReceipients SET modified_date=current_timestamp, status='Accept' WHERE id=(SELECT id FROM IntendedReceipients WHERE status='Open' and donation_id= :donation_id and user_id = :user_id)", user_id=user_id, donation_id=donation_id)
return jsonify({"message":"Accept Succesful."})
@app.route("/users/<int:user_id>/donations/<int:donation_id>/complete", methods=["POST"])
@login_required
def complete_donation(user_id, donation_id):
# NGO receives and marks donation complete
if request.method == "POST":
db.execute("UPDATE Donation SET modified_date=current_timestamp, status='Complete' WHERE id= :donation_id", donation_id=donation_id)
return jsonify({"message":"Complete Succesful."})
@app.route("/users/<int:user_id>/donations/<int:donation_id>/reject", methods=["POST"])
@login_required
def reject_donation(user_id, donation_id):
# NGO reject
if request.method == "POST":
result_set = db.execute("SELECT id, rank FROM IntendedReceipients WHERE donation_id=:donation_id and user_id = :user_id", user_id=user_id, donation_id=donation_id)
if not result_set:
#TODO
pass
intended_receipient_id, rank = result_set[0].values()
db.execute("UPDATE IntendedReceipients SET modified_date=current_timestamp, status='Reject' WHERE id= :intended_receipient_id",intended_receipient_id=intended_receipient_id)
rank = rank+1
update_row_count = db.execute("""
UPDATE IntendedReceipients set modified_date=current_timestamp, status='Open' WHERE id = (
SELECT id FROM IntendedReceipients WHERE rank=:new_rank AND donation_id=:donation_id and status='Close')
""", new_rank=rank, donation_id=donation_id)
if not update_row_count:
db.execute("""
UPDATE Donation set modified_date=current_timestamp, status='Abort' WHERE id=:donation_id
""", donation_id=donation_id)
return jsonify({"message":"Reject with Abort Succesful."})
# db.execute("UPDATE Donation SET status='Accept' WHERE id= :donation_id", donation_id=donation_id)
return jsonify({"message":"Reject Succesful."})
@app.route("/users/<int:user_id>/active-donations")
@login_required
def active_donations(user_id):
if request.method == "GET":
donations = db.execute("""
SELECT
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
ir.status AS recipient_status,
ir.modified_date AS recipient_modified_date,
iru.name AS recipient
FROM
user AS u inner JOIN donation d on d.user_id = u.id And d.status='Open' AND u.id=:user_id
left outer join IntendedReceipients as ir on d.id = ir.donation_id AND ir.status IN ('Open', 'Accept')
inner join user as iru on ir.user_id = iru.id
ORDER BY ir.modified_date DESC
""", user_id=user_id)
return render_template("view_active_donations.html", donations=donations)
@app.route("/users/<int:user_id>/donations-history")
@login_required
def donations_history(user_id):
if request.method == "GET":
donations = db.execute("""
SELECT
d.title AS donation_title,
d.note AS donation_instructions,
d.create_date AS donation_create_date,
d.modified_date AS donation_modified_date,
d.status AS donation_status,
ir.status AS recipient_status,
ir.modified_date AS recipient_modified_date,
iru.name AS recipient
FROM
user AS u inner JOIN donation d on d.user_id = u.id And d.status IN ('Complete','Abort') AND u.id=:user_id
left outer join IntendedReceipients as ir on d.id = ir.donation_id AND ir.status IN ('Accept')
left outer join user as iru on ir.user_id = iru.id
ORDER BY d.modified_date DESC
""", user_id=user_id)
return render_template("view_donations_history.html", donations=donations)
@app.route("/item-types")
def item_types():
"""
Return Item Types
"""
item_types = db.execute("SELECT * FROM ItemType WHERE is_active= :is_active", is_active='t')
return jsonify(item_types)
@app.route("/receipients")
def receipients_by_type():
item_type = request.args.get('itemType')
receipients = db.execute(
"SELECT * FROM User as user INNER JOIN Preference as preference on user.id=preference.user_id and preference.item_id in (SELECT id FROM ItemType WHERE title = :title)", title = item_type
)
return jsonify(receipients)