def unpublish_food(model_admin, request, queryset): """ Unpublish a live Restaurant Dish Profile and updates the status of pendingDish accordingly. Sends a notification email to the restaurant email for each successful unpublish action. """ count = 0 for f in queryset: count += 1 pendingFood = PendingFood.objects.filter(_id=f._id).first() restaurant = PendingRestaurant.objects.filter(_id=f.restaurant_id) if pendingFood.status == Status.Approved.name: restr = restaurant.first() owner_prefer_names = restr.owner_preferred_name food_name = f.name email = restr.email send_unpublish_email(owner_prefer_names, email, food_name, 'food') pendingFood.status = Status.Rejected.name save_and_clean(pendingFood) queryset.delete() if count > 1: messages.success( request, "Successfully unpublished " + str(count) + " food profiles.") elif count == 1: msg = "Successfully unpublished food profile for " + f.name messages.success(request, msg)
def signup(cls, restaurant_owner_data: dict): """ Constructs and saves a new RestaurantOwner record to the database and returns the newly made RestaurantOwner object :param restaurant_owner_data: data of the restaurant owner :type restaurant_owner_data: dict :rairses ObjectDoesNotExist: if PendingRestaurant record of given id does not exist :raises IntegrityError: upon business logic violations :return: new RestaurantOwner object """ user_id = restaurant_owner_data['user_id'] restaurant_id = restaurant_owner_data['restaurant_id'] if cls.objects.filter(user_id=user_id).exists(): raise IntegrityError( 'Cannot insert restaurant owner user, a user with this user_id already exists') restaurant_filter = PendingRestaurant.objects.filter(_id=restaurant_id) if not restaurant_filter.exists(): raise ObjectDoesNotExist( "This restaurant with _id: "+restaurant_id+" does not exist") if "consent_status" in restaurant_owner_data: restaurant_owner_data.update( handleConsentStatus(restaurant_owner_data['consent_status'])) restaurant = restaurant_filter.first() restaurant.owner_user_id = user_id save_and_clean(restaurant) profile = cls(**restaurant_owner_data) profile = save_and_clean(profile) return profile
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 signup(cls, first_name, last_name, email, consent_status, expired_at): """ Constructs & Saves User to DB returning the newly signed up user object :param first_name: first name of user :type first_name: str :param last_name: last name of user :type last_name: str :param email: email of user :type email: str :param consent_status: consent status regarding user's choice of receiving project updates :type consent_stautus: str :return: new NLUser :rtype: :class:`NLUser` object """ if cls.objects.filter(email=email).exists(): raise IntegrityError("This email has already been used.") user = cls( first_name=first_name, last_name=last_name, email=email, consent_status=consent_status ) if consent_status == ConsentStatus.EXPRESSED.name: user.subscribed_at = date.today() else: user.expired_at = expired_at user = save_and_clean(user) return user
def add_tag(cls, food_name, restaurant_id, category, value): """ Add tag to food :param food_name: name of food :param restaurant_id: id of restaurant :param category: category of following tag :param value: value of following tag :return: following tag object """ food = Food.objects.get(name=food_name, restaurant_id=restaurant_id) if not ManualTag.tag_exists(value, category): tag = cls(value=value, category=category, foods=[food._id]) save_and_clean(tag) return tag tag = ManualTag.objects.get(value=value, category=category) if not food.is_tagged(tag): add_new_tag(food, tag) return tag
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))
def insert(cls, restaurant_data): """ Insert restaurant into database given restaurant data :param restaurant_data: json data of restaurant :return: restaurant object representing sent data """ try: cls.objects.get(email=restaurant_data['email']) raise ValueError('Cannot insert') except ObjectDoesNotExist: restaurant = cls(**restaurant_data) update_model_geo(restaurant, restaurant_data['address']) restaurant = save_and_clean(restaurant) return restaurant
def add_dish(cls, food_data): """ insert dish into database and return response :param food_data: dictionary representation of dish :return: Food model object """ dish = cls( name=food_data['name'], restaurant_id=food_data['restaurant_id'], description=food_data['description'], price=food_data['price'], specials=food_data['specials'], category=food_data['category'], ) save_and_clean(dish) dish = model_refresh(Food, { 'name': dish.name, 'restaurant_id': dish.restaurant_id }) restaurant = Restaurant.objects.get(_id=food_data['restaurant_id']) if not restaurant.category_exists(food_data['category']): restaurant.categories.append(food_data['category']) restaurant.save(update_fields=['categories']) return dish
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 edit_profile(cls, user_id, user_data): """ Updates the fields of a RestaurantOwner record of the user_id Updated fields and values are contained in the user_data dict :param user_id: id of the sduser :type user_id: int :param user_data: RestaurnatOwner fields and values to be updated to :type user_data: dict :raises ObjectDoesNotExist: when SDUser or RestaurantOwner record does not exist :return: the updated RestaurantOwner record :rtype: :class: `RestaurantOwner` """ ro_filter = RestaurantOwner.objects.filter(user_id=user_id) profile = ro_filter.first() edit_model(profile, user_data, restaurant_owner_editable) if "consent_status" in user_data: consent_data = handleConsentStatus(user_data["consent_status"]) for field in consent_data: setattr(profile, field, consent_data[field]) profile = save_and_clean(profile) return profile
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)