Example #1
0
def get_all_bookings_restaurant(fromDate=False,
                                toDate=False,
                                restaurant_id=False):

    reservations = db_session.query(Reservation)
    tables = RestaurantService.get_tables(restaurant_id)
    ints = [table["id"] for table in tables]
    current_app.logger.debug("TABLES INTS: {}".format(ints))
    reservations = reservations.filter(Reservation.table_id.in_(ints))

    # Filtering stuff
    if fromDate is not False:
        reservations = reservations.filter(
            Reservation.reservation_date >= datetime.strptime(
                fromDate, "%Y-%m-%dT%H:%M:%SZ"))
    if toDate is not False:
        reservations = reservations.filter(
            Reservation.reservation_end <= datetime.strptime(
                toDate, "%Y-%m-%dT%H:%M:%SZ"))

    reservations = reservations.all()
    if reservations is None:
        return HttpUtils.error_message(404, "No Reservations")

    current_app.logger.debug("reservations len={}".format(len(reservations)))
    for i, reservation in enumerate(reservations):
        reservations[i] = BookingService.replace_with_customer(reservation)

    return BookingService.reservations_to_json(reservations, "customer"), 200
Example #2
0
def get_hotels_list():
    return {"result": [{
        "hotel_id": 1,
        "hotel_name": "Apex Temple Court Hotel",
        "sentiment": 0.83,
        "url": "https://www.booking.com/hotel/gb/apex-temple-court.en-gb.html"
    }]}

    # TODO: make this work again
    holiday_plan_id = request.cookies['holiday_plan_id']
    analyzer = get_analyzer(holiday_plan_id)
    vacation_requirements = analyzer.get_vacation_requirements()
    booking_service = BookingService()
    return booking_service.get_hotels_list(vacation_requirements)
Example #3
0
def get_all_bookings(user_id=False,
                     fromDate=False,
                     toDate=False,
                     restaurant_id=False):

    reservations = db_session.query(Reservation)
    # Filtering stuff
    if user_id is not False:
        current_app.logger.debug(
            "Adding reservation with filter by user id: {}".format(user_id))
        reservations = reservations.filter(Reservation.customer_id == user_id)
    if fromDate is not False:
        current_app.logger.debug(
            "Adding reservation with filter from date: {}".format(fromDate))
        reservations = reservations.filter(
            Reservation.reservation_date >= datetime.strptime(
                fromDate, "%Y-%m-%dT%H:%M:%SZ"))
    if toDate is not False:
        current_app.logger.debug(
            "Adding reservation with filter to date: {}".format(toDate))
        reservations = reservations.filter(
            Reservation.reservation_end <= datetime.strptime(
                toDate, "%Y-%m-%dT%H:%M:%SZ"))
    if restaurant_id is not False:
        current_app.logger.debug(
            "Adding reservation with filter by restaurant id: {}".format(
                restaurant_id))
        tables = RestaurantService.get_tables(restaurant_id)
        ints = [table["id"] for table in tables]
        current_app.logger.debug("TABLES INTS: {}".format(ints))
        reservations = reservations.filter(Reservation.table_id.in_(ints))

    reservations = reservations.all()
    if reservations is None:
        return HttpUtils.error_message(404, "No Reservations")

    current_app.logger.debug("reservations len={}".format(len(reservations)))
    for i, reservation in enumerate(reservations):
        reservations[i] = BookingService.replace_with_restaurant(reservation)
        current_app.logger.debug("adding people")
        listfriends = []
        current_app.logger.debug("added empty list")
        friends = (db_session.query(Friend).filter_by(
            reservation_id=reservation.id).all())
        current_app.logger.debug("Got friends: {}".format(len(friends)))
        for friend in friends:
            listfriends.append(friend.email.strip())
        current_app.logger.debug("Frinds: {}".format(listfriends))
        reservations[i].people = listfriends
    return BookingService.reservations_to_json(reservations), 200
Example #4
0
def get_booking(reservation_id):
    reservation = db_session.query(Reservation).filter_by(
        id=reservation_id).first()

    if reservation is None:
        return HttpUtils.error_message(404, "Reservation not Found")

    return BookingService.reservation_to_json(reservation), 200
Example #5
0
def people_in(restaurant_id):
    openings = RestaurantService.get_openings(restaurant_id)
    if openings is None or len(openings) == 0:
        return {"lunch": 0, "dinner": 0, "now": 0}

    openings = BookingService.filter_openings(openings,
                                              datetime.today().weekday())[0]

    openings_model = OpeningHoursModel()
    openings_model.fill_from_json(openings)

    tables = RestaurantService.get_tables(restaurant_id)
    if tables is None or len(tables) == 0:
        return {"lunch": 0, "dinner": 0, "now": 0}

    tables_id = [table["id"] for table in tables]
    current_app.logger.debug("TABLES IDs: {}".format(tables_id))

    reservations_l = (db_session.query(Reservation).filter(
        Reservation.table_id.in_(tables_id),
        extract("day", Reservation.reservation_date) == extract(
            "day", datetime.today()),
        extract("month", Reservation.reservation_date) == extract(
            "month", datetime.today()),
        extract("year", Reservation.reservation_date) == extract(
            "year", datetime.today()),
        extract("hour", Reservation.reservation_date) >= extract(
            "hour", openings_model.open_lunch),
        extract("hour", Reservation.reservation_date) <= extract(
            "hour", openings_model.close_lunch),
    ).all())

    reservations_d = (db_session.query(Reservation).filter(
        Reservation.table_id.in_(tables_id),
        extract("day", Reservation.reservation_date) == extract(
            "day", datetime.today()),
        extract("month", Reservation.reservation_date) == extract(
            "month", datetime.today()),
        extract("year", Reservation.reservation_date) == extract(
            "year", datetime.today()),
        extract("hour", Reservation.reservation_date) >= extract(
            "hour", openings_model.open_dinner),
        extract("hour", Reservation.reservation_date) <= extract(
            "hour", openings_model.close_dinner),
    ).all())

    reservations_now = (db_session.query(Reservation).filter(
        Reservation.checkin is True,
        Reservation.reservation_date <= datetime.now(),
        Reservation.reservation_end >= datetime.now(),
    ).all())

    current_app.logger.debug("End of queries")
    return {
        "lunch": len(reservations_l),
        "dinner": len(reservations_d),
        "now": len(reservations_now),
    }, 200
Example #6
0
    def test_reservation_to_json_ok(self):
        reservation = Utils.insert_reservation()
        reservation2 = Utils.insert_reservation(people_number=4)
        all_reservations = [reservation, reservation2]

        json_array = BookingService.reservations_to_json(all_reservations,
                                                         what="simple")

        assert len(all_reservations) == len(json_array)
Example #7
0
    def test_check_restaurant_openings_ok(self):
        openings = Utils.create_openings_json()
        py_datetime = datetime.datetime(year=2021,
                                        month=4,
                                        day=27,
                                        hour=12,
                                        minute=30)

        # filter opening by week_day
        opening = BookingService.filter_openings(openings,
                                                 py_datetime.weekday())
        assert len(opening) == 1

        # transform opening found in a OpeningHourModel
        openings = Utils.openings_json_to_model(opening)

        # check if the restaurant is open
        result = BookingService.check_restaurant_openings(
            openings[0], py_datetime)
        assert result == True
Example #8
0
    def test_check_restaurant_openings_ko_3(self):
        openings = Utils.create_openings_json()
        py_datetime = datetime.datetime(year=2021,
                                        month=4,
                                        day=27,
                                        hour=17,
                                        minute=30)

        # filter opening by week_day
        opening = BookingService.filter_openings(openings,
                                                 py_datetime.weekday())
        assert len(opening) == 1

        # transform opening found in a OpeningHourModel
        openings = Utils.openings_json_to_model(opening)
        # test case: close dinner and py_datetime > close_lunch
        openings[0].close_dinner = None

        # check if the restaurant is open
        result = BookingService.check_restaurant_openings(
            openings[0], py_datetime)
        assert result[1] == 404
Example #9
0
    def test_get_free_tables_ok(self):
        tables = Utils.create_tables_json()
        Utils.insert_reservation(people_number=2)

        py_datetime = datetime.datetime(year=2021,
                                        month=4,
                                        day=27,
                                        hour=12,
                                        minute=30)
        free_tables = BookingService.get_free_tables(tables, 4, py_datetime,
                                                     30)

        # STILL TWO TABLES FREE
        assert len(free_tables) == 2

        Utils.delete_all_reservations()
Example #10
0
    def test_get_free_tables_ko(self):
        tables = Utils.create_tables_json()
        Utils.insert_reservation(people_number=2)
        Utils.insert_reservation(people_number=3, table_id=2)
        Utils.insert_reservation(people_number=5, table_id=1)

        py_datetime = datetime.datetime(year=2021,
                                        month=4,
                                        day=27,
                                        hour=12,
                                        minute=30)
        free_tables = BookingService.get_free_tables(tables, 4, py_datetime,
                                                     30)

        # NO MORE TABLES
        assert len(free_tables) != 1

        Utils.delete_all_reservations()
Example #11
0
def create_booking(private=False):
    if private is False:
        json = request.get_json()
    else:
        json = private
    current_app.logger.debug("Request received: {}".format(json))
    restaurant_id = json["restaurant_id"]
    user_id = json["user_id"]
    raw_friends = json["raw_friends"]
    py_datetime = datetime.strptime(json["datetime"], "%Y-%m-%dT%H:%M:%SZ")
    people_number = json["people_number"]
    current_app.logger.debug("Translated obj to vars")
    # split friends mail and check if the number is correct
    if people_number > 1:
        splitted_friends = raw_friends.split(";")
        if len(splitted_friends) != (people_number - 1):
            return HttpUtils.error_message(
                400, "You need to specify ONE mail for each person")
        current_app.logger.debug("Friends: {}".format(str(splitted_friends)))
    # if user wants to book in the past..
    if py_datetime < datetime.now() and "is_debug" not in json:
        return HttpUtils.error_message(400, "You can not book in the past!")

    # check if the user is positive
    current_user = UserService.get_user_info(user_id)
    current_app.logger.debug("user is positive ? {}".format(
        current_user.is_positive))
    if current_user.is_positive:
        return HttpUtils.error_message(401, "You are marked as positive!"), 401
    week_day = py_datetime.weekday()

    # check if the restaurant is open. 12 in open_lunch means open at lunch. 20 in open_dinner means open at dinner.
    openings = RestaurantService.get_openings(restaurant_id)
    current_app.logger.debug("Got {} openings".format(len(openings)))
    # the restaurant is closed
    if openings is None or len(openings) == 0:
        current_app.logger.debug("No open hours")
        return HttpUtils.error_message(404, "The restaurant is closed")

    opening_hour_json = BookingService.filter_openings(openings,
                                                       week_day=week_day)[0]
    current_app.logger.debug(
        "Got openings this day: {}".format(opening_hour_json))
    # the restaurant is closed
    if opening_hour_json is None:  # TODO: Test
        print("No Opening hour")
        return HttpUtils.error_message(404, "The restaurant is closed")

    # bind to obj
    opening_hour = OpeningHoursModel()
    opening_hour.fill_from_json(opening_hour_json)
    current_app.logger.debug("Binded, weekday: {}".format(
        str(opening_hour.week_day)))

    # check if restaurant is open
    response = BookingService.check_restaurant_openings(
        opening_hour, py_datetime)
    current_app.logger.debug("Restaurant checked, i got: {}".format(
        str(response)))
    if response is not True:
        return response
    # now let's see if there is a table
    """
    get the time delta (avg_time) e name from the restaurant
    """
    restaurant_info = RestaurantService.get_info(restaurant_id)
    restaurant_name = restaurant_info["name"]
    avg_time = restaurant_info["avg_time"]
    """
    get all the reservation (with the reservation_date between the dates in which I want to book)
    or (or the reservation_end between the dates in which I want to book)
    the dates in which I want to book are:
    start = py_datetime  
    end = py_datetime + avg_time
    always filtered by the people_number  
    """

    # from the list of all tables in the restaurant (the ones in which max_seats < number of people requested)
    # drop the reserved ones
    all_table_list = RestaurantService.get_tables(restaurant_id)
    if all_table_list is None:
        return HttpUtils.error_message(500, "Can't retrieve restaurant tables")

    free_tables = BookingService.get_free_tables(all_table_list, people_number,
                                                 py_datetime, avg_time)

    # if there are tables available.. get the one with minimum max_seats
    current_app.logger.debug("OK, There are {} tables available".format(
        len(free_tables)))
    if len(free_tables) > 0:
        chosen_table = BookingService.get_min_seats_table(free_tables)
        current_app.logger.debug(
            "OK, table {} has been chosen".format(chosen_table))
        # get table name
        table_name = BookingService.get_table_name(all_table_list,
                                                   chosen_table)
        current_app.logger.debug("His name is: {}".format(table_name))
        # register on db the reservation
        new_reservation = Reservation()
        new_reservation.reservation_date = py_datetime
        new_reservation.reservation_end = py_datetime + timedelta(
            minutes=avg_time)
        new_reservation.customer_id = user_id
        new_reservation.table_id = chosen_table
        new_reservation.people_number = people_number
        db_session.add(new_reservation)
        db_session.flush()
        current_app.logger.debug("Reservation saved.")
        if people_number > 1:
            # register friends
            for friend_mail in splitted_friends:
                new_friend = Friend()
                new_friend.reservation_id = new_reservation.id
                new_friend.email = friend_mail.strip()
                db_session.add(new_friend)
        else:
            splitted_friends = []
        db_session.commit()

        SendEmailService.booking_confirmation(
            current_user.email,
            current_user.firstname,
            restaurant_name,
            splitted_friends,
            new_reservation.reservation_date,
        )

        return {
            "id": new_reservation.id,
            "restaurant_name": restaurant_name,
            "table_name": table_name,
        }, 200
    else:
        return HttpUtils.error_message(404, "No tables available")
Example #12
0
 def bookRequirement(user: User, hotel: Hotel,
                     br: BookingRequirement) -> Booking:
     return BookingService.book(user, hotel, br)
Example #13
0
    def test_fitler_table_min_seats_ko(self):
        tables = Utils.create_tables_json()

        result = BookingService.filter_table_min_seat(tables, 6)
        assert len(result) != len(tables)
Example #14
0
    def test_filter_openings_ko(self):
        openings = Utils.create_openings_json()

        result = BookingService.filter_openings(openings, week_day=2)
        assert len(result) == 0
Example #15
0
    def test_get_table_name_ok(self):
        tables = Utils.create_tables_json()

        result = BookingService.get_table_name(tables, 1)
        assert result == tables[0]["name"]
Example #16
0
    def test_get_table_name_noname_ok(self):
        tables = Utils.create_tables_noname_json()

        result = BookingService.get_table_name(tables, 3)
        assert result == "Table #3"
Example #17
0
def get_hotel_reviews_wordcloud():
    # TODO: delete this
    negative_reviews_filename = "1_negative_reviews_wordcloud.png"
    positive_reviews_filename = "1_positive_reviews_wordcloud.png"
    
    filename_negative = 'datasets/hotel_reviews_booking/wordclouds/1_2_Serjeant_s_Inn_Fleet_Street_City_of_London_London_EC4Y_1LL_United_Kingdom__Negative_Review.png'
    filename_positive = 'datasets/hotel_reviews_booking/wordclouds/1_2_Serjeant_s_Inn_Fleet_Street_City_of_London_London_EC4Y_1LL_United_Kingdom__Positive_Review.png'
    # Sends the result as a zip file
    zip_name = '1_reviews.zip'
    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, 'w', compression=zipfile.ZIP_DEFLATED) as zipf:
        image_bytes = open(os.path.join(basedir, filename_negative), "rb").read()
        image_bytes = bytearray(image_bytes)
        
        positive_reviews_data = zipfile.ZipInfo(negative_reviews_filename)
        positive_reviews_data.date_time = time.localtime(time.time())[:6]
        positive_reviews_data.compress_type = zipfile.ZIP_STORED
        zipf.writestr(positive_reviews_data, image_bytes)
        
        image_bytes = open(os.path.join(basedir, filename_positive), "rb").read()
        image_bytes = bytearray(image_bytes)
        
        positive_reviews_data = zipfile.ZipInfo(positive_reviews_filename)
        positive_reviews_data.date_time = time.localtime(time.time())[:6]
        positive_reviews_data.compress_type = zipfile.ZIP_STORED
        zipf.writestr(positive_reviews_data, image_bytes)
    memory_file.seek(0)
    return send_file(memory_file, 
                    mimetype='zip', 
                    attachment_filename=zip_name,
                    as_attachment=True)


    # TODO: use the real reviews
    hotel_id = request.args.get('hotel_id')
    if not hotel_id:
        return ''
    
    booking_service = BookingService()
    all_reviews = booking_service.get_reviews(hotel_id)
    positive_reviews = booking_utils.extract_positive_reviews(all_reviews)
    negative_reviews = booking_utils.extract_negative_reviews(all_reviews)
    
    if not positive_reviews and not negative_reviews:
        return ''

    # Creates wordcloud for positive reviews.    
    positive_reviews_filename = os.path.dirname(os.path.abspath(__file__)) + '/' + str(hotel_id) + '_positive_reviews_wordcloud'
    create_wordcloud(positive_reviews, positive_reviews_filename)
    positive_reviews_filename += '.png'

    # Creates wordcloud for negative reviews.
    negative_reviews_filename = os.path.dirname(os.path.abspath(__file__)) + '/' + str(hotel_id) + '_negative_reviews_wordcloud'
    create_wordcloud(negative_reviews, negative_reviews_filename)
    negative_reviews_filename += '.png'
    
    # Sends the result as a zip file
    zip_name = str(hotel_id) + '_reviews.zip'
    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, 'w', compression=zipfile.ZIP_STORED) as zipf:
        # Positive reviews wordcloud.
        image_bytes = open(os.path.join(basedir, positive_reviews_filename), "rb").read()
        image_bytes = bytearray(image_bytes)
        
        positive_reviews_data = \
            zipfile.ZipInfo(os.path.basename(positive_reviews_filename))
        positive_reviews_data.date_time = time.localtime(time.time())[:6]
        positive_reviews_data.compress_type = zipfile.ZIP_STORED
        zipf.writestr(positive_reviews_data, image_bytes)

        # Negative reviews wordcloud.
        image_bytes = open(os.path.join(basedir, negative_reviews_filename), "rb").read()
        image_bytes = bytearray(image_bytes)
       
        negative_reviews_data = \
            zipfile.ZipInfo(os.path.basename(negative_reviews_filename))
        negative_reviews_data.date_time = time.localtime(time.time())[:6]
        negative_reviews_data.compress_type = zipfile.ZIP_STORED
        zipf.writestr(negative_reviews_data, image_bytes)
    memory_file.seek(0)
    return send_file(memory_file, 
                    mimetype='zip', 
                    attachment_filename=zip_name,
                    as_attachment=True)
Example #18
0
    def test_get_table_name_ko(self):
        tables = Utils.create_tables_json()

        result = BookingService.get_table_name(tables, 4)
        assert result == "NO_NAME"
Example #19
0
    def test_get_min_seats_table_ok(self):
        tables = Utils.create_tables_json()

        min_seat_table = BookingService.get_min_seats_table(tables)
        assert min_seat_table == 3