Exemple #1
0
    def POST(self):
        params = web.input()
        itemID = params['itemID']
        userID = params['userID']
        minPrice = params['minPrice']
        maxPrice = params['maxPrice']
        status = params['status']
        category = params['category']
        description = params['description']
        currTime = sqlitedb.getTime()

        if itemID != "":
            t = sqlitedb.transaction()
            result1 = sqlitedb.getItemByStatus(status, currTime)
            try:
                myresult = sqlitedb.getItemById(itemID)
            except Exception as e:
                t.rollback()
                print str(e)
                update_message = 'No item found.'

                return render_template('search.html',
                                       search_result=False,
                                       message=update_message)
            else:
                t.commit()
                result = merge(myresult, result1)
                return render_template('search.html', search_result=result)
        else:
            t = sqlitedb.transaction()
            try:
                result1 = sqlitedb.getItemByUserID(userID)
                result2 = sqlitedb.getItemByPrice(minPrice, maxPrice)
                result3 = sqlitedb.getItemByStatus(status, currTime)
                result4 = sqlitedb.getItemByCategory(category)
                result5 = sqlitedb.getItemByDescription(description)
            except Exception as e:
                t.rollback()
                print str(e)
                return render_template('search.html', message=str(e))
            else:
                m1 = merge(result1, result2)
                m2 = merge(m1, result3)
                m3 = merge(m2, result4)
                result = merge(m3, result5)
                if result == []:
                    update_message = 'No Item found.'
                    return render_template('search.html',
                                           message=update_message)
                else:
                    return render_template('search.html', search_result=result)
Exemple #2
0
 def POST(self):
     post_params = web.input()
     #if(defined(post_params)):
     restaurantId = post_params['restaurantId']
     name = post_params['name']
     category = post_params['category']
     minPrice = post_params['minPrice']
     maxPrice = post_params['maxPrice']
     city = post_params['city']
     lat = post_params['lat']
     longi = post_params['long']
     distance = post_params['distance']
     minStars = post_params['minStars']
     t = sqlitedb.transaction()
     try:
         search_result = sqlitedb.search(restaurantId, name, category,
                                         minPrice, maxPrice, city, lat,
                                         longi, distance, minStars)
         updateMessage = 'search successful'
     except Exception as e:
         t.rollback()
         updateMessage = str(e)
         #search_result = 'error'
         return render_template('search.html', message=updateMessage)
     else:
         t.commit()
         return render_template('search.html',
                                message=updateMessage,
                                search_result=search_result)
Exemple #3
0
 def GET(self):
     #print itemID
     params = web.input()
     restaurantId = params['restaurantId']
     #print itemID
     t = sqlitedb.transaction()
     try:
         #print "try statement"
         result = sqlitedb.getRestaurantById(
             restaurantId)  #edit function to handle exception
         categories = sqlitedb.getCategories(restaurantId)
         categories_string = 'None'
         if categories:
             categories_string = ''
             for c in categories:
                 categories_string += c.Category
                 categories_string += '; '
     except Exception as e:
         t.rollback()
         error = str(e)
         return render_template('view.html', error=error)
     else:
         t.commit()
         if not result:
             return render_template('view.html')
         return render_template('view.html',
                                result=result,
                                categories=categories_string)
    def getNotOverloaded(self,itemID,message):
        t = sqlitedb.transaction()
        try:
			bidClosed = sqlitedb.isAuctionClosed(itemID)
			itemResults = sqlitedb.getAuctionByItemID(itemID)
			itemInfo = self.prepareQueryForRender(itemResults)
			categoryResults = sqlitedb.getAuctionCategories(itemID)
			sellerResults = sqlitedb.filterBySeller( ((itemInfo['rows'])[0]['sellerID']) )
			bidResults = sqlitedb.getBidHistory(itemID)
			winner = sqlitedb.auctionWinner(itemID)
        except Exception as e:
            print(e)
        else:
            t.commit()
        #print(bidClosed)
        categoryInfo = self.prepareQueryForRender(categoryResults) 
        sellerInfo = self.prepareQueryForRender(sellerResults)
        bidInfo = self.prepareQueryForRender(bidResults)
        try: 
            winner = winner[0]['bidderID']
        except:
            winner='Nobody'
        itemInfo.update(\
            {'bidClosed':bidClosed,\
            'winner':winner,\
            'description':(itemInfo['rows'])[0]['description']})
        #overwrite the item cols because the order gets randomly changed
        itemInfo['cols'] = ['itemID','name','currently','buyPrice','numberOfBids','started','ends','sellerID','firstBid']        
        return self.render_template('auction.html', \
            itemInfo = itemInfo,\
            categoryInfo = categoryInfo,\
            bidInfo = bidInfo,\
            message = message,\
            sellerInfo = sellerInfo)
Exemple #5
0
    def POST(self):
        post_params = web.input()
        logger.debug('select_time.POST just got an input')
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss']
        enter_name = post_params['entername']

        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Hello, %s. Previously selected time was: %s.)' % (
            enter_name, selected_time)
        # save the selected time as the current time in the database
        t = sqlitedb.transaction()
        try:
            query_string = "update CurrentTime set the_time = $selected_time"
            sqlitedb.query(query_string, {'selected_time': selected_time})
        except Exception as e:
            t.rollback()
            msg = 'tried to update time to ' + selected_time + '\nERROR: ' + str(
                e)
            return render_template('select_time.html', message=msg)
        else:
            t.commit()
            return render_template('select_time.html', message=update_message)
Exemple #6
0
    def POST(self):
        post_params = web.input()
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss']
        enter_name = post_params['entername']

        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Hello, %s. Previously selected time was: %s.)' % (
            enter_name, selected_time)
        # TODO: save the selected time as the current time in the database
        t = sqlitedb.transaction()
        try:
            sqlitedb.setTime(selected_time)
        except Exception as e:
            t.rollback()
            print str(e)
            update_message = str(e)
        else:
            t.commit()
        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('select_time.html', message=update_message)
Exemple #7
0
    def POST(self):
        post_params = web.input()
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss']
        enter_name = post_params['entername']

        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Hello, %s. Time was successfully updated!)' % (
            enter_name)
        # TODO: save the selected time as the current time in the database
        # insert transaction

        t = sqlitedb.transaction()
        try:
            _query = 'UPDATE CurrentTime SET Time = $time'
            sqlitedb.db.query(_query, {'time': selected_time})
        except Exception as e:
            t.rollback()
            print str(e)
            update_message = str(e)
        else:
            t.commit()

        current_time = sqlitedb.getTime()

        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('select_time.html',
                               message=update_message,
                               curr_time=current_time)
	def POST(self):
		post_params = web.input()
		itemID = post_params['itemID']
		userID = post_params['userID']
		price = post_params['price']
		update_message = 'Congradulations %s! You successfully made a bid for item %s for $%s' % (userID, itemID, price)

		t = sqlitedb.transaction()
		try:
			makeBidResult = sqlitedb.bid(itemID, userID, price)
		except Exception as e:
			t.rollback()
			update_message = str(e)
			if update_message == 'foreign key constraint failed':
				update_message = 'The username you entered cannot be recognized by our system. Please try again with a different username.'
			elif update_message == 'columns AuctionID, Time are not unique':
				update_message = 'You cannot make a bid at the same time. Please try again later.'
			elif update_message == 'The Bid Amount is not larger than the previous Amount!':
				update_message = 'You have to bid more than the last bid. Please try again with a higher amount.'
		else:
			t.commit()

		auctionResult = sqlitedb.getAuctionDetail(itemID)
		categoryResult = sqlitedb.getItemCategory(itemID)
		categoryString = ''
		for cr in categoryResult:
			categoryString += cr['Category']
			categoryString += ', '
		categoryString = categoryString[:len(categoryString)-2]
		bidResult = sqlitedb.getAuctionBids(itemID)
		winnerString = 'None'
		if bidResult:
			winnerString = bidResult[0]['BidderID']

		return render_template('item.html', items = auctionResult, categories = categoryString, bids = bidResult, winner = winnerString, message = update_message)
Exemple #9
0
    def POST(self):
        #get params
        post_params = web.input()
        itemID = post_params['itemID']
        userID = post_params['userID']
        minPrice = post_params['minPrice']
        maxPrice = post_params['maxPrice']
        status = post_params['status']
        cat = post_params['cat']
        desc = post_params['desc']

        currTime = sqlitedb.getTime()

        #begin transaction
        t = sqlitedb.transaction()
        search_result = []
        err = ""
        try:
            search_result = sqlitedb.searchResults(itemID, userID, minPrice,
                                                   maxPrice, status, cat, desc,
                                                   currTime)
        except Exception as e:
            t.rollback()
            err = "Database Constraints Violated"
        else:
            t.commit()

        return render_template('search.html',
                               err=err,
                               search_result=search_result)
Exemple #10
0
    def POST(self):
        post_params = web.input()
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss'];
        enter_name = post_params['entername']


        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Thank you for changing the time %s. The new time selected is: %s.)' % (enter_name, selected_time)

        t = sqlitedb.transaction()
        query_string = 'update CurrentTime set Time = $time'
        try:
            sqlitedb.db.query(query_string, {'time': selected_time})
        except Exception as e:
            t.rollback()
            update_message = str(e)
        else:
            t.commit()
        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('select_time.html', message = update_message)    
Exemple #11
0
    def POST(self):
        post_params = web.input()
        item_id = int(post_params['itemID'])
        user_id = post_params['userID']
        price = float(post_params['price'])
        current_time = sqlitedb.getTime()
        test = "select * from Bids where (userID = $user_id) and (itemID = $item_id)"
        message = "A bid of $%s has been placed by %s for item %s" % (price,user_id,item_id)
        add_result = ""
        t = sqlitedb.transaction()
        try:
            started = sqlitedb.query("select Started from Items where ItemID = $item_id", {'item_id': item_id})
            ends = sqlitedb.query("select Ends from Items where ItemID = $item_id", {'item_id': item_id})
            buyPrice = sqlitedb.query("select Buy_Price from Items where ItemID = $item_id", {'item_id': item_id})[0].Buy_Price
            s = sqlitedb.query("select * from Bids where (ItemID = $item_id) and (Amount >= $buyPrice)",{'item_id': item_id, 'buyPrice': buyPrice})
            if (sqlitedb.isResultEmpty(s)):
                add_result = "done"
                sqlitedb.query("insert into Bids values ($user_id,$currTime,$price,$item_id)",
                    {'user_id':user_id,'currTime':current_time, 'price':price,'item_id':item_id, 'started': started[0].Started, 'ends': ends[0].Ends})
            
            else:
                message = "INSERT FAILED!"
                add_result = ""


        except Exception as e:
            message = str(e)
            add_result = ""
        else:
            t.commit()

        return render_template('add_bid.html',message = message, add_result = add_result)
Exemple #12
0
 def POST(self):
     post_params = web.input()
     logger.debug('addbid.POST just got an input')
     itemid = post_params['itemID']
     bidderid = post_params['userID']
     bid_amount = post_params['price']
     the_time = sqlitedb.getTime()
     t = sqlitedb.transaction()
     try:
         query_dict = {
             'time': str(the_time),
             'bidder_id': str(bidderid),
             'item_id': int(itemid),
             'amount': float(bid_amount)
         }
         logger.debug(query_dict)
         sqlitedb.db.insert('Bids', **query_dict)
         t.commit()
     except Exception as e:
         t.rollback()
         if str(e) == 'FOREIGN KEY constraint failed':
             e = 'Username not recognized'
         msg = 'Sorry, that was not a legal bid. ERROR: ' + str(e)
         return render_template('addbid.html',
                                message=msg,
                                itemID=itemid,
                                userID=bidderid)
     else:
         msg = 'Your bid is logged. Good luck!'
         return render_template('addbid.html', message=msg)
Exemple #13
0
 def POST(self):
     post_params = web.input()
     itemID = post_params['itemID']
     maxPrice = post_params['maxPrice']
     minPrice = post_params['minPrice']
     status = post_params['status']
     descrption = post_params['descrption']
     category = post_params['category']
     t = sqlitedb.transaction()
     try:
         item_res = sqlitedb.browseAuctions(itemID, category, descrption,
                                            minPrice, maxPrice, status)
         global searchingResult
         searchingResult = item_res
         global urls
         a = (
             '/searchResult/(.*)',
             'searchResult',
         )
         urls = urls + a
         for i in range(len(item_res)):
             urlStr = "http://0.0.0.0:8080/searchResult/search" + str(i)
             item_res[i][0].Link = urlStr
     except Exception as e:
         t.rollback()
         print str(e)
     else:
         t.commit()
     return render_template('search.html', search_result=item_res)
Exemple #14
0
    def GET(self):
        post_params = web.input()
        if bool(post_params):
            itemID = post_params['ItemID']

            t = sqlitedb.transaction()
            err = ""
            search_result1 = []
            search_result2 = []
            search_result3 = []
            #wait for kevins code:
            try:
                search_result1, search_result2, search_result3 = sqlitedb.auctionInfo(
                    itemID)
            except:
                t.rollback()
                err = "error with getting auction information"
            else:
                t.commit()

            return render_template('auction_info.html',
                                   sr1=search_result1,
                                   sr2=search_result2,
                                   sr3=search_result3,
                                   cTime=sqlitedb.getTime())
        else:
            return render_template('auction_info.html')
Exemple #15
0
    def POST(self):
        post_params = web.input()
        itemID = post_params['itemID']
        userID = post_params['userID']
        price = post_params['price']
        add_result = False

        t = sqlitedb.transaction()
        err = ""

        try:
            sqlitedb.placeBid(itemID, userID, price)

        except Exception as e:
            t.rollback()
            err = unicode(e.message, "utf8")
        else:
            try:
                t.commit()
            except Exception as e:
                err = err = unicode(e.message, "utf8")
            else:
                add_result = True

        return render_template('add_bid.html', add_result=add_result, err1=err)
    def POST(self):
        current_time = sqlitedb.getTime()
        post_params = web.input()
        itemID = post_params['itemID']
        userID = post_params['userID']
        price = float(post_params['price'])

        if sqlitedb.getUser(userID):
            if sqlitedb.getItemById(itemID) is None:
                result = False
                update_message = 'Item is invalid'
                return render_template('add_bid.html',
                                       add_result=result,
                                       message=update_message)
            else:
                if sqlitedb.bidisOpen(itemID):
                    t = sqlitedb.transaction()
                    query_string = 'INSERT INTO Bids (itemID, UserID, Amount, Time) VALUES ($itemID, $userid, $price, $time) '
                    try:
                        if user_id == '' or item_id == '' or amount == '':
                            return render_template('add_bid.html',
                                                   message='empty fields')
                        sqlitedb.query(
                            query_string, {
                                'itemID': itemID,
                                'userid': userID,
                                'price': price,
                                'time': current_time
                            })
                    except Exception as e:
                        t.rollback()
                        print str(e)
                        update_message = 'An error has occurred'
                        result = False
                        return render_template('add_bid.html',
                                               add_result=result,
                                               message=update_message)
                    else:
                        t.commit()
                        update_message = 'Add bid successfully!'
                        result = True
                        return render_template('add_bid.html',
                                               add_result=result,
                                               message=update_message)
                else:
                    update_message = 'Bid is closed'
                    result = False
                    return render_template('add_bid.html',
                                           add_result=result,
                                           message=update_message)
        else:
            result = False
            update_message = 'User is invalid'
            return render_template('add_bid.html',
                                   add_result=result,
                                   message=update_message)
Exemple #17
0
 def GET(self):
     t = sqlitedb.transaction()
     try:
         current_time = sqlitedb.getTime()
     except Exception as e:
         t.rollback()
         print str(e)
     else:
         t.commit()
     return render_template('curr_time.html', time=current_time)
Exemple #18
0
    def POST(self):
        try:
            post_params = web.input()
            add_result = ''
            item_id = post_params['itemID']
            price = post_params['price']
            user_id = post_params['userID']
            current_time = sqlitedb.getTime()

            # Validation checks

            # make all input fields required
            if (item_id == '' or price == '' or user_id == ''):
                return render_template(
                    'add_bid.html', message='Error: All fields are required')

            # don't accept bids on items that don't exist
            if (sqlitedb.getItemById(item_id) == None):
                return render_template('add_bid.html',
                                       message='Error: Invalid Item ID !')

            # Don't accept bids from users that don't exist
            if (sqlitedb.getUserById(user_id) == None):
                return render_template('add_bid.html',
                                       message='Error: Invalid User ID !')

            # @TODO: add more validation checks

            # insert transaction
            t = sqlitedb.transaction()
            try:
                sqlitedb.db.insert('Bids',
                                   ItemID=item_id,
                                   UserID=user_id,
                                   Amount=price,
                                   Time=current_time)

            except Exception as e:
                t.rollback()
                message = str(e)
                print str(e)

            else:
                t.commit()
                message = 'Success ! Added bid for ' + str(
                    item_id) + ' by ' + str(user_id) + ' at $' + str(price)
                print 'commited ' + str(t)
                # @TODO validations

        except Exception as e:
            message = str(e)

        return render_template('add_bid.html',
                               message=message,
                               add_result=add_result)
Exemple #19
0
    def POST(self):
        print web.input()
        post_params = web.input()
        itemID = post_params['itemID']
        price = post_params['price']
        userID = post_params['userID']
        if not sqlitedb.checkItemID(itemID):
            update_message = 'ItemID is not found'
            return render_template('add_bid.html', message=update_message)
        if not sqlitedb.checkUserID(userID):
            update_message = "UserID is not found"
            return render_template('add_bid.html', message=update_message)
        ''' if not sqlitedb.checkBidBuyPrice(price, itemID):
            update_message = 'Buy Price has already been exceeded'
            return render_template('add_bid.html', message=update_message) '''
        t = sqlitedb.transaction()
        if sqlitedb.hasAuctionEnded(itemID):
            update_message = 'Auction has ended'
        try:
            current_time = sqlitedb.getTime()
            int(itemID)
            #if isinstance(itemID, int):
            update_message = 'Bid set on item:%s at $%s' \
                        ' at %s' % ((itemID), (price), (current_time))
            sqlitedb.insertBid(itemID, userID, price, current_time)
        except Exception as e:
            t.rollback()
            print str(e)
            #update_message = str(e)
            update_message = "Please check your input"
            result = False
        else:
            result = True
            t.commit()
        ''' try:
            current_time = sqlitedb.getTime()
            int(itemID)
            #if isinstance(itemID, int):
            update_message = 'Bid set on item:%s at $%s' \
                        ' at %s' % ((itemID), (price), (current_time))
            sqlitedb.insertBid(itemID, userID, price, current_time)
            #else:
            #    raise Exception('Error: ItemID was not an int')
        except Exception as e:
            print str(e)
            update_message = str(e) '''

        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('add_bid.html',
                               message=update_message,
                               add_result=result)
Exemple #20
0
 def POST(self):
     post_params = web.input()
     itemID = post_params['itemID']
     userID = post_params['userID']
     category = post_params['category']
     itemDesc = post_params['itemDesc']
     minPrice = post_params['minPrice']
     maxPrice = post_params['maxPrice']
     status = post_params['status']
     t = sqlitedb.transaction()
     try:
         Items = sqlitedb.search(itemID, userID, category, itemDesc,
                                 maxPrice, minPrice, status)
         result = {}
         item_list = []
         category_list = []
         Bid_list = []
         winner_list = []
         for itemID in Items:
             item = sqlitedb.getItemById(itemID)
             item_list.append(item)
             category_list.append(sqlitedb.getCategoryByID(itemID))
             currTime = sqlitedb.getTime()
             #check if buy_price is reached
             if item.Buy_Price != None and item.Buy_Price <= item.Currently and item.Number_of_Bids != 0:
                 status = "Closed"
             else:
                 if currTime < item.Started:
                     status = 'NotStarted'
                 elif currTime > item.Ends:
                     status = 'Closed'
                 else:
                     status = 'Open'
             Bid_list.append(sqlitedb.getBidsByID(itemID))
             winner = None
             if status == 'Closed':
                 winner = sqlitedb.getWinnerByID(itemID)
             winner_list.append(winner)
             #print(map(itemgetter('Category'), sqlitedb.getCategoryByID(itemID)))
     except Exception as e:
         t.rollback()
         print(str(e))
         return render_template('search.html', message=str(e))
     else:
         t.commit()
         return render_template('search_result.html',
                                Item=item_list,
                                Categories=category_list,
                                status=status,
                                Bids=Bid_list,
                                Winner=winner_list)
 def POST(self):
     current_time = sqlitedb.getTime()
     post_params = web.input()
     itemID = post_params['itemID']
     userID = post_params['userID']
     price = float(post_params['price'])
     
     # if the user is valid
     if sqlitedb.getUserByUserId(userID):
         # if the item is valid
         if sqlitedb.getItemById(itemID) is not None:
             # if the bid is active
             if sqlitedb.isBidActive(itemID):
                 t = sqlitedb.transaction()
                 query_string = 'INSERT INTO Bids (itemID, UserID, Amount, Time) VALUES ($itemID, $userID, $price, $time) '
                 try:
                     if itemID == '':
                         return render_template('add_bid.html', message = 'no itemID')
                     if userID == '':
                         return render_template('add_bid.html', message = 'no userID')
                     if price == '':
                         return render_template('add_bid.html', message = 'no amount')
                     sqlitedb.query(query_string, {'itemID': itemID, 'userid': userID, 'price': price, 'time': current_time})
                 except Exception as exception:
                     t.rollback()
                     print str(exception)
                     result = False
                     update_message = 'Error when add a bid'
                     return render_template('add_bid.html', add_result = result, message = update_message)
                 else:
                     t.commit()
                     result = True
                     update_message = 'Successfully add a bid'
                     return render_template('add_bid.html', add_result = result, message = update_message)
             # if the bid is not active
             else:
                 result = False
                 update_message = 'The bid is closed now'
                 return render_template('add_bid.html', add_result = result, message = update_message)
         # if the item can't be found
         else:
             result = False
             update_message = 'Cannot get the item with item id'
             return render_template('add_bid.html', add_result = result, message = update_message)
     # if the user can't be found
     else:
         result = False
         update_message = 'Cannot get the user with user id'
         return render_template('add_bid.html', add_result = result, message = update_message)
Exemple #22
0
 def POST(self):
     post_params = web.input()
     itemID = post_params['itemID']
     price = post_params['price']
     userID = post_params['userID']
     t = sqlitedb.transaction()
     try:
         add_result = sqlitedb.enterBids(itemID, userID.encode("utf-8"),
                                         price)
     except Exception as e:
         t.rollback()
         print str(e)
     else:
         t.commit()
     return render_template('add_bid.html', add_result=add_result)
Exemple #23
0
    def POST(self):
        current_time = sqlitedb.getTime()
        post_params = web.input()
        itemID = post_params['itemID']
        userID = post_params['userID']
        price = post_params['price']

        if sqlitedb.isUserValid(userID):
            try:
                if sqlitedb.isBidAlive(itemID):
                    # Add bid into db
                    t = sqlitedb.transaction()
                    try:
                        #sqlitedb.update('update CurrentTime set time = $updated_time', {'updated_time': selected_time})
                        sqlitedb.query(
                            'INSERT INTO Bids (itemID, UserID, Amount, Time) VALUES ($itemID, $userid, $price, $time) ',
                            {
                                'itemID': itemID,
                                'userid': userID,
                                'price': price,
                                'time': current_time
                            }, True)
                    except Exception as e:
                        t.rollback()
                        print str(e)
                        update_message = 'An error occur'
                        result = False
                    else:
                        t.commit()
                        update_message = 'Success!'
                        result = True
                else:
                    update_message = 'Auction on this item is closed'
                    result = False
            except Exception as e:
                # item not exist
                print(e)
                result = False
                update_message = 'Item not exist'
        else:
            result = False
            update_message = 'User is not exist'

        return render_template('add_bid.html',
                               add_result=result,
                               message=update_message)
    def tryAddingBid(self, itemID, userID, price):

        # Check if inputs exists and are valid
        inputResult = self.validateInput(itemID, userID, price)
        if inputResult["error"]:
            return inputResult

        # Check if the itemID exists in the database
        itemResult = isItemNotPresent(itemID)
        if itemResult["error"]:
            return itemResult

        # check if the user exits in the database
        userResult = isUserNotPresent(userID)
        if userResult["error"]:
            return userResult

        # check if the bid is open
        bidOpen = isAuctionClosedForItem(itemID)
        if bidOpen["error"]:
            return bidOpen

        transaction = sqlitedb.transaction()
        try:
            query_string = 'INSERT INTO BIDS VALUES ($itemID, $userID, $price, $currtime)'

            values = {
                'itemID': int(itemID),
                'userID': userID,
                'price': float(price),
                'currtime': sqlitedb.getTime()
            }
            sqlitedb.executeQuery(query_string, values)

        except Exception as e:
            transaction.rollback()
            #print(str(e))
            triggerErrors = processTriggerErrors(str(e))

            if (triggerErrors["error"]):
                return triggerErrors

            return processSQLErrors(str(e))
        else:
            transaction.commit()
            return createReturnObject(False, "Bid successfully placed")
Exemple #25
0
    def POST(self):
        current_time = sqlitedb.getTime()
        post_params = web.input()
        userID = post_params['userID']
        price = post_params['price']
        itemID = post_params['itemID']

        if sqlitedb.checkUser(userID):
            try:
                if sqlitedb.checkBid(itemID):
                    t = sqlitedb.transaction()
                    try:
                        sqlitedb.query(
                            'INSERT INTO Bids (itemID, UserID, Amount, Time) VALUES ($itemID, $userid, $price, $time) ',
                            {
                                'itemID': itemID,
                                'userid': userID,
                                'price': price,
                                'time': current_time
                            }, True)
                    except Exception as e:
                        t.rollback()
                        print str(e)
                        update_message = 'Failed'
                        result = False
                    else:
                        t.commit()
                        update_message = 'Success'
                        result = True
                else:
                    update_message = 'Closed item'
                    result = False
            except Exception as e:
                print(e)
                update_message = 'Item does not exist'
                result = False
        else:
            update_message = 'User does not exist'
            result = False
        return render_template('add_bid.html',
                               add_result=result,
                               message=update_message)
Exemple #26
0
    def POST(self):
        post_params = web.input()
        item_id = post_params['itemid']
        user_id = post_params['userid']
        amount = post_params['amount']
        current_time = sqlitedb.getTime()

        web.debug(item_id)
        web.debug(user_id)
        web.debug(amount)

        t = sqlitedb.transaction()
        try:
            sqlitedb.addBid(item_id, user_id, current_time, amount)
        except:
            t.rollback()
            raise web.seeother('/500?errortype={0}&errorvalue={1}'.format(sys.exc_info()[0], sys.exc_info()[1]))
        else:
            t.commit()

        return render_template('place_bid.html', itemid = item_id, username = session.get('username', None))
Exemple #27
0
 def POST(self):
     categories = sqlitedb.getAllCategories()
     post_params = web.input()
     restaurantId = post_params['restaurantId']
     name = post_params['name']
     category = post_params['category']
     minPrice = post_params['minPrice']
     maxPrice = post_params['maxPrice']
     city = post_params['city']
     lat = post_params['lat']
     longi = post_params['long']
     distance = post_params['distance']
     minStars = post_params['minStars']
     numResults = post_params['numResults']
     sortBy = post_params['sortBy']
     #print post_params
     t = sqlitedb.transaction()
     try:
         search_result = sqlitedb.search(restaurantId, name, category,
                                         minPrice, maxPrice, city, lat,
                                         longi, distance, minStars,
                                         numResults, sortBy)
         #search_result = sqlitedb.search(None, None, None, None, None, None, None, None, None, '5')
         #search_result = sqlitedb.getRestaurantById('W9Bh_7mfuUrEAdQBJMVOvA')
         updateMessage = 'search successful'
     except Exception as e:
         t.rollback()
         updateMessage = str(e)
         #search_result = 'error'
         #return json.dumps({'status': 1, 'message': updateMessage})
         return render_template('search.html',
                                message=updateMessage,
                                categories=categories)
     else:
         t.commit()
         #return json.dumps({'status': 0, 'results': list(search_result)})
         return render_template('search.html',
                                message=updateMessage,
                                search_result=search_result,
                                categories=categories)
    def POST(self):
        post_params = web.input()
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss']
        enter_name = post_params['entername']

        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Hello, %s. Previously selected time was: %s.)' % (enter_name, selected_time)

        transaction = sqlitedb.transaction()
        try:
            query_string = "UPDATE CurrentTime SET time = $selected_time where time = $current_time"

            current_time = sqlitedb.getTime()

            #print("select time query: " + query_string)
            #print("selected_time type: " + str(type(selected_time)))
            #print("current_time type: " + str(type(current_time)))

            values = {
                "selected_time": selected_time,
                "current_time": sqlitedb.getTime()
            }

            result = sqlitedb.executeQuery(query_string, values)
        except Exception as e:
            transaction.rollback()
            #print("Inside exception clause in selecttime: " + str(e))
            triggerErrors = processTriggerErrors(str(e))
            update_message = "Error: " + triggerErrors["msg"]
        else:
            transaction.commit()

        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('select_time.html', message = update_message)
Exemple #29
0
    def POST(self):
        try:
            post_params = web.input()
            add_result = ''
            item_id = post_params['itemID']
            price = post_params['price']
            user_id = post_params['userID']
            current_time = sqlitedb.getTime()

            # Must have all inputs filled out
            if (item_id == '' or price == '' or user_id == ''):
                return render_template('add_bid.html', message='Invalid entry: All fields required.')

            # Check item exists
            if (sqlitedb.getItemById(item_id) == None):
                return render_template('add_bid.html', message='Invalid entry: Item ID not found.')

            # Check user exists
            if (sqlitedb.getUserById(user_id) == None):
                return render_template('add_bid.html', message='Invalid entry: User ID not found.')

            t = sqlitedb.transaction()
            try:
                sqlitedb.db.insert('Bids', ItemID=item_id, UserID=user_id, Amount=price, Time=current_time)

            except Exception as e:
                add_result = 2
                t.rollback()
                message = str(e)

            else:
                t.commit()
                add_result = 1
                message = 'Success ! Added bid for ' + str(item_id) + ' by ' + str(user_id) + ' at $' + str(price)

        except Exception as e:
            message = str(e)

        return render_template('add_bid.html', message=message, add_result=add_result)
	def POST(self):
		post_params = web.input()
		MM = post_params['MM']
		dd = post_params['dd']
		yyyy = post_params['yyyy']
		HH = post_params['HH']
		mm = post_params['mm']
		ss = post_params['ss'];
		enter_name = post_params['entername']

		selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
		update_message = '(Time updated to: %s.)' % (selected_time)

		t = sqlitedb.transaction()
		try:
			result = sqlitedb.updateTime(selected_time)
		except Exception as e:
			t.rollback()
			update_message = str(e)
		else:
			t.commit()
		return render_template('select_time.html', message = update_message)
Exemple #31
0
 def GET(self):
     #print itemID
     params = web.input()
     restaurantId = params['restaurantId']
     #print itemID
     t = sqlitedb.transaction()
     try:
         #print "try statement"
         result = sqlitedb.getRestaurantById(
             restaurantId)  #edit function to handle exception
         categories = sqlitedb.getCategories(restaurantId)
         categories_string = 'None'
         if categories:
             categories_string = ''
             for c in categories:
                 categories_string += c.Category
                 categories_string += '; '
         reviewsResult = sqlitedb.getReviewsByRestaurant(restaurantId)
         #print reviewsResult
     except Exception as e:
         t.rollback()
         error = str(e)
         #return json.dumps({'status': 1, 'error': error})
         return render_template('view.html', error=error)
     else:
         t.commit()
         if not result:
             #return json.dumps({'status': 0, 'message': 'no results'})
             return render_template('view.html')
         #return json.dumps({'status': 0, 'results': list(result)})
         if reviewsResult is None:
             return render_template('view.html',
                                    result=result,
                                    categories=categories_string)
         else:
             return render_template('view.html',
                                    result=result,
                                    categories=categories_string,
                                    reviews=reviewsResult)
Exemple #32
0
 def POST(self):
     params = web.input()
     itemID = int(params['itemID'])
     userID = params['userID']
     price = params['price']
     currentTime = sqlitedb.getTime()
     update_message = 'You(userID:%s) have successfully bidded on the item(itemID:%s) for %s dollars' % (
         userID, itemID, price)
     t = sqlitedb.transaction()
     try:
         sqlitedb.addBid(itemID, userID, price, currentTime)
     except Exception as e:
         t.rollback()
         print str(e)
         update_message = str(e)
         return render_template('add_bid.html',
                                message=update_message,
                                add_result=False)
     else:
         t.commit()
         return render_template('add_bid.html',
                                message=update_message,
                                add_result=True)
    def querySearchArgs(self,message,itemid,userid,price):
    	t = sqlitedb.transaction()
        try:
            bidClosed = sqlitedb.isAuctionClosed(itemid)
            if bidClosed:
                message = "Bid not placed! I'm sory the auction is closed for item id:" + str(itemid)
                return self.getNotOverloaded(itemid,message)
            currentTime = sqlitedb.getTime()
            sqlitedb.placeBid(currentTime,itemid,userid,price)
            sqlitedb.updateNumberOfBidsAndCurrently(itemid,price)
        except Exception as e:
            t.rollback()
            message = "Bid not placed! " + str(e)
            if str(e)=='constraint failed':
                message = "Bid not placed! You wagered more than the buy price. Just trying to save you money!"
            if str(e)=='foreign key constraint failed':
                message = "Bid not placed!  User " + userid + " does not exist!"
            return self.getNotOverloaded(itemid,message)
        else:
            t.commit()

        message = userid + ' successfully placed a bid of $' + str(price) +' itemID=' + str(itemid)
        return self.getNotOverloaded(itemid,message)
Exemple #34
0
 def POST(self):
     post_params = web.input()
     itemID = post_params['itemID']
     userID = post_params['userID']
     amount = post_params['price']
     # insert a bid
     # 1. trigger4 will increase the number of bids for that item
     # 2. trigger3 checks new amount is higher that previous amount
     # 3. trigger5,6 check this bid's time cannot outside start and end time
     # 5. userID and itemID must exist gauranteed by foreigh key constraints
     # 6. trigger 8 set the current price to be the new amount
     # 7. we need to check that auction is closed if buy price is reached
     # TODO 4
     t = sqlitedb.transaction()
     try:
         #check if user enter all filelds
         if userID == "" or itemID == "" or amount == "":
             raise Exception("Please fill in all information!!")
         else:
             #check if this auction is open or not
             if not sqlitedb.checkStatus(itemID):
                 raise Exception("This auction is closed!")
             else:
                 sqlitedb.insertBids(itemID, userID, amount)
     except:
         t.rollback()
         print("error!!!")
         #print(str(e))
         return render_template(
             'add_bid.html',
             message=
             "Invalid Input! Please try again to fill in corret data!")
     else:
         t.commit()
         return render_template('add_bid.html',
                                message="Your bid has been added!",
                                add_result="success")
Exemple #35
0
    def POST(self):
        post_params = web.input()
        MM = post_params['MM']
        dd = post_params['dd']
        yyyy = post_params['yyyy']
        HH = post_params['HH']
        mm = post_params['mm']
        ss = post_params['ss'];
        enter_name = post_params['entername']


        selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)
        update_message = '(Hello, %s. Previously selected time was: %s.)' % (enter_name, selected_time)
        t = sqlitedb.transaction()
        try:
            sqlitedb.query('update CurrentTime set currTime = $time', {'time': selected_time})
        except Exception as e: 
            update_message = str(e)
            t.rollback()
        else:
            t.commit()
        # Here, we assign `update_message' to `message', which means
        # we'll refer to it in our template as `message'
        return render_template('select_time.html', message = update_message)
Exemple #36
0
    def POST(self):
        post_params = web.input()
        itemID = post_params['itemID']
        userID = post_params['userID']
        itemCategory = post_params['itemCategory']
        minPrice = post_params['minPrice']
        maxPrice = post_params['maxPrice']
        status = post_params['status']
        itemDescription = post_params['itemDescription']
        userInfo = {
            'itemID': itemID,
            'itemCategory': itemCategory,
            'itemDescription': itemDescription,
            'userID': userID,
            'minPrice': minPrice,
            'maxPrice': maxPrice,
            'status': status
        }
        searchinfo = {}
        searchlen = {'select': ['distinct', '*'], 'from': [], 'where': []}
        searchstring = ""

        for key, value in userInfo.items():
            if value != "":
                if "itemID" == key:
                    if not sqlitedb.checkItem(value):
                        error_message = 'Following Item ID does not exist:' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append('Items.itemID = $itemID')

                elif "userID" == key:
                    if not sqlitedb.checkUser(value):
                        error_message = 'Following User ID does not exist:' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append(
                        'exists(select Users.userID from Users where Users.userID = $userID and Items.Seller_UserID==Users.userID)'
                    )

                elif "itemCategory" == key:
                    if not sqlitedb.checkCategory(value):
                        error_message = 'Following Item Category does not exist :' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append(
                        'exists(select Categories.itemID from Categories where Categories.category = $itemCategory and Categories.itemID = Items.itemID)'
                    )

                elif "itemDescription" == key:
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append(
                        'Items.Description like $itemDescription')
                    value = '%' + value + '%'

                elif "minPrice" == key:
                    if not sqlitedb.checkMin(value):
                        error_message = 'Following price does not exist:' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append('Items.Currently >= $minPrice')

                elif "maxPrice" == key:
                    if not sqlitedb.checkMax(value):
                        error_message = 'Following price does not exist:' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    searchlen['where'].append('Items.Currently <= $maxPrice')

                elif "status" == key:
                    currentTime = sqlitedb.getTime()
                    currentTimeString = '\'' + currentTime + '\''
                    if not sqlitedb.checkStatus(value, currentTimeString):
                        error_message = 'An item does not exist with Status:' + value
                        return render_template('search.html',
                                               message=error_message)
                    if "Items" not in searchlen['from']:
                        searchlen['from'].append('Items')
                    if value == 'open':
                        searchlen['where'].append('Items.Ends>' +
                                                  currentTimeString +
                                                  ' and Currently<Buy_Price')
                    elif value == 'close':
                        searchlen['where'].append('(Items.Ends<' +
                                                  currentTimeString +
                                                  ' or Currently>=Buy_Price)')
                    elif value == 'notStarted':
                        searchlen['where'].append('Items.Started>' +
                                                  currentTimeString)
                    else:
                        pass
                searchinfo[key] = value
            else:
                print(key + "does not have data.")

        searchstring = 'select'
        for index, value in enumerate(searchlen['select']):
            if (index + 1 != len(searchlen['from'])):
                searchstring = searchstring + ' ' + value
            else:
                searchstring = searchstring + ' ' + value

        if len(searchlen['from']) != 0:
            searchstring = searchstring + ' from'
            for index, value in enumerate(searchlen['from']):
                if (index + 1 != len(searchlen['from'])):
                    searchstring = searchstring + ' ' + value + ','
                else:
                    searchstring = searchstring + ' ' + value

        if len(searchlen['where']) != 0:
            searchstring = searchstring + ' where'
            for index, value in enumerate(searchlen['where']):
                if (index + 1 != len(searchlen['where'])):
                    searchstring = searchstring + ' ' + value + ' and'
                else:
                    searchstring = searchstring + ' ' + value
        t = sqlitedb.transaction()
        try:
            search_result = sqlitedb.query(searchstring, searchinfo)

        except Exception as e:
            t.rollback()
            print str(e)
        else:
            t.commit()
        return render_template('search.html',
                               search_result=search_result,
                               search_params=userInfo)
Exemple #37
0
    def POST(self):
        post_params = web.input()
        item_id = post_params['itemID']
        user_id = post_params['userID']
        min_price = post_params['minPrice']
        max_price = post_params['maxPrice']
        category = post_params['category']
        status = post_params['status']
        search_result = [status]
        src1 = ""
        src2 = ""
        src3 = ""
        src4 = ""
        src5 = ""
        src6 = ""
        itemId = ""
        minPrice = ""
        maxPrice = ""
        winnerStr = ""

        currTime = sqlitedb.getTime()
        if (item_id != ""):
            itemId = int(item_id)
            src1 = " (select ItemID from Items where ItemID = $itemId) "
        
        if (user_id != ""):
            src2 = " (select ItemID from Sales where UserID = $userId) "
        
        if (min_price != ""):
            minPrice = float(min_price)
            src3 = " (select ItemID from Items where Currently > $minPrice) "
        if (max_price != ""):
            maxPrice = float(max_price)
            src4 = " (select ItemID from Items where Currently < $maxPrice) "
        if (status == "open" ):
            src5 = " (select ItemID from Items where (Started < $currTime) and (Ends > $currTime)) "
        if (status == "close"):
            winnerStr = "select distinct ItemID, UserID as Winner from Bids where UserID in (select UserID from (select UserID, max(Amount) from Bids group by ItemID))"
            src5 = " (select ItemID from Items where ((Started < $currTime) and (Ends < $currTime)) or Currently > Buy_Price)"
        if (status == "notStarted"):
            src5 = " (select ItemID from Items where (Started > $currTime) and (Ends > $currTime)) "
        if (status == "all") :
            src5 = " (select ItemID from Items) "
        if (category != ""):
            src6 = " (select ItemID from Categories where (Category = $category)) "
        arr = [src1,src2,src3,src4,src5,src6]
        query_string = "select distinct * from Items inner join Sales on Items.ItemID = Sales.ItemID where Items.ItemID in"
        first = False
        for i in xrange(len(arr)):
            if first == False and arr[i] != "":
                first = True
                query_string += arr[i]
            elif arr[i] != "":
                query_string += "and Items.ItemID in" + arr[i]

        t = sqlitedb.transaction()
        if (winnerStr != ""):
            cols = "q1.ItemID,Ends,First_Bid,Name,Started,Number_of_Bids,UserID,Buy_Price,Currently,Description,Winner"
            query_string = "select distinct " + cols +  " from (" +query_string + ") q1 inner join (" + winnerStr + ") q2 on q1.ItemID = q2.ItemID"
        
        
        try:
            result = sqlitedb.query(query_string, {'userId' : user_id, 'itemId': itemId, 'maxPrice':maxPrice, 'minPrice': minPrice, 'currTime':currTime, 'category':category})
            search_result = result
        except Exception as e:
            search_result = []

        else:
            t.commit()

            


        return render_template('search.html',search_result = search_result)