def deleteBaseMenuItem(cuisine_id, baseMenuItem_id): '''Serve form to delete a base menu item ''' client_login_session = getClientLoginSession() baseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=baseMenuItem_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(baseMenuItem_id=baseMenuItem_id) baseForNoCuisine = DataManager.\ getBaseMenuItem(baseMenuItem_id=-1) DataManager.deleteBaseMenuItem(baseMenuItem_id=baseMenuItem_id) flash("reassigned " + str(len(restaurantMenuItems)) + \ " restaurant menu items' base to '" +\ baseForNoCuisine.name + "'") flash("deleted " + baseMenuItem.name + " from " +\ cuisine.name + "'s base menu and from the database") return redirect(url_for('cuisine',cuisine_id=cuisine_id)) else: return render_template("DeleteBaseMenuItem.html", baseMenuItem=baseMenuItem, cuisine_id=cuisine_id, hiddenToken=login_session['state'], client_login_session=client_login_session)
def addCuisine(): '''Serve form for adding a cuisine to the database ''' client_login_session = getClientLoginSession() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) name = validateUserInput(request.form['name'], 'name', 'create', 'cuisine', maxlength=80, required=True, unique=True) if name is None: return redirect(url_for('cuisines')) DataManager.addCuisine(name) flash("Added cuisine '" + name + "' to the database!") return redirect(url_for('cuisines')) else: return render_template('AddCuisine.html', hiddenToken=login_session['state'], client_login_session=client_login_session)
def deleteRestaurant(restaurant_id): '''Serve form to delete a restaurant ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to delete this restaurant") return redirect(url_for('restaurant', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(restaurant_id=restaurant_id) DataManager.deleteRestaurant(restaurant_id) flash("deleted " + str(len(restaurantMenuItems)) + \ " restaurant menu items from the database") flash("deleted restaurant " + str(restaurant.id) + " (" + \ restaurant.name + ") from the database") return redirect(url_for('restaurants')) else: return render_template('DeleteRestaurant.html', restaurant=restaurant, hiddenToken=login_session['state'], client_login_session=client_login_session)
def editCuisine(cuisine_id): '''Serve form to edit a cuisine ''' client_login_session = getClientLoginSession() cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) oldName = cuisine.name newName = validateUserInput(request.form['name'], 'name', 'edit', 'cuisine', maxlength=80, unique=True, oldInput=oldName, tableName='Cuisine') DataManager.editCuisine(cuisine_id, newName=newName) if newName is not None: flash("Changed cuisine's name from '" + oldName +\ "' to '" + newName + "'") return redirect(url_for('cuisine', cuisine_id=cuisine_id)) else: return render_template("EditCuisine.html", cuisine=cuisine, hiddenToken=login_session['state'], client_login_session=client_login_session)
def deleteCuisine(cuisine_id): '''Serve form to delete a cuisine ''' client_login_session = getClientLoginSession() cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) # all of this is for flash messaging cuisineName = cuisine.name cuisineID = cuisine.id restaurantMenuItems = DataManager.\ getRestaurantMenuItems(cuisine_id=cuisine_id) numItemsReassigned = len(restaurantMenuItems) restaurants = DataManager.\ getRestaurants(cuisine_id=cuisine_id) numRestaurantsReassigned = len(restaurants) baseMenuItems = DataManager.\ getBaseMenuItems(cuisine_id=cuisine_id) numItemsDeleted = len(baseMenuItems) itemBaseForNoCuisine = DataManager.\ getBaseMenuItem(baseMenuItem_id=-1) # here is the logic restaurantBaseForNoCuisine = DataManager.\ getCuisine(cuisine_id=-1) DataManager.deleteCuisine(cuisine_id) flash("reassigned " + str(numItemsReassigned) + \ " restaurant menu items' base item to '" + \ itemBaseForNoCuisine.name + "'") flash("reassigned " + str(numRestaurantsReassigned) + \ " restaurants' cuisine to '" + \ restaurantBaseForNoCuisine.name + "'") flash("deleted " + str(numItemsDeleted) + \ " base menu items from the database") flash("deleted cuisine " + str(cuisineID) + " (" + \ cuisineName + ") from the database") return redirect(url_for('cuisines')) else: return render_template("DeleteCuisine.html", cuisine=cuisine, hiddenToken=login_session['state'], client_login_session=client_login_session)
def restaurantMenuItem(restaurant_id, restaurantMenuItem_id): '''Serve a restaurant menu item ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to view this item's details") return redirect(url_for('restaurantMenu', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() restaurantMenuItem = DataManager.\ getRestaurantMenuItem(restaurantMenuItem_id) restaurantMenuItem.price = Decimal(restaurantMenuItem.price).\ quantize(Decimal('0.01')) restaurantCuisineObj = DataManager.\ getCuisine(cuisine_id=restaurant.cuisine_id) restaurantCuisine = restaurantCuisineObj.name restaurantMenuItemSection = DataManager.\ getMenuSection(menuSection_id=restaurantMenuItem.menuSection_id) baseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=restaurantMenuItem.baseMenuItem_id) baseMenuItem.price = Decimal(baseMenuItem.price).quantize(Decimal('0.01')) baseMenuItemCuisineObj = DataManager.\ getCuisine(cuisine_id=baseMenuItem.cuisine_id) baseMenuItemCuisine = baseMenuItemCuisineObj.name baseMenuItemSection = DataManager.\ getMenuSection(menuSection_id=baseMenuItem.menuSection_id) picture = DataManager.getPicture(restaurantMenuItem.picture_id) timesOrdered = 0 return render_template("RestaurantMenuItem.html", restaurantMenuItem=restaurantMenuItem, restaurant=restaurant, restaurantCuisine=restaurantCuisine, baseMenuItem=baseMenuItem, baseMenuItemCuisine=baseMenuItemCuisine, timesOrdered=timesOrdered, picture=picture, restaurantMenuItemSection=restaurantMenuItemSection, baseMenuItemSection=baseMenuItemSection, client_login_session=client_login_session)
def baseMenuItem(cuisine_id, baseMenuItem_id): '''Serve a base menu item ''' client_login_session = getClientLoginSession() baseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=baseMenuItem_id) baseMenuItem.price = Decimal(baseMenuItem.price).\ quantize(Decimal('0.01')) cuisine = DataManager.\ getCuisine(cuisine_id=baseMenuItem.cuisine_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(baseMenuItem_id=baseMenuItem.id) picture = DataManager.getPicture(baseMenuItem.picture_id) menuSection = DataManager.\ getMenuSection(menuSection_id=baseMenuItem.menuSection_id) timesOrdered = 0 return render_template("BaseMenuItem.html", baseMenuItem=baseMenuItem, restaurantMenuItems=restaurantMenuItems, cuisine=cuisine, timesOrdered=timesOrdered, picture=picture, menuSection=menuSection, client_login_session=client_login_session)
def allRestaurantMenuItemsJSON(): '''JSON endpoint for all restaurant menu items ''' restaurantMenuItems = DataManager.getRestaurantMenuItems() return jsonify(RestaurantMenuItems=\ [i.serialize for i in restaurantMenuItems])
def restaurantMenu(restaurant_id): '''Serve a restaurant's menu ''' restaurant = DataManager.getRestaurant(restaurant_id) sectionedItems = DataManager.\ getRestaurantMenuItems(restaurant_id=restaurant_id, byMenuSection=True) for menuSection, items in sectionedItems.iteritems(): for item in items: # ensure display nicely formatted item.price = Decimal(item.price).quantize(Decimal('0.01')) if (isLoggedIn() and restaurant.user_id == login_session['user_id']): return render_template('PrivateRestaurantMenu.html', restaurant=restaurant, sectionedItems=sectionedItems) else: return render_template('PublicRestaurantMenu.html', restaurant=restaurant, sectionedItems=sectionedItems)
def cuisineJSON(cuisine_id): '''JSON endpoint for a single cuisine Includes all restaurants with that cuisine, all base menu items for that cuisine, and all restaurant menu items based on that cuisine ''' cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) baseMenuItems = DataManager.getBaseMenuItems(cuisine_id=cuisine_id) restaurants = DataManager.getRestaurants(cuisine_id=cuisine_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(cuisine_id=cuisine_id) return jsonify(Cuisine=cuisine.serialize, BaseMenuItems=[i.serialize for i in baseMenuItems], Restaurants=[i.serialize for i in restaurants], RestaurantMenuItems=\ [i.serialize for i in restaurantMenuItems])
def cuisines(): ''' Display all cuisines ''' cuisines = DataManager.getCuisines() client_login_session = getClientLoginSession() return render_template("Cuisines.html", cuisines=cuisines, client_login_session=client_login_session)
def users(): '''Serve information about all users ''' client_login_session = getClientLoginSession() users = DataManager.getUsers() return render_template('Users.html', users=users, client_login_session=client_login_session)
def deleteUser(user_id): '''Serve a form to delete a user ''' user = DataManager.getUser(user_id) if user.id != login_session['user_id']: flash("You do not have permission to delete this profile") return redirect(url_for('user', user_id=user.id)) client_login_session = getClientLoginSession() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) DataManager.deleteUser(user.id) flash("deleted " + user.name + " from " +\ "the database") # this is messy but needed because even though disconnect() -- which # deletes all of this information (confirmed with print statements) -- # has already run on "onsubmit" with submission of this form, # the login_session mysteriously still has all of this information del login_session['credentials'] del login_session['user_id'] del login_session['username'] del login_session['picture'] del login_session['email'] del login_session['picture_serve_type'] if 'gplus_id' in login_session: del login_session['gplus_id'] elif 'facebook_id' in login_session: del login_session['facebook_id'] return redirect(url_for('users')) return render_template('DeleteUser.html', user=user, hiddenToken=login_session['state'], client_login_session=client_login_session)
def restaurantJSON(restaurant_id): '''JSON endpoint for a single restaurant Includes all of the restaurant's menu items ''' restaurant = DataManager.getRestaurant(restaurant_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(restaurant_id=restaurant_id) return jsonify(Restaurant=restaurant.serialize, RestaurantMenuItems=[i.serialize for i in restaurantMenuItems])
def restaurant(restaurant_id): '''Serve info about a restaurant ''' client_login_session = getClientLoginSession() restaurant = DataManager.getRestaurant(restaurant_id) owner = DataManager.getUser(restaurant.user_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(restaurant_id=restaurant_id) cuisine = DataManager.getCuisine(cuisine_id=restaurant.cuisine_id) picture = DataManager.getPicture(restaurant.picture_id) numMenuItems = len(restaurantMenuItems) if numMenuItems > 0: mostExpensiveItem = restaurantMenuItems[0] for item in restaurantMenuItems: if item.price > mostExpensiveItem.price: mostExpensiveItem = item mostExpensiveItem.price =\ Decimal(mostExpensiveItem.price).\ quantize(Decimal('0.01')) mostExpensiveItem.price =\ Decimal(mostExpensiveItem.price).\ quantize(Decimal('0.01')) else: mostExpensiveItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=-1) mostExpensiveItem.name = 'N/A' mostExpensiveItem.price = 'N/A' return render_template('Restaurant.html', restaurant=restaurant, numMenuItems=numMenuItems, mostExpensiveItem=mostExpensiveItem, cuisine=cuisine, picture=picture, owner=owner, client_login_session=client_login_session)
def restaurantJSON(restaurant_id): '''JSON endpoint for a single restaurant Includes all of the restaurant's menu items ''' restaurant = DataManager.getRestaurant(restaurant_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(restaurant_id=restaurant_id) return jsonify( Restaurant=restaurant.serialize, RestaurantMenuItems=[i.serialize for i in restaurantMenuItems])
def restaurants(): '''Serve info about all of the restaurants ''' client_login_session = getClientLoginSession() cuisines = DataManager.getCuisines() numRestaurants = 0 # get restaurants labeled with user or non-user # sectioned by cuisine cuisineToRestaurantsDict = {} for cuisine in cuisines: cuisineToRestaurantsDict[cuisine.id] = {} cuisineToRestaurantsDict[cuisine.id]['cuisine'] = cuisine restaurants = DataManager.\ getRestaurants(cuisine_id=cuisine.id) restaurantDicts = {} for restaurant in restaurants: numRestaurants += 1 restaurantDict = {} restaurantDict['restaurant'] = restaurant if (isLoggedIn() and restaurant.user_id == login_session['user_id']): restaurantDict['ownership'] = 'user' else: restaurantDict['ownership'] = 'non-user' restaurantDicts[restaurant.id] = restaurantDict cuisineToRestaurantsDict[cuisine.id]['restaurants'] = \ restaurantDicts return render_template("Restaurants.html", cuisineToRestaurantsDict=cuisineToRestaurantsDict, numRestaurants=numRestaurants, client_login_session=client_login_session)
def deleteRestaurantMenuItem(restaurant_id, restaurantMenuItem_id): '''Serve a form to delete a restaurant menu item ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to delete this item") return redirect(url_for('restaurantMenu', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() restaurantMenuItem = DataManager.\ getRestaurantMenuItem(restaurantMenuItem_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) restaurantMenuItemName = restaurantMenuItem.name DataManager.\ deleteRestaurantMenuItem(restaurantMenuItem_id=\ restaurantMenuItem_id) flash("removed item " + str(restaurantMenuItem_id) + " (" + \ restaurantMenuItemName + ") from the menu and database") return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: return render_template('DeleteRestaurantMenuItem.html', restaurant=restaurant, restaurantMenuItem=restaurantMenuItem, hiddenToken=login_session['state'], client_login_session=client_login_session)
def editRestaurant(restaurant_id): '''Serve form to add a restaurant menu item to a restaurant's menu ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to edit this restaurant") return redirect(url_for('restaurant', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() restaurant = DataManager.getRestaurant(restaurant_id) cuisines = DataManager.getCuisines() picture = DataManager.getPicture(restaurant.picture_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) oldName = restaurant.name oldCuisine = DataManager.\ getCuisine(cuisine_id=restaurant.cuisine_id) oldPicture = DataManager.getPicture(restaurant.picture_id) newName = validateUserInput(request.form['name'], 'name', 'edit', 'restaurant', maxlength=100) validCuisineIDs = {} for cuisine in cuisines: validCuisineIDs[str(cuisine.id)] = True # for 'do not change' validCuisineIDs['-2'] = True newCuisine_id = validateUserInput(request.form['cuisineID'], 'cuisine_id', 'edit', 'restaurant', columnNameForMsg='cuisine', oldInput=str(oldCuisine.id), validInputs=validCuisineIDs) if newCuisine_id == '-2': newCuisine_id = None providedPic = validateUserPicture('edit', 'restaurant', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300) if providedPic is not None: # delete the old pic if it was an upload and new is a link # or save the new pic if it was an upload if (providedPic['serve_type'] == 'link' and oldPicture.serve_type == 'upload'): path = app.config['UPLOAD_FOLDER'] + '/' + oldPicture.text os.remove(path) flash("deleted old uploaded pic") elif providedPic['serve_type'] == 'upload': picfilename = 'restaurant' + str(restaurant_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) providedPic['text'] = picfilename # edit the pic DataManager.editPicture(restaurant.picture_id, newText=providedPic['text'], newServe_Type=providedPic['serve_type']) flash("updated base menu item picture") # we edited the pic directly, no need to include here DataManager.editRestaurant(restaurant.id, newName=newName, newCuisine_id=newCuisine_id) restaurant = DataManager.getRestaurant(restaurant_id) if newName is not None: flash("changed " + restaurant.name + "'s (ID " + \ str(restaurant.id) + ") name from '" + oldName + \ "' to '" + newName + "'") if newCuisine_id is not None: flash("changed " + restaurant.name + "'s (ID " + \ str(restaurant.id) + ") cuisine") return redirect(url_for('restaurant', restaurant_id=restaurant_id)) else: return render_template('EditRestaurant.html', restaurant=restaurant, cuisines=cuisines, hiddenToken=login_session['state'], picture=picture, client_login_session=client_login_session)
def cuisinesJSON(): '''JSON endpoint for all cuisines ''' cuisines = DataManager.getCuisines() return jsonify(Cuisines=[i.serialize for i in cuisines])
def baseMenuItemsJSON(): '''JSON endpoint for all base menu items ''' baseMenuItems = DataManager.getBaseMenuItems() return jsonify(BaseMenuItems=[i.serialize for i in baseMenuItems])
def cuisine(cuisine_id): '''Serve cuisine info page ''' cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) restaurants = DataManager.\ getRestaurants(cuisine_id=cuisine_id) baseMenuItems = DataManager.\ getBaseMenuItems(cuisine_id=cuisine_id) restaurantMenuItems = DataManager.\ getRestaurantMenuItems(cuisine_id=cuisine_id) sectionedBaseMenuItems = DataManager.\ getBaseMenuItems(cuisine_id=cuisine_id, byMenuSection=True) client_login_session = getClientLoginSession() # get restaurants labeled with user or non-user restaurantDicts = {} for restaurant in restaurants: restaurantDict = {} restaurantDict = {'restaurant': restaurant} if (isLoggedIn() and restaurant.user_id == login_session['user_id']): restaurantDict['ownership'] = 'user' else: restaurantDict['ownership'] = 'non-user' restaurantDicts[restaurant.id] = restaurantDict # get the base items with their children # in format that plays nice with jinja # and labels things user or non-user # and also calculate some data about the items mostExpensiveBaseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=-1) mostExpensiveRestaurantMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=-1) sectionedBaseItemsWithChildren = {} for section, baseItemList in sectionedBaseMenuItems.iteritems(): sectionedBaseItemsWithChildren[section] = {} for baseItem in baseItemList: baseItemID = baseItem.id if baseItem.price > mostExpensiveBaseMenuItem.price: mostExpensiveBaseMenuItem = baseItem childrenItems = DataManager.\ getRestaurantMenuItems(baseMenuItem_id=baseItem.id) children = {} for item in childrenItems: if item.price > mostExpensiveRestaurantMenuItem.price: mostExpensiveRestaurantMenuItem = item itemRestaurant = DataManager.\ getRestaurant(item.restaurant_id) itemUserID = itemRestaurant.user_id child = {} child['item'] = item if (isLoggedIn() and itemUserID == login_session['user_id']): child['ownership'] = 'user' else: child['ownership'] = 'non-user' children[item.id] = child itemWithChildren = {'item':baseItem, 'children':children} sectionedBaseItemsWithChildren[section][baseItem.id] = \ itemWithChildren # this means there were no items, so display N/A if mostExpensiveRestaurantMenuItem.id == -1: mostExpensiveRestaurantMenuItem.name = "N/A" mostExpensiveRestaurantMenuItem.price = "N/A" mostExpensiveRestaurantMenuItem.restaurant_id = "N/A" else: # display nicely mostExpensiveRestaurantMenuItem.price = \ Decimal(mostExpensiveRestaurantMenuItem.price).\ quantize(Decimal('0.01')) if mostExpensiveBaseMenuItem.id == -1: mostExpensiveBaseMenuItem.name = "N/A" mostExpensiveBaseMenuItem.price = "N/A" else: mostExpensiveBaseMenuItem.price = \ Decimal(mostExpensiveBaseMenuItem.price).\ quantize(Decimal('0.01')) return render_template("Cuisine.html", cuisine=cuisine, mostExpensiveBaseMenuItem=mostExpensiveBaseMenuItem, mostExpensiveRestaurantMenuItem=mostExpensiveRestaurantMenuItem, restaurantDicts=restaurantDicts, sectionedBaseItemsWithChildren=sectionedBaseItemsWithChildren, client_login_session=client_login_session)
def addRestaurant(): '''Serve form to add a restaurant ''' client_login_session = getClientLoginSession() cuisines = DataManager.getCuisines() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) validCuisineIDs = {} for cuisine in cuisines: validCuisineIDs[str(cuisine.id)] = True cuisine_id = validateUserInput(request.form['cuisineID'], 'cuisine_id', 'create', 'restaurant', columnNameForMsg='cuisine', required=True, validInputs=validCuisineIDs) if cuisine_id is None: return redirect(url_for('restaurants')) name = validateUserInput(request.form['name'], 'name', 'create', 'restaurant', maxlength=100, required=True) if name is None: return redirect(url_for('restaurants')) providedPic = validateUserPicture('create', 'restaurant', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300, required=True) if providedPic is None: return redirect(url_for('restaurants')) picture_id = DataManager.addPicture( text=providedPic['text'], serve_type=providedPic['serve_type']) restaurant_id = DataManager.addRestaurant( name=name, cuisine_id=cuisine_id, user_id=login_session['user_id'], picture_id=picture_id) # if pic was uploaded, now that we know item id, # save actual file for serving and set the name in the database if providedPic['serve_type'] == 'upload': picfilename = 'restaurant' + str(restaurant_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) DataManager.editPicture(picture_id=picture_id, newText=picfilename) DataManager.populateMenuWithBaseItems(restaurant_id) flash("restaurant '" + name + "' added to the database!") return redirect(url_for('restaurants')) else: return render_template('AddRestaurant.html', cuisines=cuisines, hiddenToken=login_session['state'], client_login_session=client_login_session)
def menuSectionsJSON(): '''JSON endpoint for menu sections ''' menuSections = DataManager.getMenuSections() return jsonify(MenuSections=[i.serialize for i in menuSections])
def userJSON(user_id): '''JSON endpoint for a single user ''' user = DataManager.getUser(user_id) return jsonify(User=user.serialize)
def usersJSON(): '''JSON endpoint for all users ''' users = DataManager.getUsers() return jsonify(Users=[i.serialize for i in users])
def pictureJSON(picture_id): '''JSON endpoint for a single picture ''' picture = DataManager.getPicture(picture_id) return jsonify(Picture=picture.serialize)
def picturesJSON(): '''JSON endpoint for all pictures ''' pictures = DataManager.getPictures() return jsonify(Pictures=[i.serialize for i in pictures])
def user(user_id): '''Serve a user's profile ''' client_login_session = getClientLoginSession() user = DataManager.getUser(user_id=user_id) picture = DataManager.getPicture(user.picture_id) userThings = DataManager.getUserThings(user.id) # calculate some stats to show loggedInStats = {} numRestaurants = 0 mostExpensiveRest = None mostExpensiveRestAvgPrice = None leastExpensiveRest = None leastExpensiveRestAvgPrice = None numMenuItems = 0 mostExpensiveMenuItem = None leastExpensiveMenuItem = None for restaurantID in userThings: numRestaurants = numRestaurants + 1 numItemsThisRestaurant = 0 totalRestaurantPrices = 0 thisRestaurantAvgItemPrice = None for menuSectionName in userThings[restaurantID]['items']: for item in userThings[restaurantID]['items'][menuSectionName]: item.price = Decimal(item.price).\ quantize(Decimal('0.01')) numMenuItems = numMenuItems + 1 numItemsThisRestaurant = numItemsThisRestaurant + 1 if mostExpensiveMenuItem is None: mostExpensiveMenuItem = item elif item.price > mostExpensiveMenuItem.price: mostExpensiveMenuItem = item elif (leastExpensiveMenuItem is None and numMenuItems > 1): leastExpensiveMenuItem = item elif (item.price < leastExpensiveMenuItem.price and numMenuItems > 1): leastExpensiveMenuItem = item totalRestaurantPrices = totalRestaurantPrices + item.price if numItemsThisRestaurant > 0: thisRestaurantAvgItemPrice = \ totalRestaurantPrices/numItemsThisRestaurant else: thisRestaurantAvgItemPrice = None if (mostExpensiveRest is None and numItemsThisRestaurant > 0): mostExpensiveRest = \ userThings[restaurantID]['restaurant'] mostExpensiveRestAvgPrice = thisRestaurantAvgItemPrice elif thisRestaurantAvgItemPrice > mostExpensiveRestAvgPrice: mostExpensiveRest = \ userThings[restaurantID]['restaurant'] mostExpensiveRestAvgPrice = thisRestaurantAvgItemPrice elif (leastExpensiveRest is None and numRestaurants > 1 and numItemsThisRestaurant > 0): leastExpensiveRest = \ userThings[restaurantID]['restaurant'] leastExpensiveRestAvgPrice = thisRestaurantAvgItemPrice elif (thisRestaurantAvgItemPrice < \ leastExpensiveRestAvgPrice and numRestaurants > 1): leastExpensiveRest = \ userThings[restaurantID]['restaurant'] leastExpensiveRestAvgPrice = thisRestaurantAvgItemPrice if mostExpensiveRestAvgPrice: mostExpensiveRestAvgPrice = \ Decimal(mostExpensiveRestAvgPrice).\ quantize(Decimal('0.01')) if leastExpensiveRestAvgPrice: leastExpensiveRestAvgPrice = \ Decimal(leastExpensiveRestAvgPrice).\ quantize(Decimal('0.01')) if (isLoggedIn() and login_session['user_id'] == user.id): # could put stats in a loginStats dictionary return render_template('PrivateUserProfile.html', user=user, picture=picture, userThings=userThings, numRestaurants=numRestaurants, numMenuItems=numMenuItems, mostExpensiveRest=mostExpensiveRest, mostExpensiveRestAvgPrice=mostExpensiveRestAvgPrice, leastExpensiveRest=leastExpensiveRest, leastExpensiveRestAvgPrice=leastExpensiveRestAvgPrice, mostExpensiveMenuItem=mostExpensiveMenuItem, leastExpensiveMenuItem=leastExpensiveMenuItem, client_login_session=client_login_session) else: return render_template('PublicUserProfile.html', user=user, picture=picture, userThings=userThings, numRestaurants=numRestaurants, numMenuItems=numMenuItems, client_login_session=client_login_session)
def editUser(user_id): '''Serve a form to edit a user ''' user = DataManager.getUser(user_id) if user.id != login_session['user_id']: flash("You do not have permission to edit this profile") return redirect(url_for('user', user_id=user.id)) client_login_session = getClientLoginSession() picture = DataManager.getPicture(user.picture_id) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) oldName = user.name oldPicture = picture newName = validateUserInput(request.form['name'], 'name', 'edit', 'user', maxlength=30, oldInput=oldName, usernameFormat=True) providedPic = validateUserPicture('edit', 'user', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300) if providedPic is not None: # delete the old pic if it was an upload and new is a link # or save the new pic if it was an upload if (providedPic['serve_type'] == 'link' and oldPicture.serve_type == 'upload'): path = app.config['UPLOAD_FOLDER']+'/'+oldPicture.text os.remove(path) flash("deleted old uploaded pic") elif providedPic['serve_type'] == 'upload': picfilename = 'user' + str(user_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) providedPic['text'] = picfilename # edit the pic DataManager.editPicture(user.picture_id, newText=providedPic['text'], newServe_Type=providedPic['serve_type']) picture = DataManager.getPicture(user.picture_id) login_session['picture'] = picture.text login_session['picture_serve_type'] = picture.serve_type flash("updated your picture!") # we edited the pic directly, no need to include here DataManager.editUser(user.id, newName=newName) if newName is not None: login_session['username'] = newName flash("changed your username from '" + oldName +\ "' to '"+newName+"'") return redirect(url_for('user', user_id=user.id)) else: return render_template('EditUser.html', user=user, picture=picture, hiddenToken=login_session['state'], client_login_session=client_login_session)
def addRestaurantMenuItem(restaurant_id): '''Serve form to add a restaurant menu item to a restaurant's menu ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to add an item to "+\ " this restaurant's menu") return redirect(url_for('restaurantMenu', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() baseMenuItems = DataManager.getBaseMenuItems() for item in baseMenuItems: pic = DataManager.getPicture(item.picture_id) item.picText = pic.text item.picServeType = pic.serve_type menuSections = DataManager.getMenuSections() # display nicely for item in baseMenuItems: item.price = Decimal(item.price).quantize(Decimal('0.01')) if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) validBaseMenuItemIDs = {} for item in baseMenuItems: validBaseMenuItemIDs[str(item.id)] = True baseMenuItem_id = validateUserInput(request.form['baseMenuItemID'], 'baseMenuItem_id', 'create', 'restaurant menu item', columnNameForMsg='base menu item', validInputs=validBaseMenuItemIDs, required=True) if baseMenuItem_id is None: return redirect( url_for('restaurantMenu', restaurant_id=restaurant_id)) baseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=baseMenuItem_id) # if a field is provided, use it, else use the base menu item's attr if request.form['name']: name = validateUserInput(request.form['name'], 'name', 'create', 'restaurant menu item', maxlength=80, required=True) if name is None: return redirect( url_for('restaurantMenu', restaurant_id=restaurant_id)) else: name = baseMenuItem.name if request.form['description']: description = validateUserInput(request.form['description'], 'description', 'create', 'restaurant menu item', maxlength=250, required=True) if description is None: return redirect( url_for('restaurantMenu', restaurant_id=restaurant_id)) else: description = baseMenuItem.description if request.form['price']: price = validateUserInput(request.form['price'], 'price', 'create', 'restaurant menu item', maxlength=20, required=True, priceFormat=True) if price is None: return redirect( url_for('restaurantMenu', restaurant_id=restaurant_id)) else: price = baseMenuItem.price if request.files['pictureFile'] or request.form['pictureLink']: providedPic = validateUserPicture( 'create', 'restaurant menu item', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300, required=True) if providedPic is None: return redirect( url_for('restaurantMenu', restaurant_id=restaurant_id)) else: picture_id = DataManager.\ addPicture(text=providedPic['text'], serve_type=providedPic['serve_type']) else: picture_id = baseMenuItem.picture_id validMenuSectionIDs = {} for menuSection in menuSections: validMenuSectionIDs[str(menuSection.id)] = True # if this is somehow None, # the add function defaults to base item's attr menuSection_id = validateUserInput(request.form['menuSectionID'], 'menuSection_id', 'create', 'restaurant menu item', columnNameForMsg='menu section', validInputs=validMenuSectionIDs, required=True) restaurantMenuItem_id = DataManager.\ addRestaurantMenuItem(name=name, restaurant_id=restaurant_id, description=description, price=price, baseMenuItem_id=baseMenuItem_id, picture_id=picture_id, menuSection_id=menuSection_id) # if pic was uploaded, now that we know item id, # save actual file for serving and set the name in the database if (request.files['pictureFile'] and providedPic['serve_type'] == 'upload'): picfilename = 'restaurantMenuItem' + str(restaurantMenuItem_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) DataManager.editPicture(picture_id=picture_id, newText=picfilename) flash("menu item '" + name + "' added to the menu!") return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: return render_template('AddRestaurantMenuItem.html', restaurant=restaurant, baseMenuItems=baseMenuItems, menuSections=menuSections, hiddenToken=login_session['state'], client_login_session=client_login_session)
def editRestaurantMenuItem(restaurant_id, restaurantMenuItem_id): '''Serve a form to edit a restaurant menu item ''' restaurant = DataManager.getRestaurant(restaurant_id) if restaurant.user_id != login_session['user_id']: flash("You do not have permission to edit this item") return redirect(url_for('restaurantMenu', restaurant_id=restaurant.id)) client_login_session = getClientLoginSession() user_id = restaurant.user_id restaurantMenuItem = DataManager.\ getRestaurantMenuItem(restaurantMenuItem_id) restaurantMenuItem.price = Decimal(restaurantMenuItem.price).\ quantize(Decimal('0.01')) picture = DataManager.getPicture(restaurantMenuItem.picture_id) menuSections = DataManager.getMenuSections() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) oldName = restaurantMenuItem.name oldDescription = restaurantMenuItem.description oldPrice = restaurantMenuItem.price oldMenuSection_id = restaurantMenuItem.menuSection_id oldPicture = picture newName = validateUserInput(request.form['name'], 'name', 'edit', 'restaurant menu item', maxlength=80, oldInput=oldName) newDescription = validateUserInput(request.form['description'], 'description', 'edit', 'restaurant menu item', maxlength=250, oldInput=oldDescription) newPrice = validateUserInput(request.form['price'], 'price', 'edit', 'restaurant menu item', maxlength=20, oldInput=oldPrice, priceFormat=True) validMenuSectionIDs = {} for menuSection in menuSections: validMenuSectionIDs[str(menuSection.id)] = True # for 'do not change' validMenuSectionIDs['-1'] = True newMenuSection_id = validateUserInput(request.form['menuSection'], 'menuSection_id', 'edit', 'restaurant menu item', columnNameForMsg='menu section', oldInput=str(oldMenuSection_id), validInputs=validMenuSectionIDs) if newMenuSection_id == '-1': newMenuSection_id = None providedPic = validateUserPicture('edit', 'restaurant menu item', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300) if providedPic is not None: # delete the old pic if it was an upload and new is a link # or save the new pic if it was an upload if (providedPic['serve_type'] == 'link' and oldPicture.serve_type == 'upload'): path = app.config['UPLOAD_FOLDER'] + '/' + oldPicture.text os.remove(path) flash("deleted old uploaded pic") elif providedPic['serve_type'] == 'upload': picfilename = 'restaurantMenuItem' + \ str(restaurantMenuItem_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) providedPic['text'] = picfilename # edit the pic DataManager.editPicture(restaurantMenuItem.picture_id, newText=providedPic['text'], newServe_Type=providedPic['serve_type']) flash("updated restaurant menu item picture") # we edited the pic directly, no need to include here DataManager.editRestaurantMenuItem(restaurantMenuItem.id, newName=newName, newDescription=newDescription, newPrice=newPrice, newMenuSection_id=newMenuSection_id) if newName is not None: flash("changed restaurant menu item " + \ str(restaurantMenuItem.id) + \ "'s name from '" + oldName + "' to '" + newName + "'") if newDescription is not None: flash("changed restaurant menu item " + \ str(restaurantMenuItem.id) + \ "'s description from '"+ oldDescription + "' to '" + \ newDescription + "'") if newPrice is not None: flash("changed restaurant menu item " + \ str(restaurantMenuItem.id) + \ "'s price from '" + str(oldPrice) + "' to '" + \ str(newPrice) + "'") if newMenuSection_id is not None: flash("changed the restaurant menu item's menu section") return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: return render_template('EditRestaurantMenuItem.html', restaurant=restaurant, restaurantMenuItem=restaurantMenuItem, menuSections=menuSections, hiddenToken=login_session['state'], picture=picture, client_login_session=client_login_session)
def restaurantsJSON(): '''JSON endpoint for all restaurants ''' restaurants = DataManager.getRestaurants() return jsonify(Restaurants=[i.serialize for i in restaurants])
def editBaseMenuItem(cuisine_id, baseMenuItem_id): '''Serve form to edit a base menu item ''' client_login_session = getClientLoginSession() baseMenuItem = DataManager.\ getBaseMenuItem(baseMenuItem_id=baseMenuItem_id) cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) baseMenuItem.price = Decimal(baseMenuItem.price).quantize(Decimal('0.01')) picture = DataManager.getPicture(baseMenuItem.picture_id) menuSections = DataManager.getMenuSections() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) oldName = baseMenuItem.name oldDescription = baseMenuItem.description oldPrice = baseMenuItem.price oldPicture = picture oldMenuSection_id = baseMenuItem.menuSection_id newName = validateUserInput(request.form['name'], 'name', 'edit', 'base menu item', maxlength=80, unique=True, oldInput=oldName) newDescription = validateUserInput(request.form['description'], 'description', 'edit', 'base menu item', maxlength=250, oldInput=oldDescription) newPrice = validateUserInput(request.form['price'], 'price', 'edit', 'base menu item', maxlength=20, priceFormat=True, oldInput=str(oldPrice)) validMenuSectionIDs = {} for menuSection in menuSections: validMenuSectionIDs[str(menuSection.id)] = True # for 'do not change' validMenuSectionIDs['-1'] = True newMenuSection_id = validateUserInput(request.form['menuSection'], 'menuSection_id', 'edit', 'base menu item', columnNameForMsg='menu section', oldInput=str(oldMenuSection_id), validInputs=validMenuSectionIDs) if newMenuSection_id == '-1': newMenuSection_id = None providedPic = validateUserPicture('edit', 'base menu item', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300) if providedPic is not None: # delete the old pic if it was an upload and new is a link # or save the new pic if it was an upload if (providedPic['serve_type'] == 'link' and oldPicture.serve_type == 'upload'): path = app.config['UPLOAD_FOLDER']+'/'+oldPicture.text os.remove(path) flash("deleted old uploaded pic") elif providedPic['serve_type'] == 'upload': picfilename = 'baseMenuItem' + str(baseMenuItem_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) providedPic['text'] = picfilename # edit the pic DataManager.editPicture(baseMenuItem.picture_id, newText=providedPic['text'], newServe_Type=providedPic['serve_type']) flash("updated base menu item picture") # we edited the pic directly, no need to include here DataManager.editBaseMenuItem(baseMenuItem.id, newName=newName, newDescription=newDescription, newPrice=newPrice, newMenuSection_id=newMenuSection_id) if newName is not None: flash("changed name from '"+oldName+"' to '"+newName+"'") if newDescription is not None: flash("changed description from '"+ oldDescription + "' to '" + \ newDescription + "'") if newPrice is not None: flash("changed price from '" + str(oldPrice) + "' to '" + \ str(newPrice) + "'") if newMenuSection_id is not None: flash("changed menu section") return redirect(url_for('baseMenuItem', cuisine_id=cuisine_id, baseMenuItem_id=baseMenuItem_id)) else: return render_template("EditBaseMenuItem.html", baseMenuItem=baseMenuItem, cuisine=cuisine, hiddenToken=login_session['state'], picture=picture, menuSections=menuSections, client_login_session=client_login_session)
def addBaseMenuItem(cuisine_id): '''Serve form to add a base menu item ''' client_login_session = getClientLoginSession() cuisine = DataManager.getCuisine(cuisine_id=cuisine_id) menuSections = DataManager.getMenuSections() if request.method == 'POST': if isCSRFAttack(request.form['hiddenToken']): return redirect(url_for('restaurantManagerIndex')) name = validateUserInput(request.form['name'], 'name', 'create', 'base menu item', maxlength=80, required=True, unique=True, tableName='BaseMenuItem') if name is None: return redirect(url_for('cuisine', cuisine_id=cuisine.id)) description = \ validateUserInput(request.form['description'], 'description', 'create', 'base menu item', maxlength=250, required=True) if description is None: return redirect(url_for('cuisine', cuisine_id=cuisine.id)) price = validateUserInput(request.form['price'], 'price', 'create', 'base menu item', maxlength=20, required=True, priceFormat=True) if price is None: return redirect(url_for('cuisine', cuisine_id=cuisine.id)) validMenuSectionIDs = {} for menuSection in menuSections: validMenuSectionIDs[str(menuSection.id)] = True menuSection_id = validateUserInput(request.form['menuSection'], 'menuSection_id', 'create', 'base menu item', columnNameForMsg='menu section', required=True, validInputs=validMenuSectionIDs) if menuSection_id is None: return redirect(url_for('cuisine', cuisine_id=cuisine.id)) providedPic = validateUserPicture('create', 'base menu item', file=request.files['pictureFile'], link=request.form['pictureLink'], maxlength=300, required=True) if providedPic is None: return redirect(url_for('cuisine', cuisine_id=cuisine.id)) picture_id = DataManager.addPicture(text=providedPic['text'], serve_type=providedPic['serve_type']) baseMenuItem_id = DataManager.\ addBaseMenuItem(name, cuisine_id, description=description, price=price, menuSection_id=menuSection_id, picture_id=picture_id) # if pic was uploaded, now that we know item id, # save actual file for serving and set the name in the database if providedPic['serve_type'] == 'upload': picfilename = 'baseMenuItem' + str(baseMenuItem_id) request.files['pictureFile'].save(os.path.\ join(app.config['UPLOAD_FOLDER'], picfilename)) DataManager.editPicture(picture_id=picture_id, newText=picfilename) flash("added '" + name + "' to " + cuisine.name + \ "'s base menu") return redirect(url_for('cuisine', cuisine_id=cuisine.id)) else: return render_template('AddBaseMenuItem.html', cuisine=cuisine, menuSections=menuSections, hiddenToken=login_session['state'], client_login_session=client_login_session)