def submit_order(request): trackID = int(uuid.uuid4().time_low) + int(uuid.uuid4().time_mid) user = request.user.id userObj = User.objects.get(pk=user) myuser = MyUser.objects.get(user=userObj) emp = Employee.objects.get(user=myuser) branch = emp.branch # TODO real branch is_permanent = True is_changable = False date = datetime.datetime.now().date() time = datetime.datetime.now().time() has_place = False order = Order(trackID=trackID, is_changable=is_changable, is_permanent=is_permanent, branch=branch, date=date, time= time, place=has_place) order.save() foods_order = [] for f_type in FoodType.objects.all(): val = request.POST.get(f_type.name, 0) if val != '' and val != 0: food = Food(food_type=f_type, order=order, number=val, status=False) food.save() foods_order.append(food) for food in foods_order: cooks = [] for c in CookAbility.objects.all(): if c.ability == food.food_type: cooks.append(c.cook) cook = choose_cook(cooks) foodcook = FoodCook(cook=cook, food=food, done=False) foodcook.save()
def submit_periodic_order(start_date, time, weekdays, number_of_weeks, food_dic, user): d = start_date trackID = int(uuid.uuid4().time_low) + int(uuid.uuid4().time_mid) branch = None order = Order(trackID=trackID, is_changable=True, is_permanent=False, branch=branch, date=start_date, time= time, place=True, user=user) str_days = ','.join([str(i) for i in weekdays]) p_order = PeriodicOrder(weeks_num=str_days, number_of_weeks=number_of_weeks) p_order.save() order.periodic = p_order order.save() # TODO weekdays format weekdays_arr = weekdays print(weekdays) for day in weekdays_arr: d = start_date for i in range(0, int(number_of_weeks)): print(d.weekday()) # if( d.weekday() != int(day)) while d.weekday() != int(day): d += datetime.timedelta(days=1) print(d) for key, val in food_dic: food = Food(food_type=key, number=val, order=order,status=False) food.save()
def insert_dish_page(request): """Insert dish into database""" validate(instance=request.body, schema=food_schema) body = json.loads(request.body) invalid = Food.field_validate(body) if invalid: return JsonResponse(invalid) food = Food.add_dish(body) return JsonResponse(model_to_json(food))
def approve_food(model_admin, request, queryset): """ Approve of PendingFood record and insert it into Food collection, or updates the existing record in Food collection that corresponds to this PendingFood record. Sends a notification email to the restaurant email for each successful approval. """ count = 0 total = 0 wrong_status = False for f in queryset: total += 1 food = Food(**model_to_json(f)) old_food = Food.objects.filter(_id=f._id).first() restaurant = PendingRestaurant.objects.filter(_id=f.restaurant_id) if restaurant.exists() and f.status == Status.Pending.name: count += 1 restr = restaurant.first() owner_prefer_names = restr.owner_preferred_name food_name = f.name email = restr.email send_approval_email(owner_prefer_names, email, food_name, 'food') # If there's already an approved food record in Food collection # check if the food's picture is oudated, by comparing the url # to the url in the PendingFood's picture field. If they don't match # delete the approved food record's picture from google cloud bucket if old_food: if old_food.picture != f.picture: delete(old_food.picture) food.status = Status.Approved.name save_and_clean(food) else: wrong_status = True if count > 1: messages.success( request, "Successfully approved " + str(count) + " food profiles.") queryset.update(status=Status.Approved.name) elif count == 1: link = reverse("admin:restaurant_pendingfood_change", args=[f._id]) msg = format_html( "Successfully approved restaurant profile for <a href='{}' target='_blank' rel='noopener'>{}</a>", link, f.name) messages.success(request, msg) queryset.update(status=Status.Approved.name) elif wrong_status: messages.success( request, "The restaurant this dish belongs to does not exist, or the dish status if not 'Pending'" ) else: if total > 1: msg = "The selected food profiles have been approved already." else: msg = "The selected food profile has been approved already." messages.error(request, msg)
def submit_order_customer(user, branch, date, time, dic): trackID = int(uuid.uuid4().time_low) + int(uuid.uuid4().time_mid) # branch = Branch.objects.all()[0] # is_permanent = True # is_changable = False # date = datetime.datetime.now().date() # time = datetime.datetime.now().time() has_place = True order = Order(trackID=trackID, is_changable=True, is_permanent=False, branch=branch, date=date, time= time, place=has_place, user=user) order.save() for food, val in dic: food = Food(food_type=food, order=order, number=val, status=False) food.save()
def save_model(self, request, obj, form, change): """ Overridden save method so corresponding restaurant object can update its categories field; also checks to make sure signature dish and popular dish limits are obeyed """ food = obj restaurant = Restaurant.objects.filter(_id=food.restaurant_id).first() if (food.category == 'Signature Dish' and Food.objects.filter(restaurant_id=food.restaurant_id, category='Signature Dish').count() == 1): messages.set_level(request, messages.ERROR) messages.error(request, 'A restaurant can only have 1 signature dish.') elif (food.category == 'Popular Dish' and Food.objects.filter(restaurant_id=food.restaurant_id, category='Popular Dish').count() == 6): if food._id not in list( Food.objects.filter(restaurant_id=food.restaurant_id, category='Popular Dish').values_list( '_id', flat=True)): messages.set_level(request, messages.ERROR) messages.error( request, 'A restaurant can only have up to 6 popular dishes.') else: food.clean() food.clean_fields() food.save() restaurant.categories = Food.get_all_categories(food.restaurant_id) restaurant.clean() restaurant.clean_fields() restaurant.save()
def handle(self, *args, **options): seed = self.seeder gen_dict = self.seed_dict invalid_randomizers = seed.clean(gen_dict) #need to store the inserted restaurant/name pairs for auto-tagging #stored in the format (name, restaurant_id) dishes = [] #generate numentries records in the database for _ in range(options['numentries']): #separate document for non-random fields in seeding process Document = { 'picture' : "https://storage.googleapis.com/default-assets/no-image.png" } rand_Document = seed.gen_rand_dict(gen_dict) Document.update(rand_Document) Food.add_dish(Document) ManualTag.auto_tag_food(Food.objects.get(restaurant_id = Document['restaurant_id'], name = Document['name'])._id)
def save(self, request, commit=True): data = self.cleaned_data food = Food() food.name = data['name'] food.description = data['description'] food.price = data['price'] food.menu = Restaurant.objects.filter(manager=request.user).first().menu food.save()
def seed(self): food_list = """ Gentle-Fried Mint & Orange Turkey Stewed Fennel & Garlic Mutton Stewed Hazelnut Crocodile Deep-Fried Potatoes & Lobster Seared Mustard & Thyme Gratin Dried Nuts & Taco Nutmeg and Chocolate Custard Licorice and Ginger Tarte Tatin Mango Snacks White Chocolate Cobbler Pickled Vanilla Mammoth Tenderized Nuts & Bear Smoked Parsnip & Pear Tuna Pressure-Fried Chilli Crab Deep-Fried Parmesan Kebabs Infused White Wine Winter Greens Licorice and Avocado Jelly Date and Passion Fruit Trifle Papaya Pie Cocoa Crispies Basted Ginger & Honey Pigeon Shallow-Fried Saffron Chicken Deep-Fried Dark Beer Alligator Pressure-Cooked Honey-Coated Herring Deep-Fried Carrot & Violet Spring Vegetables Cured Walnuts & Omelette Mint and Raspberry Tart Gooseberry and Walnut Sundae Cocoa Toast Coffee Pie Get food names Gentle-Fried Lime-Coated Horse Thermal-Cooked Sweet & Savory Mutton Pan-Fried Honey & Almond Alligator Basted Chilli Herring Tenderized Curry of Bruschetta Pressure-Fried Black Pepper Lasagne Banana and Chocolate Whip Honey and Chestnut Genoise Pistachio Toast Lemon Strudel """.strip().split("\n") description = """Lorem ipsum dolor sit amet, et mea legere blandit abhorreant, nam exerci accusam elaboraret no. Mea te minimum sensibus. Cu qui commodo omnesque percipit. Per munere nullam temporibus ea. Nec mentitum antiopam no. Ad duis doming indoctum his. Eos ex fabulas singulis, natum labores periculis mea ex. Quo libris apeirian eu. Per solet aperiri ea. Eligendi hendrerit nam id, eos eu alienum antiopam intellegebat, eam viderer denique cu. Homero equidem eu pro. Mel nostro constituam ad, ius ut modus cetero verear. Ad nam eros omnis, mea ei offendit molestiae. Vix adhuc possit inciderint ad, forensibus posidonium sed in, in mei decore vivendo volumus. No per labore nemore. Eos ei molestie percipit maiestatis, oratio audire molestiae ne est, dolore assentior prodesset sed ei. Ea tibique fastidii quo, sit accusata reformidans ei. Elitr primis an quo, quem contentiones eu pro. Eius cotidieque reformidans ex est, rebum expetenda has at. Ius nulla inermis disputando an, idque meliore sit et. Agam reque pericula ne mea, pro postea graeco debitis ne, mei habemus gubergren cotidieque id. Timeam eleifend cu sed, vero labitur per in. Vim ei laoreet minimum officiis, pri alterum gloriatur eu. Id erat debitis comprehensam vix, vix ea dicit dissentiet, cu vix ipsum luptatum. Ad eros ridens malorum eam.""".strip() for food_name in food_list: food = Food() food.name = food_name.strip() food.description = description food.price = random.uniform(100, 1000) food.menu = random.choice(Menu.objects.all()) food.save()
def test_edit_dish_valid(self, mock_get): """ Test if dish document is properly updated """ id = Food.objects.get(name="foodB")._id request = self.factory.post('/api/restaurant/dish/edit/', { "_id": str(id), "name": "foodB2", "description": "nutter butter", "picture": MOCK_VALID_LINK, "price": "10.99" }, content_type='application/json') actual = json.loads(view_response.edit_dish_page(request).content) expected = Food(_id=str(id), name="foodB2", restaurant_id="restB", description="nutter butter", picture=MOCK_VALID_LINK, price='10.99') self.assertDictEqual(actual, model_to_dict(expected))
def edit_dish_page(request): """Update Dish data""" # validation validate(instance=request.body, schema=food_schema) body = json.loads(request.body) invalid = Food.field_validate(body) if invalid is not None: return JsonResponse(invalid) dish = Food.objects.get(_id=body["_id"]) restaurant = Restaurant.objects.get(_id=dish.restaurant_id) if should_add_category(body, dish.category, restaurant): # add category if new add_cateogory(dish.category, restaurant) # edit model edit_model(dish, body, dish_editable) dish = save_and_clean(dish) # if category has been edited, may remove old category if category_is_changed(body) and category_exists(body['category'], restaurant._id): remove_category(body['category', restaurant]) return JsonResponse(model_to_json(dish))
def test_insert_food_valid(self, mock_get): """ Test if food is properly inserted into the database """ request = self.factory.post('/api/restaurant/dish/insert/', { "name": 'foodC', 'restaurant_id': "111111111111111111111111", 'description': "descripC", "price": '10.99', 'specials': "", 'category': '' }, content_type="application/json") actual = json.loads(view_response.insert_dish_page(request).content) expected = Food( _id=actual['_id'], name="foodC", restaurant_id="111111111111111111111111", description="descripC", picture= 'https://storage.googleapis.com/default-assets/no-image.png', price='10.99', category='') self.assertDictEqual(model_to_dict(expected), actual)
def get_restaurants_and_food_data(): r = requests.get('https://api.food.jumia.com.gh/api/v5/vendors', headers={"X-FP-API-KEY": "HTML5"}) restaurants = r.json()["data"]["items"] for restaurant in restaurants: if restaurant['name'] == 'Hellofood Test Restaurant 2' or restaurant['name'] == 'Hellofood Test Restaurant 2': print('test restaurants avoid') else: existing_restaurant = get_object_or_none(Restaurant, name=restaurant['name']) if not existing_restaurant: rest_obj = Restaurant() rest_obj.name = restaurant['name'] rest_obj.restaurant_crawl_link = restaurant['web_path'] rest_obj.description = restaurant['description'] rest_obj.city = restaurant['city']['name'] rest_obj.address = '{} \n {}'.format(restaurant['address'], restaurant['address_line2'] if restaurant['address_line2'] else '') rest_obj.latitude = restaurant['latitude'] rest_obj.longitude = restaurant['longitude'] logo_path = restaurant['logo'].split('%s/') if len(logo_path) == 3: img = download_image(logo_path[2]) try: filename = '{}.{}'.format(restaurant['name'].replace(' ', '_'), img.format) rest_obj.logo = filename tempfile = img tempfile_io = BytesIO() # Will make a file-like object in memory that you can then save tempfile.save(tempfile_io, format=img.format) rest_obj.logo.save(filename, ContentFile(tempfile_io.getvalue()), save=False) # Set save=False otherwise you will have a looping save method except: print("Error trying to save model: saving image failed: ") pass if restaurant['cms_content']['vendor_wide_logo']: try: img = download_image(restaurant['cms_content']['vendor_wide_logo']) filename = '{}_cover.{}'.format(restaurant['name'].replace(' ', '_'), img.format) rest_obj.cover_photo = filename tempfile = img tempfile_io = BytesIO() # Will make a file-like object in memory that you can then save tempfile.save(tempfile_io, format=img.format) rest_obj.cover_photo.save(filename, ContentFile(tempfile_io.getvalue()), save=False) # Set save=False otherwise you will have a looping save method except: print("Error trying to save model: saving image failed: ") pass rest_obj.save() food_path = requests.get(restaurant['web_path']) soup = BeautifulSoup(food_path.text, 'html.parser') food_items = soup.find_all('article', class_='product-variation') food_name_parent = None for food_item in food_items: the_food_name = None food_name = food_item.find('span', class_='mrs') right_text_food = food_item.find('div', class_='has-text-right') if food_name and right_text_food: right_text_food_select = right_text_food.find('span', class_='has-ellipsis') food_name_parent = food_name.get_text() the_food_name = '{} {}'.format(food_name.get_text(), right_text_food_select.get_text()) elif right_text_food and not food_name: right_text_food_select = right_text_food.find('span', class_='has-ellipsis') the_food_name = '{} {}'.format(food_name_parent, right_text_food_select.get_text()) elif food_name: food_name = food_name.get_text() food_name_parent = food_name the_food_name = food_name food_description = food_item.find('p', class_='dsc').get_text() if food_item.find('p', class_='dsc') else '' food_price = food_item.find('span', class_='mlxs').get_text() existing_food = get_object_or_none(Food, name=the_food_name) if not existing_food: food_obj = Food() food_obj.name = the_food_name.strip() food_obj.description = food_description.strip() food_obj.price = food_price food_obj.restaurant = rest_obj if not existing_restaurant else existing_restaurant food_obj.save()
def get_dish_by_restaurant_page(request): """Retrieve all dishes from a restaurant""" rest_id = request.GET.get('restaurant_id') dishes = Food.get_by_restaurant(rest_id) response = {'Dishes': models_to_json(dishes)} return JsonResponse(response)
def get(self, request, rest_id): """ Retrieve all approved dishes from a restaurant """ dishes = Food.get_by_restaurant(rest_id) response = {'Dishes': models_to_json(dishes)} return JsonResponse(response)