diff --git a/app/app.py b/app/app.py index 705ac08..50c973c 100644 --- a/app/app.py +++ b/app/app.py @@ -17,6 +17,17 @@ import logging +def getBasketAndTotal(sessionBasket): + theBasket = [] + totalPrice = 0 + for key in sessionBasket: + theItem = Item.query.filter_by(id=key).first() + quantity = int(sessionBasket[key]) + thePrice = theItem.price * quantity + totalPrice += thePrice + theBasket.append([theItem, quantity, thePrice]) + + return (theBasket, totalPrice) def populateTables(): """ @@ -267,7 +278,6 @@ def basket(): return flask.redirect(flask.url_for("index")) - theBasket = [] #Otherwise we need to work out the Basket #Get it from the session sessionBasket = flask.session.get("basket", None) @@ -275,14 +285,7 @@ def basket(): flask.flash("No items in basket") return flask.redirect(flask.url_for("index")) - totalPrice = 0 - for key in sessionBasket: - theItem = Item.query.filter_by(id=key).first() - quantity = int(sessionBasket[key]) - thePrice = theItem.price * quantity - totalPrice += thePrice - theBasket.append([theItem, quantity, thePrice]) - + theBasket, totalPrice = getBasketAndTotal(sessionBasket) return flask.render_template("basket.html", basket = theBasket, @@ -299,11 +302,34 @@ def pay(): cost = flask.request.form.get("total") theUser = User.query.filter_by(id = flask.session["user"]).first() - + return flask.render_template("pay.html", cost=cost, user = theUser) +@app.route("/basket/payment/process", methods=["POST"]) +def processPayment(): + if not flask.session["user"]: + flask.flash("You need to be logged in") + return flask.redirect(flask.url_for("index")) + + theUser = User.query.filter_by(id = flask.session["user"]).first() + sessionBasket = flask.session.get("basket", None) + theBasket, _ = getBasketAndTotal(sessionBasket) + + lastItemId = None + for itemInfo in theBasket: + thePurchace = Purchace(userId = theUser.id, itemId = itemInfo[0].id) + db.session.add(thePurchace) + lastItemId = itemInfo[0].id + + db.session.commit() + flask.session.pop("basket") + flask.flash("Payment success. Total card charge: " + flask.request.form.get("total")) + logging.info(flask.request.form.get("total")) + + # redirect user to review page for the last item + return flask.redirect(flask.url_for("reviewItem", userId=theUser.id, itemId=lastItemId)) @app.errorhandler(404) def page_not_found(e): diff --git a/app/templates/pay.html b/app/templates/pay.html index 4dac51f..b5e8ecd 100644 --- a/app/templates/pay.html +++ b/app/templates/pay.html @@ -11,7 +11,7 @@

Payment

-
+
@@ -22,7 +22,7 @@

Payment

- +