def vegan_meals(assignedMealIds, usersMedicalCondition): vegan_plan_count = meal_plan_count.vegan breakfast = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Breakfast'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Breakfast']] lunch = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Lunch'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Lunch']] dinner = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Dinner'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Dinner']] snacks = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Snacks'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Snacks']] return list(breakfast) + list(lunch) + list(dinner) + list(snacks)
def vegetarian_meals(assignedMealIds, usersMedicalCondition): # ****** Vegan Dishes ****** vegan_plan_count = meal_plan_count.vegetarian['vegan'] vega_breakfast = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Breakfast'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Breakfast']] vega_lunch = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Lunch'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Lunch']] vega_dinner = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Dinner'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Dinner']] vega_snacks = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegan'], course__in=['Snacks'], avoidableMedCond__nin=usersMedicalCondition)[:vegan_plan_count['Snacks']] vega_meals = list(vega_breakfast) + list(vega_lunch) + list(vega_dinner) + list(vega_snacks) # ****** Vegetarian Dishes ****** veget_plan_count = meal_plan_count.vegetarian['vegetarian'] veg_breakfast = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Breakfast'], avoidableMedCond__nin=usersMedicalCondition)[:veget_plan_count['Breakfast']] veg_lunch = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Lunch'], avoidableMedCond__nin=usersMedicalCondition)[:veget_plan_count['Lunch']] veg_dinner = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Dinner'], avoidableMedCond__nin=usersMedicalCondition)[:veget_plan_count['Dinner']] veg_snacks = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Snacks'], avoidableMedCond__nin=usersMedicalCondition)[:veget_plan_count['Snacks']] veg_meals = list(veg_breakfast) + list(veg_lunch) + list(veg_dinner) + list(veg_snacks) return vega_meals + veg_meals
def non_veg_meals(assignedMealIds, usersMedicalCondition): # ****** Vegetarian Dishes ****** veg_plan_count = meal_plan_count.non_veg['vegetarian'] veg_breakfast = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Breakfast'], avoidableMedCond__ne=usersMedicalCondition)[:veg_plan_count['Breakfast']] veg_lunch = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Lunch'], avoidableMedCond__ne=usersMedicalCondition)[:veg_plan_count['Lunch']] veg_dinner = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Dinner'], avoidableMedCond__ne=usersMedicalCondition)[:veg_plan_count['Dinner']] veg_snacks = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Vegetarian'], course__in=['Snacks'], avoidableMedCond__ne=usersMedicalCondition)[:veg_plan_count['Snacks']] veg_meals = list(veg_breakfast) + list(veg_lunch) + list(veg_dinner) + list(veg_snacks) print("Vege Meals : " + str(len(veg_meals))) # ****** Non-Vegetarian Dishes ****** nonveg_plan_count = meal_plan_count.non_veg['non_veg'] nonveg_breakfast = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Non-Vegetarian'], course__in=['Breakfast'], avoidableMedCond__ne=usersMedicalCondition)[:nonveg_plan_count['Breakfast']] nonveg_lunch = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Non-Vegetarian'], course__in=['Lunch'], avoidableMedCond__ne=usersMedicalCondition)[:nonveg_plan_count['Lunch']] nonveg_dinner = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Non-Vegetarian'], course__in=['Dinner'], avoidableMedCond__ne=usersMedicalCondition)[:nonveg_plan_count['Dinner']] nonveg_snacks = Meal.objects(id__nin=assignedMealIds, foodPreference__in=['Non-Vegetarian'], course__in=['Snacks'], avoidableMedCond__ne=usersMedicalCondition)[:nonveg_plan_count['Snacks']] nonveg_meals = list(nonveg_breakfast) + list(nonveg_lunch) + list(nonveg_dinner) + list(nonveg_snacks) print("Non-Veg Meals : " + str(len(nonveg_meals))) return veg_meals + nonveg_meals
def test_meal_create(self): DATETIME = datetime.now().replace(microsecond=0) meal = Meal.create(owner_user_id=self.user.id, text="Greatest Meal Ever", entry_datetime=DATETIME.isoformat(), calorie_count=9001) meal = Meal.get_by_id(meal.id) eq_(meal.owner_user_id, self.user.id) eq_(meal.text, "Greatest Meal Ever") eq_(meal.entry_datetime, DATETIME) eq_(meal.entry_time, DATETIME.time()) eq_(meal.entry_date, DATETIME.date()) eq_(meal.calorie_count, 9001)
def test_build_date_time_range_query__time_across_midnight(self): start_time = time(23).isoformat() end_time = time(1).isoformat() self.create_meal( entry_datetime=datetime.combine(date.today(), time(2)).isoformat()) self.create_meal(entry_datetime=datetime.combine( date.today(), time(1, 1)).isoformat()) self.create_meal( entry_datetime=datetime.combine(date.today() - timedelta( days=3), time(1)).isoformat()) self.create_meal( entry_datetime=datetime.combine(date.today() - timedelta( days=3), time(0, 59)).isoformat()) self.create_meal(entry_datetime=datetime.combine( date.today(), time(23, 1)).isoformat()) self.create_meal(entry_datetime=datetime.combine( date.today(), time(23)).isoformat()) self.create_meal( entry_datetime=datetime.combine(date.today() + timedelta( days=3), time(22, 59)).isoformat()) self.create_meal(entry_datetime=datetime.combine( date.today(), time(0, 0)).isoformat()) query = Meal.build_date_time_range_query(self.user.id, start_time=start_time, end_time=end_time) eq_(len(query.all()), 5) eq_(len(Meal.query.all()), 8)
def addMealData(): meals_array = request.get_json() queryList = [] for meal in meals_array: try: meal = Meal.objects.get(name=meal['name']) except DoesNotExist as dne: data = AttrDict(meal) newMeal = Meal( name=data.name, foodPreference=data.foodPreference, cuisine=data.cuisine, dietType=[dt for dt in data.dietType], idealMedCond=[imc for imc in data.idealMedCond], avoidableMedCond=[amc for amc in data.avoidableMedCond], course=data.course, calories=data.calories, nutritionInfo=data.nutritionInfo, ingredients=data.ingredients, directions=data.directions, photoURL=Config.s3URL + data.photoURL ) queryList.append(newMeal) try: meals = Meal.objects.insert(queryList, load_bulk=True) return jsonify(meals), status.HTTP_200_OK except Exception as e: return jsonify({'Error': format(e)}), status.HTTP_400_BAD_REQUEST
def test_create_meal(self): ENTRY_DATETIME = "Mon, 26 Nov 2018 04:00:00 -0000" response = self.test_client.post( '/api/meals', headers={'Authorization': 'Bearer ' + self.user_token.jwt_token}, json={ 'meal': { 'owner_user_id': self.user.id, 'text': "yummy yummy", 'entry_datetime': ENTRY_DATETIME, 'calories': 400, } }) eq_(response.status_code, 200) self.assert_json( response.json, { 'meal': { 'id': response.json['meal']['id'], 'owner_user_id': self.user.id, 'text': "yummy yummy", 'entry_datetime': ENTRY_DATETIME, 'calories': 400, } }) meal = Meal.get_by_id(response.json['meal']['id']) ok_(meal) eq_(format_datetime(meal.entry_datetime), ENTRY_DATETIME)
def test_meal_get_by_id(self): meal = self.create_meal() meal.save() queried_meal = Meal.get_by_id(meal.id) eq_(queried_meal.id, meal.id) eq_(queried_meal.owner_user_id, meal.owner_user_id) eq_(queried_meal.text, meal.text) eq_(queried_meal.calorie_count, meal.calorie_count) eq_(queried_meal.entry_datetime, meal.entry_datetime) meal.delete() meal.save() queried_meal = Meal.get_by_id(meal.id) assert queried_meal is None
def load_test_data(test_date): user = User('test123', 'abc123') user.save() user = User.query.all()[0] meal = Meal('Test meal', 'Meal desciption', test_date, b'009383615') meal.save() meal = Meal.query.all()[0] availability = Availability(test_date, meal.id) availability.save() availability = Availability.query.all()[0] ticket1 = Ticket(test_date, user.id, availability.id) ticket1.save() ticket2 = Ticket(test_date, user.id, availability.id) ticket2.save()
def deleteCollection(name): if name == 'users': print('Dropping user collection') User.drop_collection() elif name == 'meals': print('Dropping meal collection') Meal.drop_collection() elif name == 'meds': print('Dropping medicine collection') Medicine.drop_collection() elif name == 'symptoms': print('Dropping symptom collection') Symptom.drop_collection() else: print('Wrong collection name provided: {}'.format(name)) return 'Wrong collection name provided: {}'.format(name), 400 return jsonify('{} collection deleted'.format(name)), 200
def deleteMeal(meal_id): try: delMeal = Meal.objects(id=meal_id).get() delMeal.delete() return jsonify({'status': 'Meal deleted successfully'}), status.HTTP_200_OK except DoesNotExist as dne: return 'Meal not found - {}'.format(dne.with_traceback), status.HTTP_400_BAD_REQUEST except Exception as e: return jsonify({'Error': format(e)}), status.HTTP_500_INTERNAL_SERVER_ERROR
def create_meal(self, **options): props = dict( owner_user_id=self.user.id, text="Greatest Meal Ever", entry_datetime=datetime.now().isoformat(), calorie_count=9001, ) props.update(options) return Meal.create(**props)
def _create_meal(self, **overrides): params = { 'owner_user_id': self.user.id, 'text': "yummy yummy", 'entry_datetime': '2018-11-25T09:00:00', 'calorie_count': 400, } params.update(overrides) return Meal.create(**params)
def get(self, meal_id): meal = Meal.get_by_id(meal_id) if meal is None: abort(404) if meal.owner_user_id != g.user.id and not g.user.is_admin: abort(401) return meal
def saved_meal_post(): #don't use the reequest.args.get('user') to avoid malicious user. user = current_user #request.args.get('meal_name') gets the value associated #with the query string 'meal_name' #ex: /add_saved_meal_post?meal_name=breakfast selected_foods = request.args.get('selected_foods') meal_name = request.args.get('meal_name') #think about keys and values. look at the flask documentation for requesting #keys and values. #do not use 'if not selected_foods' because the id of 0 evaluates to False. if selected_foods == None or selected_foods == "": return "" #need to first strip leading and trailing commas to create a clean and valid list #of strings separated by commas. selected_foods = selected_foods.strip(",").split(',') #create an instance of the Meal model #creating a Meal object by calling the Meal constructor. #can set any column values as identified in the models, in this case models/meal.py #creating a name for the saved_meal saved_meal = Meal(name=meal_name) #loop through the food_ids to save the selected foods as a meal. #selected_foods is a list. for food_id in selected_foods: #making an instance of the Class MealFoodAssociation meal_food_association = MealFoodAssociation() #query the FoodLogFoodAssociation table to get the row (the matching association) that has the specific #food_id. food_log_food_association = session.query(FoodLogFoodAssociation).get( int(food_id)) #access the attribute of the variable which is an instance of the class #copy the attributes from the food_log_food_association to the #attribute mealfoodassociation #integer primary keys are automatically filled in. meal_food_association.food_NDB_No = food_log_food_association.food_NDB_No meal_food_association.unit_Seq = food_log_food_association.unit_Seq meal_food_association.quantity = food_log_food_association.quantity #add the saved food to the Meal saved_meal.foods.append(meal_food_association) #append the saved _meal to the list user.meals #save it once. Take it out of the for loop. user.meals.append(saved_meal) #save the meal session.add(saved_meal) session.commit() #returning an empty string is saying that the code works. return ""
def getMeals(userId): try: user = User.objects(id=userId).get() newMealsFlag = False assignedMealIds = [] if user['mealAssigned']: for meal in user['mealAssigned']: assignedMealIds.append(meal['id']) if user and user['mealExpiry']: ''' Check for meal plan expiry''' tzinf = tz.tz.tzoffset('TZONE', int(user['timeZone']) / 1000) # creating the user's timezone by localCurrentTime = utils.default_tzinfo(datetime.now(), tzinf) # datetime.now(tz=tzinf) # creating local time # Check if meal plan has expired if localCurrentTime > utils.default_tzinfo(user['mealExpiry'], tzinf): newMealsFlag = True else: try: meals = Meal.objects(id__in=assignedMealIds) return jsonify(meals), status.HTTP_200_OK except Exception as e: print('Error while getting meals ' + format(e)) return jsonify({'stat': 'Some error occurred'}), status.HTTP_500_INTERNAL_SERVER_ERROR else: newMealsFlag = True # ******* New Meal Assignment Starts Here ******* if newMealsFlag: usersMedicalCondition = user['medicalCondition'] generated_plan = [] if user['foodPreference'] == 'Vegan': generated_plan = vegan_meals(assignedMealIds, usersMedicalCondition) print("Vegan Count : " + str(len(generated_plan))) elif user['foodPreference'] == 'Vegetarian': generated_plan = vegetarian_meals(assignedMealIds, usersMedicalCondition) print("Vege Count : " + str(len(generated_plan))) else: generated_plan = non_veg_meals(assignedMealIds, usersMedicalCondition) print("Non-Veg Count : " + str(len(generated_plan))) # ****** Assigning generated plan to the user ****** tzinf = tz.tz.tzoffset('TZONE', int(user['timeZone']) / 1000) localCurrentTime = utils.default_tzinfo(datetime.now(), tzinf) # datetime.now(tz=tzinf) expiryTime = localCurrentTime + timedelta(days=1) mealExpiry = utils.default_tzinfo(expiryTime.replace(hour=5, minute=0, second=0, microsecond=0), tzinf) #user['mealAssigned'] = generated_plan user.modify(mealExpiry=mealExpiry,mealAssigned=generated_plan) return jsonify(user['mealAssigned']), status.HTTP_200_OK except Exception as e: print("Error occurred in meal assignment : " + format(e)) return format(e), status.HTTP_500_INTERNAL_SERVER_ERROR
def filterMeals(type, foodPref, userId): try: user = User.objects(id=userId).get() usersMedicalCondition = user['medicalCondition'] foodPrefArr = [] exstMealSrchFlag = False srchArr = [type]; vegLimit = 10; nonVegLimit = 0; if type == 'Snack' or 'Soup' or 'Juice': exstMealSrchFlag = True if foodPref == 'Non-Vegetarian' or foodPref == 'None': foodPrefArr = ['Vegan', 'Vegetarian'] vegLimit = 5 nonVegLimit = 5 else: foodPrefArr = [foodPref] if exstMealSrchFlag: res = [] mealAssigned = [meal['id'] for meal in user['mealAssigned']] mealQuery = Meal.objects(id__in=mealAssigned, course__in=srchArr) res = list(mealQuery) return jsonify(res), status.HTTP_200_OK else: vegQuery = Meal.objects(foodPreference__in=foodPrefArr, course__in=srchArr, avoidableMedCond__ne=usersMedicalCondition)[:vegLimit] if foodPref == 'Non-Vegetarian' or foodPref == 'None': nonVegQuery = Meal.objects(foodPreference__in=['Non-Vegetarian'], course__in=srchArr, avoidableMedCond__ne=usersMedicalCondition)[:nonVegLimit] res = list(vegQuery) + list(nonVegQuery) else: res = vegQuery return jsonify(res), status.HTTP_200_OK except Exception as e: print('Error occurred while filtering : ' + format(e)) return jsonify({'error': format(e)}), status.HTTP_400_BAD_REQUEST
def post(self): # who are you? current_user = g.user params = request.get_json() if params is None: abort(400, message="invalid params") props = params['meal'].copy() props['calorie_count'] = props['calories'] props['owner_user_id'] = current_user.id new_meal = Meal.create(**props) return new_meal
def test_should_return_just_meal_name(self): department_name = "Bar" meals_category_name = "Example Category #" meal_name = "Plov" mock_department = mock.Mock(spec=Department) mock_department.name = department_name mock_meals_category = mock.Mock(spec=MealsCategory) mock_meals_category.department = mock_department mock_meals_category.name = meals_category_name mock_instance = mock.Mock(spec=Meal) mock_instance.category = mock_meals_category mock_instance.name = meal_name self.assertEqual(Meal.__str__(mock_instance), meal_name)
def test_update_meal(self): meal = self._create_meal() old_meal_text = meal.text old_entry_datetime = meal.entry_datetime old_calories = meal.calorie_count old_owner_user_id = meal.owner_user_id new_owner_user_id = 5 new_text = "Yabadaba doo" new_entry_datetime = "Tue, 27 Nov 2018 04:00:00 -0000" new_calories = 808 assert old_meal_text != new_text assert old_entry_datetime != new_entry_datetime assert old_calories != new_calories assert meal.owner_user_id != new_owner_user_id update_payload = self._create_meal_request_payload( id=meal.id, owner_user_id=new_owner_user_id, text=new_text, entry_datetime=new_entry_datetime, calories=new_calories, ) response = self.test_client.put( '/api/meals/{}'.format(meal.id), headers={'Authorization': 'Bearer ' + self.user_token.jwt_token}, json=update_payload) expected_payload = self._create_meal_request_payload( **update_payload['meal']) expected_payload['meal']['owner_user_id'] = old_owner_user_id eq_(response.status_code, 200) self.assert_json(response.json, expected_payload) meal_record = Meal.get_by_id(meal.id) eq_(meal_record.text, new_text) eq_(meal_record.calorie_count, new_calories) eq_(meal_record.owner_user_id, old_owner_user_id) self.assert_datetime(meal_record.entry_datetime, new_entry_datetime)
def get(self): current_user = g.user page = int(request.args.get('p', 1)) keys = [ 'start_datetime', 'end_datetime', 'start_time', 'end_time', ] query_options = {key: request.args.get(key, None) for key in keys} query = Meal.build_date_time_range_query(owner_user_id=current_user.id, **query_options) result = query.paginate(page, per_page=10, error_out=False) return {'meals': result.items}
def test_meal_query_by_datetime_and_time_range(self): start_datetime = parse('2018-11-25T09:00:00') end_datetime = parse('2018-11-27T18:00:00') start_time = time(11) end_time = time(15) test_date = parse('2018-11-24T09:00:00').date() for d in range(4): datetimes = [ datetime.combine(test_date + relativedelta(days=d), time(0, 0)), datetime.combine(test_date + relativedelta(days=d), time(10, 59)), datetime.combine(test_date + relativedelta(days=d), time(11, 0)), datetime.combine(test_date + relativedelta(days=d), time(12, 59)), datetime.combine(test_date + relativedelta(days=d), time(14, 59)), datetime.combine(test_date + relativedelta(days=d), time(15, 0)), datetime.combine(test_date + relativedelta(days=d), time(15, 59)), datetime.combine(test_date + relativedelta(days=d), time(23, 59)) ] for idx, data_datetime in enumerate(datetimes): self.create_meal(text="Test Meal {}-{}".format(d + 1, idx + 1), entry_datetime=data_datetime.isoformat()) result = Meal.build_date_time_range_query( self.user.id, start_datetime=start_datetime.isoformat(), end_datetime=end_datetime.isoformat(), start_time=start_time.isoformat(), end_time=end_time.isoformat()) eq_(len(result.all()), 12) eq_(len(Meal.query.all()), 32)
def updateMeal(meal_id): data = AttrDict(request.get_json()) try: updatedMeal = Meal.objects(id=meal_id).update_one( name=data.name, foodPreference=data.foodPreference, cuisine=data.cuisine, dietType=[dt for dt in data.dietType], idealMedCond=[imc for imc in data.idealMedCond], avoidableMedCond=[amc for amc in data.avoidableMedCond], course=data.course, calories=data.calories, nutritionInfo=data.nutritionInfo, ingredients=data.ingredients, directions=data.directions, photoURL=data.photoURL ) return jsonify(updatedMeal), status.HTTP_200_OK except Exception as e: return jsonify({'Error': format(e)}), status.HTTP_500_INTERNAL_SERVER_ERROR
def test_meal_update(self): meal = self.create_meal() new_text = "It could be any meal" new_entry_datetime = datetime.now() + timedelta(days=5) new_entry_datetime = new_entry_datetime.replace(microsecond=0) new_calories = 9090 meal.update( text=new_text, entry_datetime=new_entry_datetime.isoformat(), calorie_count=new_calories, ) queries_meal = Meal.get_by_id(meal.id) eq_(queries_meal.owner_user_id, meal.owner_user_id) eq_(queries_meal.text, new_text) eq_(queries_meal.entry_datetime, new_entry_datetime) eq_(queries_meal.calorie_count, new_calories)
def put(self, meal_id): properties_to_update = request.get_json() if properties_to_update is None: abort(400) meal = Meal.get_by_id(meal_id) if meal is None: abort(404) if meal.owner_user_id != g.user.id and not g.user.is_admin: abort(401) props = properties_to_update['meal'].copy() props['calorie_count'] = props['calories'] meal.update(**props) meal.save() return meal
def addNewMeal(): data = AttrDict(request.get_json()) try: newMeal = Meal( name=data.name, foodPreference=data.foodPreference, cuisine=data.cuisine, dietType=[dt for dt in data.dietType], idealMedCond=[imc for imc in data.idealMedCond], avoidableMedCond=[amc for amc in data.avoidableMedCond], course=data.course, calories=data.calories, nutritionInfo=data.nutritionInfo, ingredients=data.ingredients, directions=data.directions, photoURL=Config.s3URL + data.photoURL ).save() return jsonify(newMeal), status.HTTP_200_OK except NotUniqueError: return jsonify({'stat:': 'Meal already exists.'}), status.HTTP_400_BAD_REQUEST except Exception as e: return jsonify({'Error': 'Error while saving meal - {}'.format(e)}), status.HTTP_500_INTERNAL_SERVER_ERROR
def test_build_date_time_range_query__datetime(self): start_datetime = parse('2018-11-26T23:01:52') end_datetime = parse('2018-11-27T23:01:52') self.create_meal( entry_datetime=parse('2018-11-26T23:59:59').isoformat()) self.create_meal( entry_datetime=parse('2018-11-26T00:00:00').isoformat()) self.create_meal( entry_datetime=parse('2018-11-27T00:00:00').isoformat()) self.create_meal( entry_datetime=parse('2018-11-27T23:01:52').isoformat()) self.create_meal( entry_datetime=parse('2018-11-27T23:59:59').isoformat()) self.create_meal( entry_datetime=parse('2018-11-28T00:59:59').isoformat()) query = Meal.build_date_time_range_query( self.user.id, start_datetime=start_datetime.isoformat(), end_datetime=end_datetime.isoformat()) eq_(len(query.all()), 3) eq_(len(Meal.query.all()), 6)
def get(self, id): return Meal.get(id), 200
def get(self, id): """ Get meal by id endpoint """ return Meal.get(id), 200