Exemplo n.º 1
0
def updateCustomer(request):
    Authorizer.authorizeCustomer(request)

    postVars = request.POST
    validKeys = ['lastName', 'firstName', 'address', 'city', 'state', 'zipCode', 'telephone', 'email', 'creditCardNumber']
    acceptedValues = []
    queryAppend = []

    query = "UPDATE Customers SET "

    for key in validKeys:
        if key in postVars:
            queryAppend.append(key + " = %s")
            acceptedValues.append(postVars[key])

    acceptedValues.append(request.matchdict['id'])
    query = query + ', '.join(queryAppend) + " WHERE ID = %s"

    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor()

        cursor.execute(query, tuple(acceptedValues))

        cursor.close()

        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err))
    Authorizer.refreshSession(request)
    raise exc.HTTPOk()
Exemplo n.º 2
0
def apiGetMailingList(request):
    Authorizer.authorizeEmployee(request)
    mailingListID = request.matchdict["id"]
    mailingLists = {}
    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        query = "SELECT * FROM MailingLists where id = %s"
        cursor.execute(query, tuple([str(mailingListID)]))

        for row in cursor:
            mailingList = {"id": row["id"], "createdBy": row["createdBy"], "name": row["name"]}

        query = "SELECT C.* from MailingListsMappings LEFT JOIN (SELECT id, firstName, lastName, email FROM Customers) as C ON C.id = MailingListsMappings.customerID and MailingListsMappings.listID = %s"

        cursor.execute(query, tuple([str(mailingList["id"])]))
        customers = []
        for row in cursor:
            customers.append({"id": row["id"], "name": row["firstName"] + " " + row["lastName"], "email": row["email"]})
            mailingList["customers"] = customers

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return mailingLists
Exemplo n.º 3
0
def employeeDashboard(request):
	Authorizer.authorizeEmployee(request)
	values = {
		'currentUser': None,
	}
	if('currentUser' in request.session):
		values["currentUser"] = request.session['currentUser']
	return values
Exemplo n.º 4
0
def managerDashboard(request):
	Authorizer.authorizeManager(request)
	values = {
		'currentUser': None,
	}
	if('currentUser' in request.session):
		values["currentUser"] = request.session['currentUser']
	return values
Exemplo n.º 5
0
def sold(request):
    Authorizer.authorizeEmployee(request)

    postVars = request.POST
    requiredKeys = ['bidID', 'customerID', 'auctionID', 'itemID']
    for key in requiredKeys:
        if(key not in postVars):
            raise exc.HTTPBadRequest()
    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor(dictionary=True)

        query = """
        INSERT INTO Wins (BidID, Time, CustomerID, AuctionID)
        VALUES (%s,NOW(),%s, %s);
        """

        cursor.execute(query, tuple([str(postVars['bidID']), str(postVars['customerID']), str(postVars['auctionID'])]))

        query = """
        UPDATE Items
        SET CopiesSold = CopiesSold + 1, Stock=Stock-1
        WHERE ID= %s
        """

        cursor.execute(query, tuple([str(postVars['itemID'])]))

        query = """
        UPDATE Customers
        SET ItemsSold=ItemsSold+1
        WHERE ID = (SELECT SellerID
            FROM Auctions
            WHERE ID = %s);
        """
        cursor.execute(query, tuple([str(postVars['auctionID'])]))

        query = """
        UPDATE Customers
        SET ItemsPurchased=ItemsPurchased+1
        WHERE ID = %s

            """
        cursor.execute(query, tuple([str(postVars['customerID'])]))

        cursor.close()
        cnx.commit()
        cnx.close()

    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    raise exc.HTTPOk()
Exemplo n.º 6
0
def salesReport(request):
    Authorizer.authorizeManager(request)

    getVars = request.GET

    validKeys = ["month", "year", "itemID", "customerID", "itemType"]

    acceptedValues = []
    queryAppend = []
    report = []

    query = "SELECT * FROM Sales_Report WHERE "

    for key in validKeys:
        if key in getVars:
            if key == "month":
                queryAppend.append("MONTH(time) = %s")
                acceptedValues.append(getVars[key])
            elif key == "year":
                queryAppend.append("YEAR(time) = %s")
                acceptedValues.append(getVars[key])
            else:
                queryAppend.append(key + " = %s")
                acceptedValues.append(getVars[key])

    query = query + " AND ".join(queryAppend)

    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        cursor.execute(query, tuple(acceptedValues))

        for row in cursor:
            reportValues = {}
            for key in row:
                if isinstance(row[key], datetime):
                    reportValues[key] = row[key].isoformat()
                elif isinstance(row[key], Decimal):
                    reportValues[key] = str(row[key])
                else:
                    reportValues[key] = row[key]
            report.append(reportValues)

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return report
Exemplo n.º 7
0
def addAuction(request):
    Authorizer.authorizeCustomer(request)

    requiredKeys = ["itemID", "sellerID", "closingTime", "openingBid", "reserve", "increment"]
    postVars = request.POST
    acceptedKeys = []

    for key in requiredKeys:
        if key in postVars:
            acceptedKeys.append(postVars[key])
        else:
            print(key)
            raise exc.HTTPBadRequest()

    # print(postVars['password'])
    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        employees = []

        query = "SELECT id FROM Employees WHERE type = 1"

        cursor.execute(query)

        for row in cursor:
            employees.append(row["id"])

        acceptedKeys.append(employees[randint(0, len(employees) - 1)])

        query = "INSERT INTO Auctions(itemID, sellerID, openingTime, closingTime, openingBid, reserve, increment, employeeID)\
                 VALUES (%s,  %s,  NOW(),  %s,  %s,  %s,  %s, %s);"

        cursor.execute(query, tuple(acceptedKeys))

        cursor.close()

        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        cursor.close()
        cnx.close()
        return Response("Something went wrong: {}".format(err))

    raise exc.HTTPOk()
Exemplo n.º 8
0
def addEmployee(request):
    Authorizer.authorizeManager(request)

    requiredKeys = ['ssn', 'lastName', 'firstName', 'address', 'city', 'state', 'zipCode', 'telephone', 'startDate', 'hourlyRate', 'type']
    requiredUserKeys = ['username','password']
    postVars = request.POST
    acceptedKeys = []
    accepteduserKeys = []

    for key in requiredKeys:
        if(key in postVars):
            acceptedKeys.append(postVars[key])
        else:
            print(key)
            raise exc.HTTPBadRequest()

    for key in requiredUserKeys:
        if(key not in postVars):
            raise exc.HTTPBadRequest()

    salt = 'qwerty'
    postVars['password'] = crypt.crypt(postVars['password'], salt)

    query = ("INSERT INTO Employees(ssn, lastName, firstName, address, city, state, zipCode, telephone, startDate, hourlyRate, type)\
             VALUES (%s,  %s,  %s,  %s,  %s,  %s,  %s, %s, %s, %s, %s);")

    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor()

        cursor.execute(query, tuple(acceptedKeys))

        query = ("INSERT INTO Users(username, password, type, id) VALUES (%s, %s, 1, LAST_INSERT_ID())")

        cursor.execute(query, tuple([postVars['username'], postVars['password']]))

        cursor.close()

        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), 500)

    raise exc.HTTPOk()
Exemplo n.º 9
0
def deleteCustomer(request):
    Authorizer.authorizeEmployee(request)

    query = "DELETE FROM Customers WHERE id= %s"

    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor()

        cursor.execute(query, tuple([request.matchdict['id']]))

        cursor.close()

        cnx.commit()
        cnx.close()

    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err))

    raise exc.HTTPOk()
Exemplo n.º 10
0
def getEmployee(request):
    Authorizer.authorizeManager(request)

    employeeID = request.matchdict['id']

    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor(dictionary=True)

        query = ("SELECT * FROM Employees WHERE id = %s")

        cursor.execute(query, tuple([str(employeeID)]))

        employee = {}
        for employee in cursor:
            employee = {
                'type': employee['type'],
                'id': employee['id'],
                'name': employee['firstName'] + " " + employee['lastName'],
                'firstName' : employee['firstName'],
                'lastName' : employee['lastName'],
                'address': employee['address'],
                'city': employee['city'],
                'state': employee['state'],
                'zipCode': employee['zipCode'],
                'telephone': employee['telephone'],
                'startDate': employee['startDate'].isoformat(),
                'hourlyRate': str(employee['hourlyRate']),
            }

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    if(len(employee) == 0):
        raise exc.HTTPNoContent()

    return employee
Exemplo n.º 11
0
def allCustomers(request):
    Authorizer.authorizeEmployee(request)

    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor(dictionary=True)

        query = ("SELECT * FROM Customers")

        cursor.execute(query)

        items = []
        for customer in cursor:
            items.append({
                'id': customer['id'],
                'name': customer['firstName'] + customer['lastName'],
                'firstName': customer['firstName'],
                'lastName': customer['lastName'],
                'address': customer['address'],
                'city': customer['city'],
                'state': customer['state'],
                'zipCode': customer['zipCode'],
                'telephone': customer['telephone'],
                'email': customer['email'],
                'creditCardNumber': customer['creditCardNumber'],
                'itemsSold': customer['itemsSold'],
                'itemsPurchased': customer['itemsPurchased'],
                'rating': str(customer['rating'])
            })

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    if(len(items) == 0):
        raise exc.HTTPNoContent()

    return items
Exemplo n.º 12
0
def apiAddMailingList(request):
    Authorizer.authorizeEmployee(request)
    postVars = request.POST
    print(postVars)
    if "name" not in postVars:
        raise exc.HTTPBadRequest()

    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        query = "INSERT INTO MailingLists(name, createdBy) VALUES(%s, %s)"
        cursor.execute(query, tuple([postVars["name"], Authorizer.getCurrentUser(request)["id"]]))

        if "customers[]" in postVars:
            # postVars.getall('customers[]')
            query = "SELECT LAST_INSERT_ID() as id"
            cursor.execute(query)
            mailingListID = cursor.fetchone()["id"]
            print(mailingListID)
            for customerID in postVars.getall("customers[]"):
                print(customerID)
                query = "SELECT COUNT(*) as count FROM Customers where id = %s"
                cursor.execute(query, tuple([str(customerID)]))
                count = cursor.fetchone()["count"]
                if count != 0:
                    query = "INSERT INTO MailingListsMappings(listID, customerID) VALUES (%s, %s)"
                    cursor.execute(query, tuple([mailingListID, customerID]))
                else:
                    raise exc.HTTPBadRequest()

        cursor.close()
        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    raise exc.HTTPOk()
Exemplo n.º 13
0
def mailingList(request):
    Authorizer.authorizeEmployee(request)

    query = """SELECT email, concat(lastName, ' ', firstName) AS name FROM Customers"""

    mailingList = []

    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        cursor.execute(query)

        for row in cursor:
            customer = {}
            for key in row:
                customer[key] = row[key]
            mailingList.append(customer)

    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return mailingList
Exemplo n.º 14
0
def itemSuggestions(request):
    Authorizer.authorizeCustomer(request)

    session = request.session
    customerID = None
    if(Authorizer.getCurrentUserType(request) == 0):
        customerID = Authorizer.getCurrentUser(request)['id']
    else:
        if('customerID' in request.GET):
            customerID = request.GET['customerID']
        else:
            raise exc.HTTPBadRequest()

    query = """
        SELECT * FROM Items WHERE type IN (
            SELECT type FROM Items WHERE id IN (
                SELECT itemID FROM Searches WHERE customerID = %s
                )
            )
        AND Items.name NOT IN (
            SELECT name FROM Items WHERE id IN (
                SELECT itemID FROM Auctions WHERE id IN (
                    SELECT auctionID FROM Bids WHERE customerID = %s
                    )
                )
            )
        LIMIT 5
        """

    suggestedItems = []
    try:
        cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='305')
        cursor = cnx.cursor(dictionary=True)

        cursor.execute(query, tuple([str(customerID), str(customerID)]))

        for row in cursor:
            item = {}
            for key in row:
                if(isinstance(row[key], datetime)):
                    item[key] = row[key].isoformat()
                elif(isinstance(row[key], Decimal)):
                    item[key] = str(row[key])
                else:
                    item[key] = row[key]
            suggestedItems.append(item)

        for item in suggestedItems:
            query = ("SELECT url FROM ItemsImages WHERE itemID = %s")
            cursor.execute(query, tuple([str(item['id'])]))
            urls = []
            for row in cursor:
                urls.append(row['url'])
            item['images'] = urls

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return suggestedItems
Exemplo n.º 15
0
def revenueReport(request):
    Authorizer.authorizeManager(request)

    getVars = request.GET

    query = "SELECT ItemName, SUM(Amount) AS revenue, COUNT(Amount) AS copiesSold FROM Sales_Report WHERE "
    secondQuery = "SELECT ItemName, SUM(Amount) AS revenue, COUNT(Amount) AS copiesSold FROM Sales_Report WHERE MONTH(time) = MONTH(NOW()) AND YEAR(time) = YEAR(NOW()) AND "
    value = None
    if "employeeID" in getVars and "customerID" not in getVars and "itemID" not in getVars:
        query = query + "monitorID = %s GROUP BY ItemName"
        secondQuery = secondQuery + "monitorID = %s GROUP BY ItemName"
        value = getVars["employeeID"]
    elif "employeeID" not in getVars and "customerID" in getVars and "itemID" not in getVars:
        query = query + "customerID = %s GROUP BY ItemName"
        secondQuery = secondQuery + "customerID = %s GROUP BY ItemName"
        value = getVars["customerID"]
    elif "employeeID" not in getVars and "customerID" not in getVars and "itemID" in getVars:
        query = query + "itemID = %s"
        secondQuery = secondQuery + "itemID = %s"
        value = getVars["itemID"]
    else:
        raise exc.HTTPBadRequest()

    report = {}
    totalReport = []
    monthReport = []
    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        cursor.execute(query, tuple([str(value)]))

        for row in cursor:
            totalReportValues = {}
            for key in row:
                if isinstance(row[key], datetime):
                    totalReportValues[key] = row[key].isoformat()
                elif isinstance(row[key], Decimal):
                    totalReportValues[key] = str(row[key])
                else:
                    totalReportValues[key] = row[key]
            totalReport.append(totalReportValues)
        report["total"] = totalReport

        cursor.execute(secondQuery, tuple([str(value)]))

        for row in cursor:
            monthReportValues = {}
            for key in row:
                if isinstance(row[key], datetime):
                    monthReportValues[key] = row[key].isoformat()
                elif isinstance(row[key], Decimal):
                    monthReportValues[key] = str(row[key])
                else:
                    monthReportValues[key] = row[key]
            monthReport.append(monthReportValues)
        report["month"] = monthReport

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return report
Exemplo n.º 16
0
def apiRevenueStats(request):
    Authorizer.authorizeManager(request)

    getVars = request.GET

    query1 = "SELECT SUM(Amount) AS revenue, COUNT(Amount) AS copiesSold, Items.* FROM Sales_Report LEFT JOIN Items on Items.id = Sales_Report.itemID GROUP BY itemID ORDER BY revenue DESC LIMIT 1"
    query2 = "SELECT SUM(Amount) AS revenue, COUNT(Amount) AS copiesSold, Customers.* FROM Sales_Report LEFT JOIN Customers on Customers.id = Sales_Report.sellerID GROUP BY customerID ORDER BY revenue DESC LIMIT 1;"
    query3 = "SELECT SUM(Amount) AS revenue, COUNT(Amount) AS copiesSold, Employees.* FROM Sales_Report LEFT JOIN Employees on Employees.id = Sales_Report.monitorID GROUP BY monitorID ORDER BY revenue DESC LIMIT 1;"

    stats = {}
    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        cursor.execute(query1)
        row = cursor.fetchone()
        stat = {}
        for key in row:
            if isinstance(row[key], datetime):
                stat[key] = row[key].isoformat()
            elif isinstance(row[key], Decimal):
                stat[key] = str(row[key])
            else:
                stat[key] = row[key]

        stats["item"] = stat

        query1 = "SELECT * FROM ItemsImages WHERE itemID = %s"
        cursor.execute(query1, tuple([str(stat["id"])]))
        images = []
        for row in cursor:
            images.append(row["url"])
        stats["item"]["images"] = images

        cursor.execute(query2)
        row = cursor.fetchone()
        stat = {}
        for key in row:
            if isinstance(row[key], datetime):
                stat[key] = row[key].isoformat()
            elif isinstance(row[key], Decimal):
                stat[key] = str(row[key])
            else:
                stat[key] = row[key]

        stats["customer"] = stat

        cursor.execute(query3)
        row = cursor.fetchone()
        stat = {}
        for key in row:
            if isinstance(row[key], datetime):
                stat[key] = row[key].isoformat()
            if isinstance(row[key], date):
                stat[key] = row[key].isoformat()
            elif isinstance(row[key], Decimal):
                stat[key] = str(row[key])
            else:
                stat[key] = row[key]

        stats["employee"] = stat

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return stats
Exemplo n.º 17
0
def apiAuctionWin(request):
    Authorizer.authorizeEmployee(request)
    auctionID = request.matchdict["id"]

    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        query = "SELECT * from Auctions where id = %s"
        cursor.execute(query, tuple([str(auctionID)]))
        auction = cursor.fetchone()

        if auction["finished"] == 1:
            cursor.close()
            cnx.close()
            raise exc.HTTPBadRequest()
        elif auction["closingTime"] > datetime.now():
            cursor.close()
            cnx.close()
            raise exc.HTTPBadRequest()

        query = "UPDATE Auctions SET finished=1 WHERE id = %s"
        cursor.execute(query, tuple([str(auctionID)]))

        # query = "SELECT COUNT(*) as count, amount, id, customerID FROM Bids where auctionID = 1 ORDER BY amount DESC LIMIT 1"
        query = "SELECT COUNT(*) as count FROM Bids where auctionID = %s"
        cursor.execute(query, tuple([str(auctionID)]))
        bid = cursor.fetchone()
        if bid["count"] == 0:
            cursor.close()
            cnx.commit()
            cnx.close()
            raise exc.HTTPOk()

        query = "SELECT amount, id, customerID FROM Bids WHERE auctionID = %s ORDER BY amount DESC LIMIT 1"
        cursor.execute(query, tuple([str(auctionID)]))
        bid = cursor.fetchone()

        if bid["amount"] < auction["reserve"]:
            cursor.close()
            cnx.commit()
            cnx.close()
            raise exc.HTTPOk()

        query = "INSERT INTO Wins (bidID, time, customerID, auctionID)\
                    VALUES (%s, NOW(), %s, %s);"
        cursor.execute(query, tuple([bid["id"], bid["customerID"], auction["id"]]))

        query = "UPDATE Items\
                 SET CopiesSold = CopiesSold + 1, Stock=Stock-1\
                 WHERE ID=%s"
        cursor.execute(query, tuple([str(auction["itemID"])]))
        print("itemUpdated")
        query = "UPDATE Customers\
                SET ItemsSold=ItemsSold+1\
                WHERE ID = %s"
        cursor.execute(query, tuple([str(auction["sellerID"])]))
        print("seller")
        query = "UPDATE Customers\
                SET ItemsPurchased=ItemsPurchased+1\
                WHERE ID = %s"
        cursor.execute(query, tuple([str(bid["customerID"])]))
        print("customer")
        cursor.close()
        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        cursor.close()
        cnx.close()
        return Response("Something went wrong: {}".format(err), status=500)

    raise exc.HTTPOk()
Exemplo n.º 18
0
def apiAuctionsUnapproved(request):
    Authorizer.authorizeEmployee(request)
    auctions = []
    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True)

        query = "SELECT * FROM Auctions where closingTime<NOW() AND finished=0"

        cursor.execute(query)

        for row in cursor:
            auctionInfo = {}
            for key in row:
                if isinstance(row[key], datetime):
                    auctionInfo[key] = row[key].isoformat()
                elif isinstance(row[key], Decimal):
                    auctionInfo[key] = str(row[key])
                else:
                    auctionInfo[key] = row[key]
            auctions.append(auctionInfo)

        for auction in auctions:
            print(auction)

            query = "SELECT * FROM Customers where id = %s"
            cursor.execute(query, tuple([str(auction["sellerID"])]))
            customer = cursor.fetchone()
            print("hii")
            auction["sellerName"] = customer["firstName"] + " " + customer["lastName"]

            query = "SELECT name FROM Items where id=%s"
            cursor.execute(query, tuple([str(auction["itemID"])]))
            item = cursor.fetchone()
            print("hiii")
            auction["itemName"] = item["name"]

            query = "SELECT url from ItemsImages where itemID=%s"
            cursor.execute(query, tuple([str(auction["itemID"])]))
            # print('hi')
            imageArray = []
            for row in cursor:
                imageArray.append(row["url"])
            auction["itemImage"] = imageArray

            query = "SELECT COUNT(*) as count FROM Bids where auctionID = %s"
            # print(tuple(str(auction["id"])))
            print(auction["id"])
            cursor.execute(query, tuple([str(auction["id"])]))
            # print('loop started')
            bid = cursor.fetchone()
            if bid["count"] == 0:
                print("no bids")
                auction["winner"] = None
            else:
                query = "SELECT amount, id, customerID FROM Bids WHERE auctionID = %s ORDER BY amount DESC LIMIT 1"
                cursor.execute(query, tuple([str(auction["id"])]))

                bid = cursor.fetchone()

                auction["amount"] = str(bid["amount"])

                query = "SELECT * FROM Customers where id = %s"
                print("h")

                cursor.execute(query, tuple([str(bid["customerID"])]))
                print("hi")
                customer = cursor.fetchone()
                auction["winnerName"] = customer["firstName"] + " " + customer["lastName"]

        cursor.close()
        cnx.close()
    except mysql.connector.Error as err:
        return Response("Something went wrong: {}".format(err), status=500)

    return auctions
Exemplo n.º 19
0
def apiAddBid(request):
    Authorizer.authorizeCustomer(request)
    auctionID = request.matchdict["id"]

    customer = request.session["currentUser"]

    requiredKeys = ["value", "maxBid"]
    postVars = request.POST
    acceptedKeys = []

    for key in requiredKeys:
        if key in postVars:
            acceptedKeys.append(postVars[key])
        else:
            print(key)
            raise exc.HTTPBadRequest()

    try:
        cnx = mysql.connector.connect(user="******", password="******", host="127.0.0.1", database="305")
        cursor = cnx.cursor(dictionary=True, buffered=True)

        query = "SELECT COUNT(*) as count, itemID, increment, openingBid, sellerID FROM Auctions WHERE id = %s AND closingTime > NOW()"

        cursor.execute(query, tuple([str(auctionID)]))

        row = cursor.fetchone()
        auctionCount = row["count"]

        if auctionCount == 0:
            cursor.close()
            cnx.close()
            raise exc.HTTPBadRequest()

        itemID = row["itemID"]
        increment = row["increment"]
        if customer["id"] < row["sellerID"]:
            raise exc.HTTPForbidden()

        postVars["value"] = Decimal(postVars["value"])
        postVars["maxBid"] = Decimal(postVars["maxBid"])

        if postVars["value"] < row["openingBid"]:
            raise exc.HTTPForbidden()

        # Check if bid already exists
        query = "SELECT * FROM Bids WHERE customerID = %s AND auctionID = %s"

        cursor.execute(query, tuple([customer["id"], auctionID]))
        print("rowcount", cursor.rowcount)
        if cursor.rowcount > 0:
            row = cursor.fetchone()
            query = "UPDATE Bids SET amount = %s, maxBid = %s WHERE id = %s"
            cursor.execute(query, tuple([postVars["value"], postVars["maxBid"], row["id"]]))

        else:
            query = "INSERT INTO Bids(itemID, customerID, maxBid, amount, time, auctionID) VALUES (%s, %s, %s, %s, NOW(), %s)"
            cursor.execute(
                query, tuple([str(itemID), str(customer["id"]), postVars["maxBid"], postVars["value"], auctionID])
            )

        query = "INSERT INTO BidLogs (amount, customerID, auctionID, time) VALUES (%s, %s, %s, NOW())"

        cursor.execute(query, tuple([postVars["value"], customer["id"], auctionID]))

        query = "SELECT * from Bids WHERE auctionID = %s"

        cursor.execute(query, tuple([str(auctionID)]))

        bids = []

        for row in cursor:
            bid = {}
            for key in row:
                if isinstance(row[key], datetime):
                    bid[key] = row[key].isoformat()
                else:
                    bid[key] = row[key]
            bids.append(bid)

        changed = True

        currentMaxBid = 0

        while changed:
            changed = False
            currentMaxBid = max([bid["amount"] for bid in bids])
            numOccurences = [bid["amount"] for bid in bids].count(currentMaxBid)
            print(numOccurences)
            # print(currentMaxBid)
            if numOccurences == 1:
                for bid in bids:
                    print("\n")
                    print(bid["amount"])
                    print(increment)
                    if (bid["amount"] + increment) <= bid["maxBid"] and bid["amount"] < currentMaxBid:
                        bid["changed"] = True
                        changed = True
                        bid["amount"] = bid["amount"] + increment
            else:
                for bid in bids:
                    print("\n")
                    print(bid["amount"])
                    print(increment)
                    if (bid["amount"] + increment) <= bid["maxBid"] and bid["amount"] <= currentMaxBid:
                        bid["changed"] = True
                        changed = True
                        bid["amount"] = bid["amount"] + increment

        for bid in bids:
            if "changed" in bid:
                # print('wut')
                query = "UPDATE Bids SET amount = %s, time = NOW() WHERE id = %s"
                cursor.execute(query, tuple([bid["amount"], bid["id"]]))
                # print('HIIII')
                query = "INSERT INTO BidLogs (customerID, amount, time, auctionID) VALUES (%s, %s, NOW(), %s)"
                cursor.execute(query, tuple([bid["customerID"], str(bid["amount"]), auctionID]))

        query = "UPDATE Auctions SET currentBid = %s WHERE id = %s"
        cursor.execute(query, tuple([str(currentMaxBid), auctionID]))

        cursor.close()
        print("COMMITTING")
        cnx.commit()
        cnx.close()
    except mysql.connector.Error as err:
        cursor.close()
        cnx.close()
        return Response("Something went wrong: {}".format(err), 500)

    raise exc.HTTPOk()