def history():
    """Show history of transactions"""

    modaltext = modal()
    current_buyer_orders = Order.query.filter_by(buyerid=current_user.id).all()
    # print(current_buyer_orders)
    history = []

    for orders in current_buyer_orders:
        produc = Product.query.filter_by(prodid=orders.productid).first()
        produc_path = produc.prodPath
        produc_path = produc_path.split(",")[0]
        produc_price = produc.prodPrice
        produc_name = produc.prodName

        if ((orders.unitprice - 5) % produc_price) == 0:
            #means delivery
            deliverymethod = "Delivery"
            #should return an integer
            qty = (orders.unitprice - 5) / produc_price

        else:
            deliverymethod = "Collection"
            qty = orders.unitprice / produc_price

        history.append([
            produc_path, produc_name, deliverymethod, qty, produc_price,
            orders.unitprice, orders.order_date
        ])

    return render_template("transact/userorderhistory.html",
                           modal=modaltext,
                           history=history), 200
Example #2
0
def login():
    """Log user in
    Converted to Bakery as at 6 Oct 5:09pm """

    modaltext = modal()

    # return user to where he was at before.
    if current_user.is_authenticated:
        return redirect("/")

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        username = request.form.get("username")
        password = request.form.get("password")

        # Ensure username was submitted
        if not username:
            flash("Please provide a username")
            return redirect(url_for("auth_bp.login"))

        # Ensure password was submitted
        if not password:
            flash("Please provide a password.")
            return redirect(url_for("auth_bp.login"))

        # Get the object associated with the user.
        alluser = User.query.filter_by(username = username).all()
        if len(alluser) == 1:
            user = alluser[0]
            if user.check_password(password = password):
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                session["user"] = user.username
                session["usertype"] = user.usertype
                login_user(user, remember = True, duration = timedelta(minutes = 15))
                return redirect(url_for("index"))
            else:
                flash("Wrong credentials.")
                return render_template("authentication/login.html"), 400
        elif len(alluser) == 0:
            flash("Wrong credentials.")
            return render_template("authentication/login.html"), 400
        else:
            print("Database is bugged. Please check")
    else:
        return render_template("authentication/login.html", modal = modaltext), 200
def browse():
    """Browse cakes on sale"""

    modaltext = modal()
    listofproducts = Product.query.all()

    for i in range(len(listofproducts)):
        listofproducts[i].prodPath = listofproducts[i].prodPath.split(",")
        listofproducts[i].prodPrice = str(
            format(listofproducts[i].prodPrice, '.2f'))

    # db.session.rollback()
    return render_template("transact/browse.html",
                           modal=modaltext,
                           listofproducts=listofproducts,
                           mycount=range(len(listofproducts)))
def productlist(product):
    ''' this should be a pass-through function '''
    ''' pass the results of this function to another one'''
    ''' try it with a form'''
    modaltext = modal()

    #https://stackoverflow.com/questions/8398726/using-the-post-method-with-html-anchor-tags
    if request.method == "POST":
        path = request.form.get("name")
        sell_id = path[6]
        productnum = path[14]
        # print("Path is {}, Sell id is {}, productnum is {}".format(path, sell_id, productnum))

        # Default, by prod id, i.e. by time. since we have seller id, we can just use prod id
        targetproduct = Product.query.filter_by(sell_id=sell_id).all()
        finalproduct = targetproduct[int(productnum) - 1]
        # print(finalproduct.prodid)
        # print(finalproduct.prodPath)

        return render_template("transact/product.html",
                               modal=modaltext,
                               finalproduct=finalproduct), 200
    else:
        # From main page gallery
        prodname = request.args.get("prodid")

        # From main page gallery
        if prodname:
            # print(prodname)
            prodname = prodname.split("/")[-1].strip("?").replace("-", " ")
            # print(prodname)

        # From new posting, with no element id identifier
        else:
            prodname = request.url.split("/")[-1]
            prodname = prodname.replace("-", " ")

        finalproduct = Product.query.filter_by(prodName=prodname).first()
        # print(finalproduct)
        # print(request.method)
        # print(request.headers.get("Referer"))
        return render_template("transact/product.html",
                               modal=modaltext,
                               finalproduct=finalproduct), 200
def cart():

    modaltext = modal()
    user_to_add = User.query.filter_by(id=current_user.id).first()
    items = user_to_add.cart_details

    today = date.today()
    totalproducts = []
    todelete = []
    for item in items.split(" "):
        if item == "" or item == " ":
            continue
        else:
            # print("item is {}".format(item))
            prodid = item.split("-")[0]
            delivery = item.split("-")[1]
            qty = item.split("-")[2]
            orderdate = "-".join(item.split("-")[3:])

            delta = today - datetime.strptime(orderdate, "%Y-%m-%d").date()
            # print(delta)

            if delta.days > 15:
                todelete.append(item)
                continue
            else:
                totalproducts.append([
                    Product.query.filter_by(prodid=prodid).first(), delivery,
                    qty, orderdate
                ])

    for i in todelete:
        user_to_add.cart_details = items.replace(i, "", 1)
        # totalproducts.append(Product.query.filter_by(prodid = prodid).first())
        # print("prodid = {}, delivery = {}, sellerid = {}, orderdate = {}".format(prodid, delivery, sellerid, orderdate))
    db.session.commit()

    return render_template("transact/cart.html",
                           totalproducts=totalproducts,
                           modal=modaltext), 200
Example #6
0
def register():
    """Register user
    Converted to bakery @ 6 Oct 4:45pm """

    modaltext = modal()

    if request.method == "POST":

        username = request.form.get("username")
        password = request.form.get("password")
        confirmpass = request.form.get("confirmation")
        usertype = request.form.get("buysell")

        existing_user = User.query.filter_by(username=username).first()
        if username and password and password == confirmpass and len(password) > 8 and confirmpass:
            # creates an instance of the User class and adds it into the database (session only).
            if not existing_user:
                new_user = User(username = username, password = password, usertype = usertype)
                new_user.authenticated = True
                db.session.add(new_user)

                logged = User.query.filter_by(username = username).first()
                session["user"] = new_user.username
                session["usertype"] = new_user.usertype
                login_user(new_user, remember = True, duration = timedelta(minutes = 15))

                db.session.commit()
                flash("Welcome, {}".format(username))
                return redirect(url_for("index"))
            else:
                flash('A user already exists with that username.')
                return render_template("authentication/register.html", modal = modaltext), 400
        else:

            flash("Please ensure you have filled in all the details, and adhered to the guidelines.", 400)
            return render_template("authentication/register.html", modal = modaltext), 400
    else:
        return render_template("authentication/register.html", modal = modaltext), 200
def post():

    modaltext = modal()
    # User submits a listing of cakes. Each listing should have 3 pictures of cakes to show, with specified sizes.
    if request.method == "POST":

        price = request.form.get("postprice")
        name = request.form.get("posttitle")
        description = request.form.get("postdescription")

        # Server side validation in case Javascript is disabled.
        if not price or not name or not description:
            flash("Incomplete form. Did you forget to key in the details?")
            return redirect(request.url)

        try:
            price = float(price)
        except:
            flash("Please input numbers and decimals only.")
            return redirect(request.url)

        # Check for uploaded files.
        if 'file' not in request.files:
            flash('No files found')
            return redirect(request.url)

        file1 = request.files.getlist('file')

        if file1[0].filename == '':
            flash(
                "No selected file for 1st or 2nd image. Please check and submit again."
            )
            return redirect(request.url)

        sell_id = current_user.id
        prodpath = ''
        count = len(Product.query.filter_by(sell_id=sell_id).all()) + 1
        for i in range(len(file1)):
            if file1[i].filename == '':
                continue
            if allowed_file(file1[i].filename):
                filename = secure_filename(file1[i].filename)
                newfilename = "seller" + str(sell_id) + "product" + str(
                    count) + "img" + str(i + 1) + "." + str(
                        filename.split(".", 1)[1])
                file1[i].save(
                    os.path.join(app.config['UPLOAD_FOLDER'], newfilename))
                prodpath += newfilename
            else:
                flash(
                    "Please only upload pictures. Accepted formats are: .png, .jpeg, .jpg"
                )
                return redirect(request.url)

            prodpath += ','

        newproduct = Product(sell_id=sell_id,
                             prodName=name,
                             prodDesc=description,
                             prodPrice=price,
                             prodPath=prodpath,
                             listdate=date.today())
        db.session.add(newproduct)
        db.session.commit()

        message = "Listing Uploaded! Click <a href = " + "'/product/" + name.replace(
            " ", "-"
        ) + "'" + "class = 'alert-link'>here</a>" + " to see your new listing!"
        flash(Markup(message))
        return redirect("/")
    else:
        return render_template("transact/post.html", modal=modaltext)
def payment():
    modaltext = modal()
    if request.method == "GET":
        #To make payment
        area = [
            "North", "South", "East", "West", "North-East", "North-West",
            "South-East", "South-West"
        ]
        with open('static/paymentmodal.txt', 'r') as file:
            paymentmodalwords = file.read().split("/n")
            paymentmodalwords = [i.strip("/n") for i in paymentmodalwords]

        user_to_add = User.query.filter_by(id=current_user.id).first()
        items = user_to_add.cart_details
        totalproducts = []
        valuepayment = ""
        for item in items.split(" "):
            # print(item)
            if item == "" or item == " ":
                continue
            else:
                # print("item is {}".format(item))
                prodid = item.split("-")[0]
                delivery = item.split("-")[1]
                delivery = delivery[0].upper() + delivery[1:]
                qty = item.split("-")[2]
                orderdate = "-".join(item.split("-")[3:])

                totalproducts.append([
                    Product.query.filter_by(prodid=prodid).first(), delivery,
                    qty, orderdate
                ])

                valuepayment += "prodid" + str(prodid) + delivery + " "

        # print(totalproducts)
        return render_template("transact/payment.html",
                               modal=modaltext,
                               area=area,
                               paymentmodalwords=paymentmodalwords,
                               totalproducts=totalproducts,
                               valuepayment=valuepayment)

    else:
        #Delete form details, but still process order form.

        paymentitems = request.form.get("payproddetails")
        allform = request.form.to_dict(flat=False)
        del allform

        buy_id = current_user.id

        price = 0
        for item in paymentitems.split(" ")[0:-1]:
            produc = Product.query.filter_by(prodid=item[6]).first()
            producid = produc.prodid
            price = produc.prodPrice
            if item[7:] == "Deliver":
                price += 5

            seller = produc.sell_id
            neworder = Order(buyerid=buy_id,
                             sellerid=seller,
                             unitprice=price,
                             productid=producid,
                             order_date=date.today())
            db.session.add(neworder)

        currentuser = User.query.filter_by(id=current_user.id).first()

        #Paid for and so cart items will be deleted.
        currentuser.cart_details = ""
        db.session.commit()
        flash(
            "Thank you for making the purchase. Your order will arrive instantaneously!"
        )
        return redirect("/")

    return render_template("transact/cart.html"), 404