def test_get_all_dishes(self):
     """ Test if all dishes from a restaurant is retrieved correctly """
     response = self.client.get('/api/dish/approved/' +
                                str(self.restaurant._id) + '/')
     dishes = [
         model_to_json(Food.objects.get(_id=str(self.dish_1._id))),
         model_to_json(Food.objects.get(_id=str(self.dish_2._id)))
     ]
     expected = {'Dishes': dishes}
     self.assertDictEqual(expected, json.loads(response.content))
    def test_get_post(self):
        """ Test if restaurant posts are retrieved correctly """
        response = self.client.get('/api/restaurant/post/')
        actual = json.loads(response.content)
        for post in actual['Posts']:
            post.pop('Timestamp')
        posts = [
            model_to_json(
                RestaurantPost.objects.get(_id=str(self.post_1._id))),
            model_to_json(RestaurantPost.objects.get(_id=str(self.post_2._id)))
        ]

        expected = {"Posts": posts}
        self.assertDictEqual(expected, actual)
Beispiel #3
0
    def delete(self, request, post_id):
        """ Deletes a single restaurant post """
        user = request.user
        check_user_status(user)

        post_deleted = RestaurantPost.remove_post(post_id)
        return JsonResponse({"Deleted post": model_to_json(post_deleted)})
    def post(self, request):
        """ insert a newsletter user into the db provided all the user fields """
        validate(instance=request.data,
                 schema=schemas.newsletter_signup_schema)
        body = request.data

        ip = get_client_ip_address(request)
        block = NLAudit.update_audit(ip)
        if block:
            msg = "You have submitted too many signups and have been temporarily blocked. Please do not spam our system!"
            return JsonResponse(
                {
                    'status': 500,
                    'code': 'too_many_signups',
                    'detail': msg
                },
                status=500)
        NLUser.field_validate(body)
        user = NLUser.signup(first_name=body['first_name'],
                             last_name=body['last_name'],
                             email=body['email'],
                             consent_status=body['consent_status'],
                             expired_at=date.today() +
                             relativedelta(days=+182))
        return JsonResponse(model_to_json(user))
 def test_get_dishes(self):
     """ Tests if dishes for restaurant owned by user are retrieved correctly """
     response = self.client.get('/api/dish/pending/')
     dishes = [
         model_to_json(PendingFood.objects.get(_id=str(self.dish_2._id)))
     ]
     expected = {'Dishes': dishes}
     self.assertDictEqual(expected, json.loads(response.content))
def insert_tag_page(request):
    """Insert tag to database"""
    validate(instance=request.body, schema=tag_schema)
    body = json.loads(request.body)
    food_name, restaurant_id, category, value = \
        body['food_name'], body['restaurant_id'], body['category'], body['value']
    tag = ManualTag.add_tag(food_name, restaurant_id, category, value)
    return JsonResponse(model_to_json(tag))
 def test_get_favs(self):
     """ Tests if all favourited restaurants are retrieved correctly """
     response = self.client.get('/api/user/favourite/')
     actual = json.loads(response.content)
     fav_rest = Restaurant.objects.get(_id=str(self.restaurant_2._id))
     fav_rest.offer_options = ast.literal_eval(fav_rest.offer_options)
     expected = [model_to_json(fav_rest)]
     self.assertListEqual(expected, actual)
Beispiel #8
0
    def get(self, request):
        """ Retrieves a restaurant owner profile """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant_owner = RestaurantOwner.get_by_user_id(user_id=user_id)
        return JsonResponse(model_to_json(restaurant_owner))
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({})
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))
Beispiel #11
0
    def delete(self, request, dish_id):
        """ Deletes dish from database """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)
        deleted_dish = PendingFood.remove_dish(dish_id, restaurant._id)
        return JsonResponse(model_to_json(deleted_dish))
def get_all_posts_page(request):
    """ retrieve list of restaurants from database """
    posts = list(TimelinePost.objects.all())
    posts = sort(posts)
    response = {'Posts': []}
    for post in posts:
        time_stamp = {'Timestamp': post.Timestamp.strftime("%b %d, %Y %H:%M")}
        response['Posts'].append(model_to_json(post, time_stamp))
    return JsonResponse(response)
def decline_cart_page(request):
    """Decline a cart which has been sent by a user"""
    validate(instance=request.body, schema=cart_schema)
    body = json.loads(request.body)
    try:
        cart = Cart().decline_cart(cart_id=body['_id'])
        return JsonResponse(model_to_json(cart))
    except ValueError as error:
        return HttpResponseBadRequest(str(error))
Beispiel #14
0
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 test_get_pending_restaurant(self):
        """ Test if pending restaurant owned by ro is retrieved properly """
        response = self.client.get('/api/restaurant/pending/')
        restaurant = PendingRestaurant.objects.get(owner_user_id=self.ro.id)
        restaurant.restaurant_image_url = ['/']
        restaurant.payment_methods = ['/']
        restaurant.offer_options = ['']

        expected = model_to_json(restaurant)
        self.assertDictEqual(expected, json.loads(response.content))
def get_post_by_restaurant_page(request):
    """Retrieve all posts from a restaurant"""
    rest_id = request.GET.get('restaurant_id')
    posts = list(TimelinePost.objects.filter(restaurant_id=rest_id))
    posts = sort(posts)
    response = {'Posts': []}
    for post in posts:
        time_stamp = {'Timestamp': post.Timestamp.strftime("%b %d, %Y %H:%M")}
        response['Posts'].append(model_to_json(post, time_stamp))
    return JsonResponse(response)
Beispiel #17
0
    def get(self, request):
        """ Retrieve restaurant from pending collection by the owner's user_id """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)

        restaurant = model_to_json(restaurant)
        return JsonResponse(restaurant)
Beispiel #18
0
    def put(self, request):
        """ Modifies a SubscriberProfile record in the database """
        body = request.data
        user = request.user
        check_user_status(user)

        body['user_id'] = user.id
        SubscriberProfile.field_validate(body)
        profile = SubscriberProfile.edit(body)
        return JsonResponse(model_to_json(profile))
def update_status_page(request):
    """ Update cart status in database """
    validate(instance=request.body, schema=status_schema)
    body = json.loads(request.body)
    if valid_status(body['status']):
        try:
            cart = getattr(Cart, OrderStates[body['status']].value)(Cart, body['_id'])
            return JsonResponse(model_to_json(cart))
        except ValueError as error:
            return HttpResponseBadRequest(str(error))
    return HttpResponseBadRequest('Invalid request, please check your request')
def edit_item_amount_page(request):
    """ Edit food item """
    validate(instance=request.body, schema=item_schema)
    body = json.loads(request.body)
    responsemessage = Item.edit_item_amount(body['item_id'], body['count'])
    for entry in responsemessage:
        try:
            responsemessage[entry] = model_to_json(responsemessage[entry])
        except AttributeError:
            pass
    return JsonResponse(responsemessage)
Beispiel #21
0
    def post(self, request):
        """ Insert new restaurant as a draft into database """
        user = request.user
        check_user_status(user)

        validate(instance=request.data,
                 schema=schemas.restaurant_insert_draft_schema)
        body = request.data
        PendingRestaurant.field_validate_draft(body)
        restaurant = PendingRestaurant.insert(body)
        return JsonResponse(model_to_json(restaurant))
Beispiel #22
0
    def put(self, request):
        """ Updates a restaurant owner profile """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.restaurant_owner_edit_schema)
        body = request.data
        RestaurantOwner.field_validate(body)
        profile = RestaurantOwner.edit_profile(user_id, body)
        return JsonResponse(model_to_json(profile))
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')
Beispiel #24
0
    def put(self, request):
        """ Edit a restaurant profile and save it as a draft in the database """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data,
                 schema=schemas.restaurant_edit_draft_schema)
        body = request.data
        PendingRestaurant.field_validate_draft(body)
        restaurant = PendingRestaurant.edit_draft(user_id, body)
        return JsonResponse(model_to_json(restaurant))
Beispiel #25
0
 def get(self, request, format_type):
     """ Retrieves analytics data for all restaurants page
     given their restaurant ids and format of date """
     restaurants = list(Restaurant.objects.all())
     restaurant_data = {}
     for restaurant in restaurants:
         restJson = model_to_json(restaurant)
         rest_id = restJson.get('_id')
         traffic = get_analytics_data(rest_id, format_type)
         traffic['name'] = restJson.get('name')
         restaurant_data[rest_id] = traffic
     return JsonResponse(restaurant_data)
Beispiel #26
0
    def put(self, request):
        """ For updating existing image caption for a restaurant """
        user = request.user
        check_user_status(user)

        user_id = user.id
        body = request.data
        validate(instance=body, schema=schemas.image_captions_schema)
        restaurant = PendingRestaurant.get_by_owner(user_id)

        restaurant = PendingRestaurant.update_image_captions(restaurant, body)
        return JsonResponse(model_to_json(restaurant))
    def test_get_approved_restaurant(self):
        """ Test if approved restaurant is retrieved by _id """
        _id = Restaurant.objects.get(email="*****@*****.**")._id
        response = self.client.get('/api/restaurant/approved/' + str(_id) +
                                   '/')

        restaurant = Restaurant.objects.get(email="*****@*****.**")
        restaurant.restaurant_image_url = ['/']
        restaurant.payment_methods = ['/']
        restaurant.offer_options = ['']

        expected = model_to_json(restaurant)
        self.assertDictEqual(expected, json.loads(response.content))
def upload_post_page(request):
    """Upload post into post timeline post table"""

    try:  # validate request
        validate(instance=request.body, schema=post_schema)
    except jsonschema.exceptions.ValidationError:
        return HttpResponseBadRequest('Invalid request')

    body = json.loads(request.body)
    post = TimelinePost(**body)
    post.full_clean()
    post.save()
    return JsonResponse(model_to_json(post, {'Timestamp': post.Timestamp}))
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 #30
0
    def post(self, request):
        """ Insert a new post for a restaurant """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.post_schema)
        body = request.data
        body['owner_user_id'] = user_id
        RestaurantPost.field_validate(body)

        post = RestaurantPost.insert(body, request)
        return JsonResponse(model_to_json(post))