Example #1
0
def addProduct():
    try:
        if request.method == "POST":
            postAction = request.form["postAction"]
            if postAction == 'cancel':
                return redirect("/admin")
            ProductName = request.form["ProductName"]
            Category = request.form["Category"]
            SubCategory = request.form["SubCategory"]
            Description = request.form["Description"]
            Image = request.form["Image"]
            Price = request.form["Price"]
            Discount = request.form["Discount"]
            if ProductName and Category and SubCategory and Price and Discount:
                DBQuery.addProduct('products', ProductName.title(),
                                   Category.title(), SubCategory.title(),
                                   Description.title(), Image, Price.title(),
                                   Discount.title())
                flash("Product Added Successfully")
                return redirect("/admin")
            else:
                flash('Please fill in all the details')
                return redirect("/add")
        return render_template('add.html')
    except:
        flash('Something went wrong')
        return redirect("/")
Example #2
0
def deleteproduct():
    try:
        productId = request.form["productId"]
        DBQuery.deleteProductUsingId(productId)
        flash("Product Deleted Successfully")
        return redirect("/admin")
    except:
        flash('Something went wrong')
        return redirect("/")
Example #3
0
def adminLogs():
    try:
        login_dictionary = {}
        user_list = []
        order_list = []
        if session.get('superAdmin'):
            login_dictionary["superAdmin"] = "true"
            user_data = DBQuery.getAllUser()
            for userData in user_data:
                userDetails = UserDetails(userData[0], userData[1],
                                          userData[2], userData[3],
                                          userData[4], userData[5],
                                          date.isoformat(userData[6]),
                                          userData[7], userData[8],
                                          userData[9])
                if userDetails.getUserName() != "admin":
                    if userDetails.getOrderedProducts() is None:
                        userDetails.setOrderedProducts([])
                        jsonUserDump = json.dumps(userDetails.__dict__)
                        user_list.append(json.loads(jsonUserDump))
                    else:
                        jsonUserDump = json.dumps(userDetails.__dict__)
                        user_list.append(json.loads(jsonUserDump))
                        # if userDetails.getOrderedProducts() is not None:
                        for value in json.loads(
                                userDetails.getOrderedProducts()):
                            orderDetails = OrderDetails(
                                value['id'], value['productName'],
                                value['category'], value['subCategory'],
                                value['description'], value['image'],
                                value['price'], value['numberOfItems'],
                                value['totalCountOrdered'], value['orderedBy'],
                                value['timeStamp'])
                            jsonDump = json.dumps(orderDetails.__dict__)
                            order_list.append(json.loads(jsonDump))
        elif session.get('logged_in'):
            login_dictionary['logged_in'] = "true"
        # Fetch All the products from Database
        product_data = DBQuery.getAllProducts()
        product_list = []
        for productFromDB in product_data:
            productBrief = ProductBrief(productFromDB[0], productFromDB[1],
                                        productFromDB[2], productFromDB[3],
                                        productFromDB[4], productFromDB[5],
                                        productFromDB[6], productFromDB[7])

            jsonData = json.dumps(productBrief.__dict__)
            product_list.append(json.loads(jsonData))
        login_dictionary['userList'] = user_list
        login_dictionary['orderList'] = order_list
        login_dictionary['productList'] = json.dumps(product_list)
        return render_template('admin.html', data=login_dictionary)
    except Exception as e:
        flash('Something went wrong')
        return redirect("/")
Example #4
0
def createUser():
    try:
        if request.method == "POST":
            postAction = request.form["postAction"]
            if postAction == 'cancel':
                return redirect("/login")
            user_data = DBQuery.getAllUser()
            userName = request.form['UserName']
            email = request.form['Email']
            for userData in user_data:
                userDetails = UserDetails(userData[0], userData[1],
                                          userData[2], userData[3],
                                          userData[4], userData[5],
                                          userData[6], userData[7],
                                          userData[8], userData[9])
                if userName == userDetails.getUserName():
                    flash(
                        'User Name Already Taken, Please try with a different user name'
                    )
                    return redirect("/create")
            gender = request.form['Gender']
            date_of_birth = request.form['DateofBirth']
            name = request.form['FullName']
            phoneNumber = request.form['PhoneNumber']
            password = request.form['Password']
            confirmPassword = request.form['ConfirmPassword']
            walletBalance = 50
            if name and userName and password and email:
                if password == confirmPassword:
                    DBQuery.createUser(name.capitalize(), userName,
                                       hash_password(password), email, gender,
                                       date_of_birth, phoneNumber,
                                       walletBalance)
                    flash('User Account Created Successfully')
                    return redirect("/login")
                else:
                    flash('Passwords don\'t match')
                    return redirect("/create")
            else:
                flash('Please fill in all the details')
                return redirect("/create")
        return render_template("user.html")
    except:
        flash('Something went wrong')
        return redirect("/")
Example #5
0
def updateProduct():
    try:
        productId = request.args.get('id')
        product = []
        # Fetch product from Database using product ID
        if productId is not None:
            productFromDB = DBQuery.getProductUsingId(productId)
            productBrief = ProductBrief(productFromDB[0], productFromDB[1],
                                        productFromDB[2], productFromDB[3],
                                        productFromDB[4], productFromDB[5],
                                        productFromDB[6], productFromDB[7])
            product.append(productBrief.__dict__)
        else:
            if request.method == "POST":
                postAction = request.form["postAction"]
                if postAction == 'cancel':
                    return redirect("/admin")
                if postAction == 'delete':
                    return deleteproduct()
                productId = int(request.form["productId"])
                productName = request.form["productName"]
                category = request.form["category"]
                subCategory = request.form["subCategory"]
                description = request.form["description"]
                image = request.form["image"]
                price = request.form["price"]
                discount = request.form["discount"]
                if productName and category and subCategory and price and discount:
                    DBQuery.updateProduct(productId, productName, category,
                                          subCategory, description, image,
                                          price, discount)
                    flash("product Updated Successfully")
                    return redirect("/admin")
                else:
                    flash('Please fill in all the details')
                    return redirect("/update")
        jsonData = json.dumps(product)
        return render_template('update.html', update=json.loads(jsonData))
    except:
        flash('Something went wrong')
        return redirect("/")
Example #6
0
def forgotPassword():
    try:
        if request.method == "POST":
            userName = request.form["username"]
            newPassword = request.form["NewPassword"]
            password = request.form["ConfirmPassword"]
            postAction = request.form["postAction"]
            if postAction == 'cancel':
                return redirect("/login")
            if postAction == 'submit' and userName and password and newPassword:
                if newPassword == password:
                    DBQuery.updatePassword(userName, hash_password(newPassword));
                    flash("Password Updated Successfully")
                    return redirect("/login")
                else:
                    flash("Passwords don't match")
                    return redirect('/forgotPassword')
            else:
                flash("Enter the details")
        return render_template('forgotPassword.html')
    except:
        flash('Something went wrong')
        return redirect("/")
Example #7
0
def loginPage():
    try:
        if request.method == "POST":
            userName = request.form["username"]
            password = request.form["password"]
            postAction = request.form["postAction"]
            if postAction == 'create':
                return redirect("/create")
            elif postAction == 'home':
                return redirect("/")
            userDetailsFromDB = DBQuery.getUserByUserName(userName)

            if userDetailsFromDB:
                # Based on Database Details, Passing it in UserDetails Class
                userDetails = UserDetails(userDetailsFromDB[0], userDetailsFromDB[1], userDetailsFromDB[2],
                                          userDetailsFromDB[3], userDetailsFromDB[4], userDetailsFromDB[5],
                                          userDetailsFromDB[6], userDetailsFromDB[7], userDetailsFromDB[8],
                                          userDetailsFromDB[9])
                if verify_password(userDetails.getPassword(), password):
                    if userName == 'admin' and password == 'admin':
                        session['superAdmin'] = True
                    else:
                        session['logged_in'] = True
                    session['userName'] = userName
                    session['user'] = [userDetails.getName(), userDetails.getUserName(), userDetails.getEmail(),
                                       userDetails.getGender(), userDetails.getDateOfBirth(),
                                       userDetails.getPhoneNumber(), userDetails.getWalletBalance()]
                    return redirect("/")
                else:
                    flash('Please enter a valid password')
                    return redirect("/login")
            else:
                flash('No Username and Password found in our records, Please try again')
                return redirect("/login")
        return render_template('login.html')
    except:
        flash('Something went wrong')
        return redirect("/")
Example #8
0
def shop():
    try:
        login_dictionary = {}
        data = DBQuery.getAllProducts()
        product_list = []
        if session.get('logged_in'):
            login_dictionary['logged_in'] = "true"
        elif session.get('superAdmin'):
            login_dictionary["superAdmin"] = "true"
        login_dictionary['user'] = session['user']
        # Fetch All the products from Database
        for productFromDB in data:
            productBrief = ProductBrief(productFromDB[0], productFromDB[1],
                                        productFromDB[2], productFromDB[3],
                                        productFromDB[4], productFromDB[5],
                                        productFromDB[6], productFromDB[7])

            jsonData = json.dumps(productBrief.__dict__)
            product_list.append(json.loads(jsonData))
        login_dictionary['productList'] = json.dumps(product_list)
        return render_template('shop.html', data=login_dictionary)
    except:
        flash('Something went wrong')
        return redirect("/")
Example #9
0
def getLocation():
    try:
        location_data = {}
        if request.method == "POST":
            userOrderList = []
            if request.get_json():
                userOrderHistory = DBQuery.getUserByUserName(
                    session.get("userName"))
                ajaxData = json.loads(request.get_json()['data'])
                session['walletBalance'] = request.get_json()['wallet']
                # post  location
                if userOrderHistory[9] is None:
                    userOrderList = []
                else:
                    userOrderList = json.loads(userOrderHistory[9])
                for order in ajaxData:
                    productFromDB = DBQuery.getProductUsingId(order['id'])
                    # print("request.json", productFromDB)
                    orderDetails = OrderDetails(
                        productFromDB[0], productFromDB[1], productFromDB[2],
                        productFromDB[3], productFromDB[4], productFromDB[5],
                        productFromDB[6], productFromDB[7], order['count'],
                        session.get("userName"),
                        datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
                    userOrderList.append(orderDetails.__dict__)
                session['userOderList'] = userOrderList
                # Sending back AJAX Response Call
                return jsonify(flash("Proceed to order"))
            elif request.form:
                location = request.form["location"]
                address = request.form['address']
                postAction = request.form["postAction"]
                if postAction == 'cancel':
                    return redirect("/shop")
                elif postAction == 'submit':
                    URL = "https://geocode.search.hereapi.com/v1/geocode"
                    location = location  #input("Enter the location here: ")  # taking user input
                    api_key = 'oILvnb3yIsakFmQI-UJafpCXmRvN4INE2EZSwgt0R8s'  # Acquire from developer.here.com
                    PARAMS = {'apikey': api_key, 'q': location}

                    # sending get request and saving the response as response object
                    r = requests.get(url=URL, params=PARAMS)
                    data = r.json()

                    # Acquiring the latitude and longitude from JSON
                    latitude = data['items'][0]['position']['lat']
                    longitude = data['items'][0]['position']['lng']
                    location_data['data'] = data
                    location_data['api_key'] = api_key
                    location_data['latitude'] = latitude
                    location_data['longitude'] = longitude
                    location_data['postAction'] = postAction
                    location_data['address'] = address
                    return render_template('location.html', data=location_data)
                elif postAction == 'confirm':
                    userOrderList = session.get('userOderList')
                    DBQuery.updateOrders(json.dumps(userOrderList),
                                         session.get("userName"))
                    DBQuery.walletBalance(session.get('walletBalance'),
                                          session.get('userName'))
                    # userDetailsFromDB = DBQuery.getUserByUserName(session.get('userName'))
                    session['user'][6] = session.get('walletBalance')
                    flash(
                        'Order has been placed successfully! Continue shopping'
                    )
                    return redirect('/shop')
        # Default ballsbridge dublin location data
        location_data = {
            'data': {
                'items': [{
                    'title': 'Ballsbridge, Dublin, Ireland',
                    'id': 'here:cm:namedplace:23217387',
                    'resultType': 'locality',
                    'localityType': 'district',
                    'address': {
                        'label': 'Ballsbridge, Dublin, Ireland',
                        'countryCode': 'IRL',
                        'countryName': 'Ireland',
                        'county': 'County Dublin',
                        'city': 'Dublin',
                        'district': 'Ballsbridge',
                        'postalCode': '4'
                    },
                    'position': {
                        'lat': 53.33061,
                        'lng': -6.23343
                    },
                    'mapView': {
                        'west': -6.25266,
                        'south': 53.31556,
                        'east': -6.20429,
                        'north': 53.3392
                    },
                    'scoring': {
                        'queryScore': 1.0,
                        'fieldScore': {
                            'district': 1.0
                        }
                    }
                }]
            },
            'api_key': 'oILvnb3yIsakFmQI-UJafpCXmRvN4INE2EZSwgt0R8s',
            'latitude': 53.33061,
            'longitude': -6.23343
        }
        return render_template('location.html', data=location_data)
    except Exception as e:
        flash('Something went wrong')
        return redirect("/location")
Example #10
0
    ret = ret.join(DataFrame({'y':y_new}))
    # ugh, have to redefine the dataframe because the mean collapses it to a Series
    return ret.mean().to_frame().transpose()
    #return DataFrame(np.atleast_2d(ret.mean().values),columns=colnames[34:49] + ['y'])

"""

#paired_query = DBQuery(query_player_ID_DB, (query_match_shared_DB,
#                                            query_player_DB1, query_player_DB2,
#                                            query_match_DB1, query_match_DB2),
#                       column_names=colnames)
#paired_query.query_paired_all()
#I need to query individual matches AND keep track if they win or lose!
#print('done!')

paired_query = DBQuery(query_player_ID_fast, query_function_fast,
                       str(sys.argv[1]), fast_colnames)

#player_plot_IDs = list(range(2,10))
player_plot_IDs = [9, 13, 18, 21, 24, 31]
name_dict = paired_query.get_dict_names(player_plot_IDs)
paired_query.query_for_elo()

#ELO!
#elo.calc_matches(paired_query.matches)
#elo.plot(player_plot_IDs, player_names=name_dict)
#pl.show()

#new Elo!
ratingdb_fname = 'ratingdb.sqlite'
try:
    os.remove(ratingdb_fname)
Example #11
0
#hv.extension('bokeh')
import bokeh.palettes as pa
import bokeh.plotting as bp
#import bokeh.charts as bc
#import bkcharts as bk
from bokeh.models import HoverTool, ColumnDataSource
from Database import DBQuery, ratingDB, query_player_ID_fast, \
    query_function_fast, fast_colnames
#import datetime
import pandas as pd
#import plotly.plotly as pt
#import plotly.graph_objs as go
#import cufflinks as cf

playerdb_fname = 'sqlitedb_complete.sqlite'
paired_query = DBQuery(query_player_ID_fast, query_function_fast,
                       playerdb_fname, fast_colnames)

player_plot_IDs = list(range(1, 20))
#player_plot_IDs = [9, 13, 18, 21, 24, 31]
name_dict = paired_query.get_dict_names(player_plot_IDs)
paired_query.query_for_elo()

#current Elo!
ratingdb_fname = 'ratingdb.sqlite'
rating_DB = ratingDB(matches=paired_query.matches,
                     database_name=ratingdb_fname)
#rating_DB.PlotElo(player_plot_IDs, player_names=name_dict)
#pl.show()
#print('Elo done')

#TODO: customize the hover tool!