def createrest(request):
    if request.method == 'POST':
        form = RestaurantCreateForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = form.save()
            restaurant = Restaurant()
            restaurant.user = user
            restaurant.business_name = data['business_name']
            restaurant.address = data['address']
            restaurant.city = data['city']
            restaurant.state = data['state']
            restaurant.zip_code = data['zip_code']
            restaurant.phone_number = data['phone_number']
            restaurant.save()
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password1'])
            login(request, user)

            return HttpResponseRedirect(reverse('restaurant_profile',
                                                args=[user.restaurant.id]))

    else:
        form = RestaurantCreateForm()

    return render(request, 'registration/restaurant_registration.html',
                  {'form': form})
Beispiel #2
0
def add_restaurant(request):
    error = []
    if 'ok' in request.POST:
        name = request.POST['name']
        phone_number = request.POST['phone']
        address = request.POST['address']
        opentime = request.POST['opentime']

        if not name:
            error.append('請輸入餐廳名稱')
        if not phone_number:
            error.append('請輸入電話')
        if not address:
            error.append('請輸入地址')
        if not opentime:
            error.append('請輸入營業時間')
        if not error:
            r = Restaurant(name=name,
                           phone_number=phone_number,
                           address=address,
                           opentime=opentime)
            r.save()
            name = ''
            phone_number = ''
            address = ''
            opentime = ''
            return HttpResponseRedirect('/restaurant')
    return render_to_response('restaurant/add_restaurant.html', locals())
Beispiel #3
0
def add_restaurant(request):
	user = request.user
	if not user.is_authenticated:
		return HttpResponseRedirect(reverse('Login'))
	userprofile = UserProfile.objects.get(user = user)
	if request.method == 'POST':
		name = request.POST['name']
		if name:
			r = Restaurant(name = name)
			try:
				r.save()
			except:
				return HttpResponseRedirect(reverse('addRestaurant'))
			r.user.add(user)
			base = userprofile.base
			array = userprofile.array
			if not base or not array:
				return HttpResponseRedirect(reverse('init'))
			base = json.loads(base)
			array = json.loads(array)
			base = add_arr(base, name)
			array = add_arr(array, name)
			userprofile.base = base
			userprofile.array = array
			userprofile.save()
			return HttpResponseRedirect(reverse('viewAll'))
	return render_to_response('restaurant/add.html')
 def test_has_no_menu(self):
     user = User(username='******', email='*****@*****.**', password='******')
     user.save()
     rest = Restaurant(business_name="I love donuts", email='*****@*****.**',
                       address='1122 City Center', city='LV', state='NV',
                       zip_code='89178', phone_number='555-1212', user=user)
     rest.save()
     self.assertFalse(rest.has_menu(), "No Menu")
Beispiel #5
0
def resetApp(request):
    rules = App.getCR(App)
    rules.calculationCheck = False
    rules.periodCounter = rules.calculationPeriod
    rules.save()
    Calculation.objects.all().delete()
    Restaurant.resetServiceCounters(Restaurant)
    flag = False
    context = Context({'flag':flag,'grading':True})
    return render(request,'home.html',context)
 def test_has_menu(self):
     user = User(username='******', email='*****@*****.**', password='******')
     user.save()
     rest = Restaurant(business_name="I love donuts", email='*****@*****.**',
                       address='1122 City Center', city='LV', state='NV',
                       zip_code='89178', phone_number='555-1212', user=user)
     rest.save()
     menu = FoodItem(restaurant=rest, name='Sprinkle Donut',
                     price='2.99', description='your favorite sprinkle donut',
                     category='D')
     menu.save()
     self.assertTrue(rest.has_menu(), "Yes, there's a Menu")
def insert_restaurant_page(request):
    """Insert new restaurant into database"""
    validate(instance=request.body, schema=restaurant_schema)
    body = json.loads(request.body)
    invalid = Restaurant.field_validate(body)
    if invalid:
        return JsonResponse(invalid)
    try:
        restaurant = Restaurant.insert(body)
        return JsonResponse(model_to_json(restaurant))
    except ValueError:
        return HttpResponseBadRequest('duplicate email')
def edit_restaurant_page(request):
    """Update restaurant data"""
    validate(instance=request.body, schema=restaurant_schema)
    body = json.loads(request.body)
    invalid = Restaurant.field_validate(body)
    if invalid:  # exit if invalid body
        return JsonResponse(invalid)
    restaurant = Restaurant.get(body["restaurant_id"])
    edit_model(restaurant, body, restaurant_editable)
    if address_changed(body):
        update_model_geo(restaurant, body['address'])
    restaurant = save_and_clean(restaurant)
    return JsonResponse(model_to_json(restaurant))
Beispiel #9
0
    def post(self, request):
        form = AddRestaurantForm(request.POST, request.FILES)
        data = dict(form=form)
        if form.is_valid():
            data = form.cleaned_data

            restaurant = Restaurant()
            manager = Manager()

            restaurant.name = data['name']
            restaurant.description = data['description']
            restaurant.profile_image = request.FILES['profile_image']

            manager.email = data['manager_email']
            chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"

            password = "".join([chars[ord(c) % len(chars)] for c in urandom(8)])
            manager.set_password(password)
            manager.is_confirmed = True
            manager.save()

            manager.send_email("Login details - Restaurant booking online",
                               "Your login details :\n E-mail : " + manager.email +
                               "\n Password : "******"\n You can login now " +
                               get_current_site(request).domain + "\n Restaurant booking online")

            restaurant.manager = manager
            restaurant.category = data['category']

            restaurant.save()

        return render(request, self.template_name, dict(form=form))
    def seed(self):
        restaurant_names = [
            'El Celler de Can Roca',
            'Osteria Francescana',
            'Noma',
            'Central',
            'Eleven Madison Park',
            'Mugaritz',
            'Dinner by Heston Blumenthal',
            'Narisawa',
            'D.O.M.',
            'Gaggan',
        ]
        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 i in range(len(restaurant_names)):
            restaurant_name = restaurant_names[i]

            restaurant = Restaurant()
            restaurant.name = restaurant_name
            restaurant.description = description
            restaurant.manager = Manager.objects.filter(email="*****@*****.**" % str(i)).first()
            restaurant.category = random.choice(RestaurantCategory.objects.all())

            menu = Menu()
            menu.save()
            restaurant.menu = menu

            restaurant.save()
Beispiel #11
0
def populateDB(restaurants):
    for name, properties in restaurants.iteritems():
        # Extract dictionary
        address = ", ".join(properties['address'])
        description = properties['description']
        
        phone = properties['phone']
        website = properties['website']
        email = properties['email']        
        
        loc = (float(properties['longitude']), float(properties['latitude']))
        
        # get image name only
        img = properties['image'].split('/')[-1].strip()
        
        categories = properties['categories']
        
        try:
            # Only add new restaurant
            Restaurant.objects.all().get(name=name)
        except: 
            # Create object in database
            r = Restaurant(name=name, address=address, description=description, 
                           phone=phone, website=website, email=email, img=img, 
                           pt=Point(loc))            
            r.save()
            print r
            
            i = 0
            while i < len(categories) and i < 2:
                catName = categories[i]
                catName = catName.upper()
                c = None
                try:
                    # Get existing category if exists
                    c = Category.objects.get(name=catName)
                except:
                    # Create new category
                    if i == 0:
                        c = Category(name=catName)  # First cat
                    else:
                        c = Category(name=catName, 
                                     super_cat=categories[0].upper())  # Sub cat
                    c.save()
                    print c
                r.categories.add(c)
                r.save()
                i += 1
    def handle(self, *args, **options):
        with transaction.atomic():
            Restaurant.objects.all().delete()

            with open(args[0], 'rb') as csvfile:
                reader = csv.DictReader(csvfile)

                for fake_id, row in enumerate(reader, 1):
                    if not row['Nom du restaurant']:
                        continue

                    print row['Nom du restaurant']
                    restaurant = Restaurant.create(
                        vegoresto_id=fake_id,
                        name=row['Nom du restaurant'].decode("Utf-8"),
                        address=row['Adresse compl\xc3\xa8te'].decode("Utf-8"),
                        website=row['Site web'].decode("Utf-8"),
                        contact=row['Votre email'].decode("Utf-8"),
                    )

                    restaurant.active = True
                    review = row['Plat v\xc3\xa9g\xc3\xa9tarien/v\xc3\xa9g\xc3\xa9talien que vous avez mang\xc3\xa9']
                    if len(review) < 10:
                        restaurant.review = "Il n'y a pas eu d'informations données par la personne ayant soumis le restaurant."
                    else:
                        restaurant.review = review

                    restaurant.save()
 def test_edit_restaurant_valid(self):
     """ Test if restaurant document is properly updated """
     id = Restaurant.objects.get(_id="111111111111111111111111")._id
     request = self.factory.post('/api/restaurant/edit/', {
         "restaurant_id": "111111111111111111111111",
         "name": "kfc2",
         "address": "211 Cambodia",
         "twitter": "",
         "instagram": "",
         "rating": "1.00"
     },
                                 content_type='application/json')
     view_response.edit_restaurant_page(request)
     actual = Restaurant.objects.get(_id="111111111111111111111111")
     expected = Restaurant(
         _id=id,
         name='kfc2',
         address='211 Cambodia',
         phone=6475040680,
         city='markham',
         email='*****@*****.**',
         cuisine='american',
         pricepoint='High',
         twitter='',
         instagram='',
         bio='Finger licking good chicken',
         GEO_location="{'lat': 11.5395535, 'lng': 104.916782}",
         external_delivery_link=MOCK_VALID_LINK,
         cover_photo_url=MOCK_VALID_LINK,
         logo_url=MOCK_VALID_LINK,
         rating='3.00',
         owner_name='Colonel Sanders',
         owner_story='i made chicken',
         owner_picture_url=MOCK_VALID_LINK)
     self.assertDictEqual(model_to_dict(actual), model_to_dict(expected))
Beispiel #14
0
    def handle(self, *args, **options):
        Restaurant.objects.all().delete()

        with open(args[0], 'rb') as csvfile:
            reader = csv.DictReader(csvfile)

            for row in reader:
                # clean up
                for k, v in row.items():
                    if v == '?' or len(v) < MIN_FIELD_LEN:
                        # discard
                        row[k] = None
                        continue

                    if k == 'Mail' and '@' not in v:
                        row[k] = None
                        continue

                    row[k] = v.strip()

                if not row['Nom'] or not row['Adresse']:
                    continue

                resto = Restaurant.create(random.randint(1, 2**32), row['Nom'],
                                          row['Adresse'], row['Site'],
                                          row['Téléphone'], row['Mail'],
                                          row['Personne de contact'],
                                          row['Suivi'],
                                          row['Personne responsable'])

                if row['Vg']:
                    tags = parse_vg_tags(row['Vg'])
                    if tags:
                        resto.tags.add(*tags)
                        resto.save()
    def __init__(self):
        #initialize the seeder dictionary with all necessary randomization functions
        seed = Seeder()
        gen_dict = {}

        #load the dishes and cuisines dictionaries as they are used for selecting random food and cuisine words during seeding
        dish_path = 'dishes.csv'
        self.dish_dictionary = load_dict.read(dish_path)
        cuisine_path = 'cuisine.csv'
        self.cuisine_dictionary = load_dict.read(cuisine_path)
        #retrieve list of all existing restaurants so that the inserted foods are randomly
        #associated with a restaurant
        self.restaurant_ids = []
        Restaurants = Restaurant.get_all()
        for restaurant in Restaurants['Restaurants']:
            self.restaurant_ids.append(restaurant['_id'])

        seed.add_randomizer("name",             lambda fake: fake.random_element(self.dish_dictionary), gen_dict)
        seed.add_randomizer("restaurant_id",    lambda fake: fake.random_element(self.restaurant_ids), gen_dict)
        seed.add_randomizer("description",      lambda fake: fake.random_element(self.dish_dictionary), gen_dict)
        #randomly generates a price from 1.00 - 99.99
        seed.add_randomizer("price",            lambda fake: fake.numerify(text = "!%.##"), gen_dict)
        #randomly generates a percentage string from 0% off - 99% off
        seed.add_randomizer("specials",         lambda fake: fake.numerify(text = "!#") + "% off", gen_dict)

        self.seed_dict = gen_dict
        self.seeder = seed
Beispiel #16
0
 def handle(self, *args, **options):
     seed = self.seeder
     gen_dict = self.seed_dict
     invalid_randomizers = seed.clean(gen_dict)
     #generate numentries records in the database
     for _ in range(options['numentries']):
         #separate document for non-random fields in seeding process
         Document = {
             'twitter': " ",
             'instagram': " ",
             'external_delivery_link': " ",
             'rating': "0.00"
         }
         rand_Document = seed.gen_rand_dict(gen_dict)
         Document.update(rand_Document)
         Restaurant.insert(Document)
    def handle(self, *args, **options):
        with transaction.atomic():
            Restaurant.objects.all().delete()

            with open(args[0], 'rb') as csvfile:
                reader = csv.DictReader(csvfile)

                for fake_id, row in enumerate(reader, 1):
                    if not row['Nom du restaurant']:
                        continue

                    print row['Nom du restaurant']
                    restaurant = Restaurant.create(
                        vegoresto_id=fake_id,
                        name=row['Nom du restaurant'].decode("Utf-8"),
                        address=row['Adresse compl\xc3\xa8te'].decode("Utf-8"),
                        website=row['Site web'].decode("Utf-8"),
                        contact=row['Votre email'].decode("Utf-8"),
                    )

                    restaurant.active = True
                    review = row[
                        'Plat v\xc3\xa9g\xc3\xa9tarien/v\xc3\xa9g\xc3\xa9talien que vous avez mang\xc3\xa9']
                    if len(review) < 10:
                        restaurant.review = "Il n'y a pas eu d'informations données par la personne ayant soumis le restaurant."
                    else:
                        restaurant.review = review

                    restaurant.save()
Beispiel #18
0
    def handle(self, *args, **options):
        Restaurant.objects.all().delete()

        with open(args[0], 'rb') as csvfile:
            reader = csv.DictReader(csvfile)

            for row in reader:
                # clean up
                for k, v in row.items():
                    if v == '?' or len(v) < MIN_FIELD_LEN:
                        # discard
                        row[k] = None
                        continue

                    if k == 'Mail' and '@' not in v:
                        row[k] = None
                        continue

                    row[k] = v.strip()

                if not row['Nom'] or not row['Adresse']:
                    continue

                resto = Restaurant.create(random.randint(1, 2**32), row['Nom'], row['Adresse'], row['Site'], row['Téléphone'], row['Mail'], row['Personne de contact'], row['Suivi'], row['Personne responsable'])

                if row['Vg']:
                    tags = parse_vg_tags(row['Vg'])
                    if tags:
                        resto.tags.add(*tags)
                        resto.save()
Beispiel #19
0
def direct(request):
    if request.method == 'POST':
        newUserName = request.POST.get('userName',None)
        user = User.objects.get(userName = newUserName)
        restaurants = Restaurant.getRestaurants(Restaurant)
        context = Context({'Restaurants' : restaurants,'user':user})
        return render(request,'gradingPoints.html',context)
Beispiel #20
0
    def setRestCounters(self):
        rules = App.getCR(App)
        period = rules.periodCounter
        totalPoints = 0
        for user in User.objects.all():
            totalPoints = period + totalPoints

        for rest in Restaurant.objects.filter(serviceStatus=True):
            points = Points.objects.filter(restaurant=rest)
            for point in points:
                serviceCounter = (point.point / totalPoints) * 100
                intServiceCounter = int(serviceCounter)
                if rest.serviceCounter == 0:
                    rest.serviceCounter = intServiceCounter
                    rest.save()

        Restaurant.serviceCounters(Restaurant)
        rules.save()
def get_restaurant_page(request):
    """retrieve restaurant by id"""
    _id = request.GET.get('_id')

    restaurant = Restaurant.get(_id)
    if restaurant:
        return JsonResponse(model_to_json(restaurant))
    else:
        return JsonResponse({})
Beispiel #22
0
 def setUp(self):
     self.now = '2019-01-01 12:00:00.000000+00:00'
     self.restaurant = Restaurant(
         name='군내치킨',
         owner='박군내',
         title='군내치킨-서초점',
         tel='1234',
         min_order_price=10000,
         order_way='현장 결제',
         origin='닭:국내산',
         delivery_charge=2000,
         info='군내나지만 맛있습니다.',
         type='요기요 등록 음식점',
         img='media/restaurant/chicken.png',
         estimated_delivery_time=self.now,
         operation_start_hour=self.now,
         operation_end_hour=self.now,
     )
     self.restaurant.save()
     self.category = self.restaurant.category.create(name='1인분 주문')
     self.category.save()
def save_restaurants(restaurant_df, inspection_df):
    for index, row in inspection_df.iterrows():
        try:
            b_id = None
            if Restaurant.objects.filter(
                    restaurant_name=row["restaurantname"],
                    business_address=row["businessaddress"],
                    postcode=row["postcode"],
            ).exists():
                rt = Restaurant.objects.get(
                    restaurant_name=row["restaurantname"],
                    business_address=row["businessaddress"],
                    postcode=row["postcode"],
                )
                save_inspections(row, rt.business_id)
                logger.info(
                    "Inspection record for restaurant saved successfully: {}".
                    format(rt))
            else:

                response = json.loads(
                    match_on_yelp(row["restaurantname"],
                                  row["businessaddress"]))
                if next(iter(
                        response)) == "error" or not response["businesses"]:
                    b_id = None
                else:
                    b_id = response["businesses"][0]["id"]

                r = Restaurant(
                    restaurant_name=row["restaurantname"],
                    business_address=row["businessaddress"],
                    postcode=row["postcode"],
                    business_id=b_id,
                    compliant_status=row["isroadwaycompliant"],
                )
                if b_id:
                    if not Restaurant.objects.filter(
                            business_id=b_id).exists():
                        r.save()
                        logger.info(
                            "Restaurant details successfully saved: {}".format(
                                b_id))
                        save_inspections(row, b_id)
                        save_yelp_restaurant_details(b_id)
                    else:
                        Restaurant.objects.filter(business_id=b_id).update(
                            compliant_status=row["isroadwaycompliant"])
                        save_inspections(row, b_id)
                else:
                    r.save()
                    save_inspections(row, b_id)

        except Exception as e:
            logger.error(
                "Error while saving to table Restaurant: {} {}".format(
                    b_id, e))

            # raise
    return
Beispiel #24
0
    def handle(self, *args, **options):

        s = urllib2.urlopen(source_url)
        xml_content = s.read()
        soup = BeautifulSoup(xml_content)

        with transaction.atomic():
            # hide everything, then we'll set restaurant with a
            # review as active later
            Restaurant.objects.update(active=False)

            for resto_data in soup.root.findAll('item'):
                vegoresto_id = int(resto_data.id.text)
                resto_set = Restaurant.objects.filter(
                    vegoresto_id=vegoresto_id)
                name = resto_data.titre.text
                print 'importing {0}'.format(name.encode('utf-8'))

                if resto_set.exists():
                    resto = resto_set[0]
                    resto.name = unescape(unescape(name))
                    resto.address = unescape(resto_data.adresse.text)
                else:
                    resto = Restaurant.create(vegoresto_id=vegoresto_id,
                                              name=unescape(unescape(name)),
                                              address=unescape(
                                                  resto_data.adresse.text))

                resto.active = True

                resto.review = unescape(resto_data.vegetik_review.text)
                resto.approved_date = parse(
                    resto_data.vegetik_approved_date.text)
                resto.lat = float(resto_data.lat.text)
                resto.lon = float(resto_data.lon.text)
                resto.website = resto_data.site_internet.text
                resto.description = resto_data.description.text
                resto.phone = resto_data.tel_fixe.text
                resto.mail = resto_data.mel_public.text
                resto.main_image = resto_data.image.text
                resto.country_code = resto_data.pays.text.upper()
                resto.vegoresto_url = resto_data.vego_url.text
                if resto_data.vegoresto.text == '1':
                    resto.vegoresto = True

                tags = parse_vg_tags(resto_data.categories_culinaires.text)
                if resto_data.vegetik_veganfriendly.text == 'TRUE':
                    tags.add(VEGAN_FRIENDLY)
                if tags:
                    resto.tags.add(*tags)

                resto.save()
    def handle(self, *args, **options):

        s = urllib2.urlopen(source_url)
        xml_content = s.read()
        soup = BeautifulSoup(xml_content)

        with transaction.atomic():
            # hide everything, then we'll set restaurant with a
            # review as active later
            Restaurant.objects.update(active=False)

            for resto_data in soup.root.findAll('item'):
                vegoresto_id = int(resto_data.id.text)
                resto_set = Restaurant.objects.filter(vegoresto_id=vegoresto_id)
                name = resto_data.titre.text
                print 'importing {0}'.format(name.encode('utf-8'))

                if resto_set.exists():
                    resto = resto_set[0]
                    resto.name = unescape(unescape(name))
                    resto.address = unescape(resto_data.adresse.text)
                else:
                    resto = Restaurant.create(vegoresto_id=vegoresto_id,
                                              name=unescape(unescape(name)),
                                              address=unescape(resto_data.adresse.text))

                resto.active = True

                resto.review = unescape(resto_data.vegetik_review.text)
                resto.approved_date = parse(resto_data.vegetik_approved_date.text)
                resto.lat = float(resto_data.lat.text)
                resto.lon = float(resto_data.lon.text)
                resto.website = resto_data.site_internet.text
                resto.description = resto_data.description.text
                resto.phone = resto_data.tel_fixe.text
                resto.mail = resto_data.mel_public.text
                resto.main_image = resto_data.image.text
                resto.country_code = resto_data.pays.text.upper()
                resto.vegoresto_url = resto_data.vego_url.text
                if resto_data.vegoresto.text == '1':
                    resto.vegoresto = True

                resto.tags.clear()

                tags = parse_vg_tags(resto_data.categories_culinaires.text)
                if resto_data.vegetik_veganfriendly.text == 'TRUE':
                    tags.add(VEGAN_FRIENDLY)
                if tags:
                    resto.tags.add(*tags)

                resto.save()
    def handle(self, *args, **options):
        all_restaurants = Restaurant.get_all()['Restaurants']

        for restaurant in all_restaurants:
            try:
                geo_location = eval(restaurant['GEO_location'])
                price = restaurant['pricepoint']
                print("geo" + str(geo_location))
                if type(geo_location) == dict:
                    continue
                if not type(geo_location) == tuple:
                    print(f"one of the entries is not a tuple: {geo_location}")
                    geo_location = eval(self.faker.location_on_land())
                if not price.lower() in {'low', 'medium', 'high'}:
                    print(f"invalid pricepoint {price}")
                    if not price in {'$', "$$", "$$$"}:
                        raise Exception
                    else:
                        price = {
                            '$': 'Low',
                            "$$": 'Medium',
                            "$$$": "High"
                        }[price]
            except NameError:
                traceback.print_exc()
                geo_location = self.faker.location_on_land()
            except Exception:
                print("execution halted")
                break

            new_location = {
                "lat": str(geo_location[0]),
                "long": str(geo_location[1]),
                "city": str(geo_location[2]),
                "state": str(geo_location[3]),
                "country": str(geo_location[4])
            }
            restaurant['GEO_location'] = new_location
            restaurant['pricepoint'] = price.title()
            new_rest = Restaurant(**restaurant)
            new_rest.clean_fields()
            new_rest.clean()
            new_rest.save()
Beispiel #27
0
 def handle(self, *args, **options):
     path_fixtures = 'fixtures/'
     with open(path_fixtures + 'fixture.json') as load:
         data = json.loads(load.read())
         if options['restaurant']:
             Restaurant.objects.all().delete()
             restaurants = []
             for restaurant in data['restaurants']:
                 image_file = open(path_fixtures + restaurant['imagePath'],
                                   'rb')
                 restaurant['imagePath'] = File(image_file)
                 restaurants.append(Restaurant(**restaurant))
             Restaurant.objects.bulk_create(restaurants)
             self.stdout.write(
                 self.style.SUCCESS('It Works ! restaurants:'))
Beispiel #28
0
def add_restaurant(request):
    context = {}
    if request.user.userprofile.is_customer:
        context['errors'] = 'you are not a business user and cannot create a restaurant'
        return render(request, 'account/add-restaurant.html', context)

    if request.method == 'GET':
        context['form'] = RestaurantForm()
        return render(request, 'account/add-restaurant.html', context)

    form = RestaurantForm(request.POST)
    context['form'] = form
    if not form.is_valid():
        return render(request, 'account/add-restaurant.html', context)

    location = Point(form.cleaned_data['longitude'], form.cleaned_data['latitude'])
    new_restaurant = Restaurant(name=form.cleaned_data['name'], introduction=form.cleaned_data['introduction'],
                                address=form.cleaned_data['address'], owner=request.user, location=location)
    new_restaurant.save()
    added_recipes = form.cleaned_data['added_recipes']
    if added_recipes:
        relate_added_recipes_helper(new_restaurant, added_recipes)

    return redirect(reverse('restaurant_home', kwargs={'restaurant_id': new_restaurant.id}))
Beispiel #29
0
def api_insert_review_view(request, **kwargs):
    """
	"author" : "author_name",
	"rating" : "1",
	"weight_score" : "1",
	"text" : "content",
	"restaurant_id" : "1",
	"review_count" : "30",
	"source" : "google",
	"category" : "Pizza",
	"country" : "United States",
	"state" :"GA",
	"created_date" : "2021-01-18"
	"""
    if request.method == 'POST':
        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            # TODO: check if request missing restaurant id
            try:
                res_obj = Restaurant.objects.get(
                    res_id=request.data['restaurant_id'])
            except Restaurant.DoesNotExist:
                res_obj = Restaurant(res_id=request.data['restaurant_id'],
                                     name='',
                                     number_review=0)
                res_obj.save()

            review = res_obj.res_review.create(
                author=serializer.data['author'],
                rating=serializer.data['rating'],
                weight_score=serializer.data['weight_score'],
                text=serializer.data['text'],
                review_count=serializer.data['review_count'],
                source=serializer.data['source'],
                category=serializer.data['category'],
                country=serializer.data['country'],
                state=serializer.data['state'],
                created_date=serializer.data['created_date'])
            review.save()

            res_obj.number_review = int(res_obj.number_review) + 1
            res_obj.save()
            data = {'message': 'Success'}
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Beispiel #30
0
def getPoint(request):
    if request.method == 'POST':
        gradUserName = request.POST.get('userName',None)
        inRestName = request.POST.getlist('restName[]',None)
        points = request.POST.getlist("points[]")
        counter = 0
        user = User.objects.get(userName = gradUserName)
        for point in points:
            if point != '':
                counter = counter + int(point)
            
        if counter <= user.userPoints:
            i = 0
            for point in points:
                if point != '':
                    restN = inRestName[i]
                    rest = Restaurant.objects.get(restName = restN)
                    Points.newPoint(Points,user,rest,point)
                    user.grade(int(point))
                i = i + 1 
            user.save()
            row = []
            returnList = []
            enteredPoints = Points.objects.all()
            for point in enteredPoints:
                rest = point.restaurant.restName
                user = point.user.userName
                row = {'restaurant':rest,'user':user,'point':point.point}
                returnList.append(row)
            context = Context({'Points' : returnList})
            return render(request,'enteredPoints.html',context)
        else:
            restaurants = Restaurant.getRestaurants(Restaurant).filter(serviceStatus = True)
            context = Context({'Restaurants' : restaurants})
            return render(request,'restaurants.html',context)
    else:
        row = []
        returnList = []
        enteredPoints = Points.objects.all()
        for point in enteredPoints:
                rest = point.restaurant.restName
                user = point.user.userName
                row = {'restaurant':rest,'user':user,'point':point.point}
                returnList.append(row)
        context = Context({'Points' : returnList})
        return render(request,'enteredPoints.html',context) 
 def test_reassign_BU_to_RO_Restaurant(self):
     """
     Tests the reassign view (Upgrading from BU -> RO) by calling it then checking the database
     to see if the changes were made on the Restaurant Document
     """
     request = self.factory.post('/api/user/role_reassign/', {
         "user_email": "*****@*****.**",
         "role": "RO",
         "name": "Rando Resto",
         "address": "211 detroit",
         "phone": 6475210680,
         "city": "toronto",
         "email": "*****@*****.**",
         "cuisine": "african",
         "pricepoint": "Medium",
         "twitter": "https://twitter.com/SupremeDreams_s1",
         "instagram": "https://www.instagram.com/rdcworld1/2?hl=en",
         "bio": "Finger licking good chicken",
         "external_delivery_link":
         "https://docs.djang22oproject.com/en/topics/testing/overview/",
         "cover_photo_url": "link",
         "logo_url": "link",
         "rating": "3.00"
     },
                                 content_type='application/json')
     reassign_page(request)
     actual = Restaurant.objects.get(email="*****@*****.**")
     expected = Restaurant(
         _id=actual._id,
         name='Rando Resto',
         address='211 detroit',
         phone=6475210680,
         city='toronto',
         email='*****@*****.**',
         cuisine='african',
         pricepoint='Medium',
         twitter='https://twitter.com/SupremeDreams_s1',
         instagram='https://www.instagram.com/rdcworld1/2?hl=en',
         bio='Finger licking good chicken',
         GEO_location="{'lat': 42.3295629, 'lng': -83.0492457}",
         external_delivery_link=
         'https://docs.djang22oproject.com/en/topics/testing/overview/',
         cover_photo_url='link',
         logo_url='link',
         rating='3.00')
     self.assertDictEqual(model_to_dict(actual), model_to_dict(expected))
def reassign_page(request):
    """
    Page to change the role of a user provided the user email and new role (If upgraded to RO must
    provide fields to make new restaurant instance
    """
    validate(instance=request.body, schema=signup_schema)
    body = json.loads(request.body)
    user = SDUser.objects.get(pk=body['user_email'])
    user.reassign_role(body['role'])
    if body['role'] == "RO":
        del body['user_email']
        del body['role']
        restaurant = Restaurant.insert(body)
        user.restaurant_id = str(restaurant._id)
        user.save(update_fields=["restaurant_id"])
        return JsonResponse({"restaurant_id": str(restaurant._id)})
    else:
        user.restaurant_id = None
        user.save(update_fields=["restaurant_id"])
    return HttpResponse(status=200)
Beispiel #33
0
def approve_restr(model_admin, request, queryset):
    """
    Approve of PendingRestaurant record and insert it into Restaurant collection,
    or updates the existing record in Restaurant collection that corresponds to
    this PendingRestaurant record.
    Sends a notification email to the restaurant email
    for each successful approval.
    """
    count = 0
    total = 0
    restaurant_name = ""
    restaurant_id = None
    wrong_status = False
    for r in queryset:
        total += 1
        restaurant = Restaurant(**model_to_json(r))
        old_restaurant = Restaurant.objects.filter(_id=r._id).first()

        if r.status == Status.Pending.name:
            count += 1

            # If there's already an approved restaurant record in Restaurant collection
            # check if the restaurant's media (image or video) is oudated, by comparing the url
            # to the url in the PendingRestaurant's media fields. If they don't match
            # delete the approved restaurant record's media file from google cloud bucket
            if old_restaurant:
                if old_restaurant.logo_url != r.logo_url:
                    delete(old_restaurant.logo_url)
                if old_restaurant.cover_photo_url != r.cover_photo_url:
                    delete(old_restaurant.cover_photo_url)
                if (old_restaurant.restaurant_video_url !=
                        r.restaurant_video_url and 'youtube'
                        not in old_restaurant.restaurant_video_url):
                    delete(old_restaurant.restaurant_video_url)
            edit_model(restaurant, {
                "status": Status.Approved.name,
                "approved_once": True
            }, ["status", "approved_once"])
            save_and_clean(restaurant)

            owner_prefer_names = r.owner_preferred_name
            restaurant_name = r.name
            email = r.email
            restaurant_id = r._id
            send_approval_email(owner_prefer_names, email, restaurant_name,
                                'restaurant')
        else:
            wrong_status = True
    if count > 1:
        messages.success(
            request,
            "Successfully approved " + str(count) + " restaurant profiles.")
        queryset.update(status=Status.Approved.name, approved_once=True)
    elif count == 1:
        link = reverse("admin:restaurant_pendingrestaurant_change",
                       args=[restaurant_id])
        msg = format_html(
            "Successfully approved restaurant profile for <a href='{}' target='_blank' rel='noopener'>{}</a>",
            link, restaurant_name)
        messages.success(request, msg)
        queryset.update(status=Status.Approved.name, approved_once=True)
    elif wrong_status:
        messages.error(request,
                       "You can only approve of 'Pending' restaurants")
    else:
        if total > 1:
            msg = "The selected restaurant profiles have been approved already."
        else:
            msg = "The selected restaurant profile has been approved already."
        messages.error(request, msg)
Beispiel #34
0
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()
Beispiel #35
0
    def handle(self, *args, **options):
        Restaurant.objects.all().delete()

        Restaurant.create(1, "Exki", "12, Chaussée D'Ixelles, 1050 Ixelles", 'www.exki.be', '02/502.72.77', status='2ème vague')
        Restaurant.create(2, "Ellis Gourmet Burger", "Place Sainte-Catherine, 4 - 1000 Bruxelles", "http://www.ellisgourmetburger.com/nl/", "02/514.23.14", status="OK (autocollant)", vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(3, "Den Teepot", "66, Rue des Chartreux 1000 Bruxelles", "http://www.bioshop.be/winkels/brussel.html", "02/511.94.02", status="OK (autocollant)", vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(4, "Toukoul", "34, Rue de Laeken 1000 Bruxelles ", "http://www.toukoul.be", "02/223.73.77", "*****@*****.**", status="repasser à 13h", vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(5, "Mr Falafel", "53, Boulevard Lemonnier - 1000 Bruxelles", None, "0493/34.64.12", None, status="OK (autocollant)", vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(6, "Le Dolma", "329, Chaussée d'Ixelles - 1050 Ixelles", "www.dolma.be", "02/649.89.81", "*****@*****.**", status="OK (autocollant)", vg_contact="Lisa & Sophie H & Isabelle - 05/07")
Beispiel #36
0
def grading(request):
    users = User.getUsers(User)
    gradingFlag = Restaurant.restaurantBalance(Restaurant)
    context = Context({'users' : users,'flag':gradingFlag})
    return render(request,'gradingUser.html',context)
Beispiel #37
0
 def get(self, request, rest_id):
     """ Retrieve approved restaurant by id """
     restaurant = Restaurant.get(rest_id)
     restaurant = model_to_json(restaurant)
     return JsonResponse(restaurant)
Beispiel #38
0
 def test_delete_restaurant(self):
     restaurant = Restaurant.objects.get(pk=1)
     Restaurant.delete(restaurant)
     assert True
Beispiel #39
0
def createRestaurant(request,idEntite):
    global myfile, entite
    if  request.user.is_authenticated():
        if request.user.is_superuser :
            global ckeck
            try:
                entite = Entite.objects.filter(idEntit=idEntite)[0]
                check=1
            except:
                check=0
            if check ==1:
                if request.POST:
                    is_error = 0
                    nom = request.POST["nom"]
                    quartier = request.POST["quartier"]
                    email = request.POST["email"]
                    numero = request.POST["numero"]
                    latitude = request.POST["latitude"]
                    longitude = request.POST["longitude"]
                    # couleur=request.POST["coleur"]
                    save_plus = request.POST.getlist('save_and')
                    if latitude == "":
                        error_latitude = "veuiller remplir ce champs"
                        is_error = 1
                    if longitude == "":
                        error_longitude = "veuiller remplir ce champs"
                        is_error = 1
                    if nom == "":
                        errer_nom = "veuiller remplir ce champs"
                        is_error = 1
                    if quartier == "":
                        error_quartier = "veuiller remplir ce champs"
                        is_error = 1
                    if email == "":
                        error_email = "veuiller remplir ce champs"
                        is_error = 1
                    else:
                        if re.search(r"^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+", email) is None:
                            is_error = 1
                            error_email = "email incorrect"
                    if numero == "":
                        error_numero = "veuiller remplir ce champs"
                        is_error = 1
                    else:
                        if re.search(r"^[0-9]{9}$", numero) is None:
                            is_error = 1
                            error_numero = "numero incorrect"
                    try:
                        myfile = request.FILES['logo']
                    except:
                        error_logo = "veuillez selectionner une image"
                        is_error = 1
                    # fs = FileSystemStorage()
                    if is_error == 0:
                        restaurant=Restaurant()
                        restaurant.nomRestaurant=nom
                        restaurant.numeroRestaurant=numero
                        restaurant.emailRestaurant=email
                        restaurant.createurRestaurant=request.user
                        restaurant.entite=entite
                        restaurant.quartierRestaurant=quartier
                        restaurant.longiRestaurant=longitude
                        restaurant.latiRestaurant=latitude
                        entite_folder = "C:/Users/root/PycharmProjects/senfood/static/images/uploads/"
                        save_path = "C:/Users/root/PycharmProjects/senfood/static/images/uploads/" +decodeString(entite.nomEntite)
                        logo_name = "restau_" + nom + "_" + myfile.name
                        destination = open(os.path.join(save_path, logo_name), 'wb+')
                        restaurant.logoRestaurant = "images/uploads/" + decodeString(entite.nomEntite) + "/" + logo_name
                        restaurant.save()
                        for chunk in myfile.chunks():
                            destination.write(chunk)
                        destination.close()

                        log = Log()
                        log.utilisateur = request.user.username
                        log.action = "Creation restaurant " + nom+" pour l'entite "+decodeString(entite.nomEntite)
                        messages.success(request, 'Restaurant ajouté avec succès')
                        try:
                            _next = int(save_plus[0])
                        except:
                            _next = 0

                        if _next == 0:
                            v=5
                            #return render(request, 'creationRestaurant.html', locals())
                            return redirect(profilEntite,idEntite)
                        else:
                            nom = ""
                            quartier = ""
                            email = ""
                            numero = ""
                            longitude=""
                            latitude=""
                            return render(request, 'creationRestaurant.html', locals())
                    else:
                        # entite=Entite()
                        # entite.nomEntite=nom
                        # entite.sloganEntite=slogan
                        # entite.emailEntite=email
                        # entite.numeroEntite=numero
                        return render(request, 'creationRestaurant.html', locals())
                else:
                    return render(request, 'creationRestaurant.html', locals())
            else:
                message = "page introuvable"
                return render(request, '404.html', locals())
Beispiel #40
0
class RestaurantTest(TestCase):
    def setUp(self):
        self.now = '2019-01-01 12:00:00.000000+00:00'
        self.restaurant = Restaurant(
            name='군내치킨',
            owner='박군내',
            title='군내치킨-서초점',
            tel='1234',
            min_order_price=10000,
            order_way='현장 결제',
            origin='닭:국내산',
            delivery_charge=2000,
            info='군내나지만 맛있습니다.',
            type='요기요 등록 음식점',
            img='media/restaurant/chicken.png',
            estimated_delivery_time=self.now,
            operation_start_hour=self.now,
            operation_end_hour=self.now,
        )
        self.restaurant.save()
        self.category = self.restaurant.category.create(name='1인분 주문')
        self.category.save()

    def test_restaurant_should_be_created_on_valid_data(self):
        '''
        유효한 데이터에 대해 레스토랑을 생성한다.
        '''
        # Given

        # When

        # Then
        self.assertEqual(self.restaurant.owner, '박군내')
        self.assertEqual(self.restaurant.title, '군내치킨-서초점')
        self.assertEqual(self.restaurant.tel, '1234')
        self.assertEqual(self.restaurant.min_order_price, 10000)
        self.assertEqual(self.restaurant.order_way, '현장 결제')
        self.assertEqual(self.restaurant.delivery_charge, 2000)
        self.assertEqual(self.restaurant.info, '군내나지만 맛있습니다.')
        self.assertEqual(self.restaurant.type, '요기요 등록 음식점')
        self.assertEqual(self.restaurant.estimated_delivery_time, self.now)
        self.assertEqual(self.restaurant.operation_start_hour, self.now)
        self.assertEqual(self.restaurant.operation_end_hour, self.now)
        self.assertIsNotNone(self.restaurant.img)
        self.assertIsInstance(self.restaurant, Restaurant)
        self.assertEqual(self.restaurant.__str__(), self.restaurant.name)
        self.assertEqual(self.restaurant.category.get(pk=self.category.pk),
                         self.category)
        self.assertEqual(self.category.name, '1인분 주문')

    def test_restaurant_should_not_be_created_on_invalid_data(self):
        '''
        유효하지 않은 데이터에 대해 레스토랑을 생성하지 않는다.
        '''
        # Given

        # When

        # Then
        self.assertIsNot(self.restaurant.min_order_price, 1000)
        self.assertIsNot(self.restaurant.estimated_delivery_time, 'now')
        self.assertIsNot(self.restaurant.img, '-')
        self.assertNotIsInstance(self.category, Restaurant)
        self.assertIsNot(self.restaurant.__str__(), '굽굽치킨')
        self.assertIsNot(self.restaurant.category.get(pk=self.category.pk),
                         self.restaurant)
Beispiel #41
0
    def makePrediction(self, weatherCondition):
        totalPredictions = Calculation.objects.all().count()
        if weatherCondition == False:
            predictionRestsCount = Restaurant.objects.filter(
                serviceCounter__gt=0,
                serviceStatus=True,
                modeOfTransport=True,
                weatherCondition=True).count()
            if predictionRestsCount == 0:
                predictionRestsCount = Restaurant.objects.filter(
                    serviceCounter__gt=0,
                    serviceStatus=True,
                    weatherCondition=True).count()
                if predictionRestsCount == 0:
                    self.setRestCounters(Calculation)
                    predictionRestsCount = Restaurant.objects.filter(
                        serviceCounter__gt=0,
                        serviceStatus=True,
                        modeOfTransport=True,
                        weatherCondition=True).count()
                    if predictionRestsCount == 0:
                        predictionRestsCount = Restaurant.objects.filter(
                            serviceCounter__gt=0,
                            serviceStatus=True,
                            weatherCondition=True).count()
                        if predictionRestsCount == 0:
                            return False
                        else:
                            predictionRests = Restaurant.objects.filter(
                                serviceCounter__gt=0,
                                serviceStatus=True,
                                weatherCondition=True)
                    else:
                        predictionRests = Restaurant.objects.filter(
                            serviceCounter__gt=0,
                            serviceStatus=True,
                            modeOfTransport=True,
                            weatherCondition=True)
                else:
                    predictionRests = Restaurant.objects.filter(
                        serviceCounter__gt=0,
                        serviceStatus=True,
                        weatherCondition=True)
            else:
                predictionRests = Restaurant.objects.filter(
                    serviceCounter__gt=0,
                    serviceStatus=True,
                    modeOfTransport=True,
                    weatherCondition=True)

            predictionRestsCount = predictionRests.count()
            if predictionRestsCount > 1 and totalPredictions >= 1:
                last = Calculation.objects.last().restaurant
                for rest in predictionRests:
                    if rest.restName == last.restName:
                        predictionRests = predictionRests.exclude(
                            restName=last.restName)
                        predictionRestsCount = predictionRestsCount - 1

            if predictionRestsCount > 1:
                random_index = randint(0, predictionRestsCount - 1)
            nowDate = datetime.datetime.now()
            if predictionRestsCount > 1:
                predictionRest = predictionRests[random_index]
            else:
                predictionRest = predictionRests[0]
            finalRest = Restaurant.objects.get(
                restName=predictionRest.restName)
            finalRest.serviceCounter = finalRest.serviceCounter - 1
            finalRest.save()
            currentWeather = Weather.getCurrent(Weather)
            newCalculation = Calculation(restaurant=predictionRest,
                                         date=nowDate,
                                         weather=currentWeather)
            newCalculation.save()
            return True
        else:
            predictionRestsCount = Restaurant.objects.filter(
                serviceCounter__gt=0, serviceStatus=True).count()
            if predictionRestsCount == 0:
                self.setRestCounters(Calculation)
                predictionRestsCount = Restaurant.objects.filter(
                    serviceCounter__gt=0, serviceStatus=True).count()
                if predictionRestsCount == 0:
                    return False
                predictionRests = Restaurant.objects.filter(
                    serviceCounter__gt=0, serviceStatus=True)
            else:
                predictionRests = Restaurant.objects.filter(
                    serviceCounter__gt=0, serviceStatus=True)

            onlyPedestrian = False
            if predictionRestsCount > 1 and totalPredictions >= 1:
                last = Calculation.objects.last().restaurant
                if last.modeOfTransport == True and predictionRestsCount > 1 and predictionRests.filter(
                        modeOfTransport=False).count() >= 1:
                    onlyPedestrian = True
                for rest in predictionRests:
                    if rest.restName == last.restName:
                        predictionRests = predictionRests.exclude(
                            restName=last.restName)
                        predictionRestsCount = predictionRestsCount - 1

            if predictionRestsCount > 1 and totalPredictions >= 2:
                last2 = Calculation.objects.all().order_by('-id')[:2]
                for lasts in last2:
                    if lasts.restaurant.modeOfTransport == True and predictionRestsCount > 1 and predictionRests.filter(
                            modeOfTransport=False).count() >= 1:
                        predictionRests = predictionRests.exclude(
                            restName=lasts.restaurant.restName)
                        predictionRestsCount = predictionRestsCount - 1
                        onlyPedestrian = True

            if onlyPedestrian == True:
                predictionRests = predictionRests.filter(modeOfTransport=False)

            terraceFlag = Restaurant.terraceCheck(Restaurant)
            if terraceFlag == True:
                terraceCount = predictionRests.filter(
                    weatherCondition=False).count()
                if terraceCount > 0:
                    predictionRests = predictionRests.filter(
                        weatherCondition=False)

            vehicleFlag = Restaurant.vehicleCheck(Restaurant)
            if vehicleFlag == True:
                vehicleCount = predictionRests.filter(
                    modeOfTransport=True).count()
                if vehicleCount > 0:
                    predictionRests = predictionRests.filter(
                        modeOfTransport=True)
            predictionRestsCount = predictionRests.count()
            if predictionRestsCount > 1:
                random_index = randint(0, predictionRestsCount - 1)
            if predictionRestsCount > 1:
                predictionRest = predictionRests[random_index]
            else:
                predictionRest = predictionRests[0]
            nowDate = datetime.datetime.now()
            finalRest = Restaurant.objects.get(
                restName=predictionRest.restName)
            finalRest.serviceCounter = finalRest.serviceCounter - 1
            finalRest.save()
            currentWeather = Weather.getCurrent(Weather)
            newCalculation = Calculation(restaurant=predictionRest,
                                         date=nowDate,
                                         weather=currentWeather)
            currentUsers = User.objects.all()
            for u in currentUsers:
                send_mail('Todays Restaurant',
                          'Todays restaurant is ' + str(finalRest.restName),
                          '*****@*****.**', [u.userEmail],
                          fail_silently=False)
            newCalculation.save()
            return True
Beispiel #42
0
    def handle(self, *args, **options):
        Restaurant.objects.all().delete()

        Restaurant.create(1,
                          "Exki",
                          "12, Chaussée D'Ixelles, 1050 Ixelles",
                          'www.exki.be',
                          '02/502.72.77',
                          status='2ème vague')
        Restaurant.create(2,
                          "Ellis Gourmet Burger",
                          "Place Sainte-Catherine, 4 - 1000 Bruxelles",
                          "http://www.ellisgourmetburger.com/nl/",
                          "02/514.23.14",
                          status="OK (autocollant)",
                          vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(3,
                          "Den Teepot",
                          "66, Rue des Chartreux 1000 Bruxelles",
                          "http://www.bioshop.be/winkels/brussel.html",
                          "02/511.94.02",
                          status="OK (autocollant)",
                          vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(4,
                          "Toukoul",
                          "34, Rue de Laeken 1000 Bruxelles ",
                          "http://www.toukoul.be",
                          "02/223.73.77",
                          "*****@*****.**",
                          status="repasser à 13h",
                          vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(5,
                          "Mr Falafel",
                          "53, Boulevard Lemonnier - 1000 Bruxelles",
                          None,
                          "0493/34.64.12",
                          None,
                          status="OK (autocollant)",
                          vg_contact="Lisa & Sophie - 28/06")
        Restaurant.create(6,
                          "Le Dolma",
                          "329, Chaussée d'Ixelles - 1050 Ixelles",
                          "www.dolma.be",
                          "02/649.89.81",
                          "*****@*****.**",
                          status="OK (autocollant)",
                          vg_contact="Lisa & Sophie H & Isabelle - 05/07")