Exemplo n.º 1
0
def login(loginserver, address):
    connection = None
    account = None
    try:
        connection = mysql_connection.get_conn()

        if not exist_account(connection, loginserver.account):
            create_account(time.time(), connection, loginserver, address)
            gold = int(config.get("gateway", "login_give"))
            account = query_account_by_account(connection, loginserver.account)
            s = HttpUtils(config.get("api", "api_host")).get(
                config.get("api", "bind") %
                (account.id, loginserver.higher, address.split(':')[0],
                 loginserver.qudao), None)
            res = s.read()
            if 0 != gold:
                update_currency(connection, gold, 0, 0, 0, account.id)
        account = query_account_by_account(connection, loginserver.account)
    except:
        if connection is not None:
            connection.rollback()
        print traceback.print_exc()
    finally:
        if connection is not None:
            connection.close()
    return account
Exemplo n.º 2
0
    def get_user_info(user_id: int):
        response = HttpUtils.make_get_request(
            "{}/{}".format(USER_MICROSERVICE_URL, user_id)
        )
        if response is None:
            return HttpUtils.error_message(500, "Can't retrieve info about yourself")

        user = UserModel()
        user.fill_from_json(response)
        return user
Exemplo n.º 3
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
Exemplo n.º 4
0
 def get_openings(restaurant_id: int):
     response = HttpUtils.make_get_request(
         "{}/{}/openings".format(RESTAURANTS_MICROSERVICE_URL, restaurant_id)
     )
     if response is None:
         return None
     return response["openings"]
Exemplo n.º 5
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
Exemplo n.º 6
0
def check_in(reservation_id):
    reservation = db_session.query(Reservation).filter_by(
        id=reservation_id).first()
    if reservation is not None:
        reservation.checkin = True
        db_session.commit()
        db_session.flush()
        return {"code": 200, "message": "Success"}, 200
    return HttpUtils.error_message(404, "Reservation not found")
Exemplo n.º 7
0
def delete_booking(reservation_id, user_id):
    query = (db_session.query(Reservation).filter_by(
        id=reservation_id).filter_by(customer_id=user_id))

    to_delete = query.first()
    if to_delete is None:
        return HttpUtils.error_message(404, "Reservation not Found")

    query.delete()
    db_session.commit()
    return {"code": 200, "message": "Deleted Successfully"}, 200
Exemplo n.º 8
0
    def replace_with_restaurant(reservation):  # pragma: nocover
        response = HttpUtils.make_get_request(
            "{}/table/{}".format(RESTAURANTS_MICROSERVICE_URL, reservation.table_id)
        )

        current_app.logger.debug("ok, adding")
        r2 = ReservationRestaurantModel()
        r2.fill_from_Reservation(reservation)

        r2.addTable(response)
        current_app.logger.debug("added")
        return r2
Exemplo n.º 9
0
def update_booking(reservation_id):
    json = request.get_json()

    response, code = delete_booking(reservation_id, json["user_id"])
    if code != 200:
        return code

    response, code = create_booking(json)
    if code != 200:
        return HttpUtils.error_message(
            500,
            "Internal Error, the booking has been deleted, please replace it")
    return response, code
Exemplo n.º 10
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
Exemplo n.º 11
0
    def replace_with_customer(reservation):  # pragma: nocover
        response = HttpUtils.make_get_request(
            "{}/table/{}".format(RESTAURANTS_MICROSERVICE_URL, reservation.table_id)
        )

        current_app.logger.debug("ok, adding")
        r2 = ReservationCustomerModel()
        r2.fill_from_Reservation(reservation)

        r2.addTable(response)
        current_app.logger.debug("added table")

        customer = UserService.get_user_info(reservation.customer_id)
        r2.addCustomer(customer)
        return r2
Exemplo n.º 12
0
 def handle(self, queue):
     while not self.__close:
         try:
             rebates = queue.getall(20, True, 20)
             for rebate in rebates:
                 js = "["
                 for r in rebate:
                     js += json.dumps(r.__dict__)
                     js += ","
                 js += "]"
                 js = js.replace(",]", "]")
                 reqdata = {'jsonArray': js}
                 HttpUtils(config.get("api", "api_host")).post(
                     config.get("api", "consumption_url"), reqdata)
         except Empty:
             gl.get_v("serverlogger").logger.info("Received timeout")
         except:
             print traceback.print_exc()
Exemplo n.º 13
0
        if len(sys.argv) == 4:  # The Request is given as a single string
            config['application_id'] = str(sys.argv[2])
            config['use_iqas'] = True
            config['iqas_request'] = json.loads(str(sys.argv[3]))
        else:  # Direct consumption without iQAS
            config['application_id'] = "direct_" + str(sys.argv[2])
            config['use_iqas'] = False
            config['iqas_request'] = "NA"
            config['request_id'] = "direct"
            topics_to_subscribe = str(sys.argv[2]).split(",")

        if config['use_iqas']:
            config['iqas_request']['application_id'] = config['application_id']
            base_url_for_requests = "http://" + config[
                'iqas_api_endpoint'] + "/requests"
            status_code, response = HttpUtils.post_to_rest_endpoint(
                url=base_url_for_requests, dictionary=config['iqas_request'])
            config['request_id'] = response['request_id']

            if status_code == 200:
                ready = False
                retries = 0
                while not ready and retries < MAX_RETRIES:
                    status_code2, response2 = HttpUtils.get_from_rest_endpoint(
                        url=base_url_for_requests + "/" + config['request_id'])
                    if response2['current_status'] == 'ENFORCED':
                        break
                    else:
                        time.sleep(1)
                        retries += 1

            time.sleep(5)
Exemplo n.º 14
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")
Exemplo n.º 15
0
    def check_restaurant_openings(opening_hour, py_datetime):
        only_time = py_datetime.time()

        # strange situation.. but it could happen
        # opening hour is in db but the restaurant is closed both lunch and dinner
        if opening_hour.open_lunch is None and opening_hour.open_dinner is None:
            return HttpUtils.error_message(404, "The restaurant is closed")

        # if the restaurant is open only at lunch or at dinner do some checks..
        if opening_hour.open_lunch is None or opening_hour.close_lunch is None:
            # calc the projection (py_datetime.date combined with opening hour)

            open_dinner_projection = datetime.combine(
                py_datetime.date(), opening_hour.open_dinner
            )
            if opening_hour.close_dinner < opening_hour.open_dinner:
                close_dinner_projection = datetime.combine(
                    py_datetime.date() + timedelta(days=1),
                    opening_hour.close_dinner,
                )
            else:
                close_dinner_projection = datetime.combine(
                    py_datetime.date(), opening_hour.close_dinner
                )

            if (
                py_datetime > close_dinner_projection
                or py_datetime < open_dinner_projection
            ):
                return HttpUtils.error_message(404, "The restaurant is closed")

        if (opening_hour.open_dinner is None or opening_hour.close_dinner is None) and (
            only_time < opening_hour.open_lunch or only_time > opening_hour.close_lunch
        ):
            return HttpUtils.error_message(404, "The restaurant is closed")

        # if the restaurant is opened both at dinner and lunch
        if opening_hour.open_lunch is not None and opening_hour.open_dinner is not None:
            # asked for some hours outside the opening hours
            if only_time < opening_hour.open_lunch:
                if opening_hour.close_dinner < opening_hour.open_dinner:
                    if only_time > opening_hour.close_dinner:
                        return HttpUtils.error_message(404, "The restaurant is closed")
                else:
                    return HttpUtils.error_message(404, "The restaurant is closed")
            if (
                only_time < opening_hour.open_dinner
                and only_time > opening_hour.close_lunch
            ):
                return HttpUtils.error_message(404, "The restaurant is closed")
            if opening_hour.close_dinner < opening_hour.open_dinner:
                close_dinner_projection = datetime.combine(
                    py_datetime.date() + timedelta(days=1),
                    opening_hour.close_dinner,
                )
            else:
                close_dinner_projection = datetime.combine(
                    py_datetime.date(), opening_hour.close_dinner
                )
            if py_datetime > close_dinner_projection:
                return HttpUtils.error_message(404, "The restaurant is closed")
        return True
Exemplo n.º 16
0
 def get_info(restaurant_id: int):
     return HttpUtils.make_get_request(
         "{}/{}".format(RESTAURANTS_MICROSERVICE_URL, restaurant_id)
     )