Ejemplo n.º 1
0
def choose_hour(update, context):
    i = 0
    while i < len(HOURS):

        if update.message.text in HOURS[i]:
            check = sess.query(Reservation).filter_by(
                day=date(2019, int(userState[update.message.chat.id]['month']),
                         int(userState[update.message.chat.id]['day'])),
                slot=update.message.text).first()
            if check is None:
                res = Reservation(
                    user_id=update.message.chat.id,
                    day=date(2019,
                             int(userState[update.message.chat.id]['month']),
                             int(userState[update.message.chat.id]['day'])),
                    slot=update.message.text)
                sess.add(res)
                sess.commit()
                userState[update.message.chat.id] = {}
                update.message.reply_text('Time reserved successfully.')
                return True
            else:
                update.message.reply_text('This hour is already reserved.')
                return False
        i += 1
    update.message.reply_text('This hour is not available to reserve.')
    return False
Ejemplo n.º 2
0
    def insert_reservation(
        py_datetime=datetime.datetime(year=2021, month=4, day=27, hour=12, minute=30),
        avg_time=30,
        people_number=2,
        table_id=3,
        user_id=1,
    ):
        db_session = current_app.config["DB_SESSION"]

        friends_mail = []
        if people_number > 1:
            for n in range(1, people_number):
                friends_mail.append("friend{}@me.com".format(n))

        # register on db the reservation
        new_reservation = Reservation()
        new_reservation.reservation_date = py_datetime
        new_reservation.reservation_end = py_datetime + datetime.timedelta(
            minutes=avg_time
        )
        new_reservation.customer_id = user_id
        new_reservation.table_id = table_id
        new_reservation.people_number = people_number
        db_session.add(new_reservation)
        db_session.flush()
        if people_number > 1:
            for mail in friends_mail:
                new_friend = Friend()
                new_friend.reservation_id = new_reservation.id
                new_friend.email = mail.strip()
                db_session.add(new_friend)
        db_session.commit()

        return new_reservation
Ejemplo n.º 3
0
def book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        building = form.building.data
        roomNum = form.room.data
        client = form.renter.data
        startDate = form.startDate.data
        endDate = form.endDate.data

        #write to database
        aRoom = db.session.query(Room).filter_by(building_id=building,
                                                 number=roomNum).first()
        if not aRoom:
            err = "Room number " + str(
                roomNum) + " is not valid for the building " + str(building)
            return render_template('error.html', msg=err)
        aClient = db.session.query(Client).filter_by(name=client).first()
        if not aClient:
            session['bookInfo'] = json.dumps({
                'room': roomNum,
                'newRenterName': client,
                'bookRoomId': xstr(aRoom.roomId),
                'stDate': xstr(startDate),
                'endDate': xstr(endDate)
            })
            return redirect(url_for('newRenter'))
        res = Reservation(arrive=startDate,
                          depart=endDate,
                          roomId=aRoom.roomId,
                          clientId=aClient.clientId)

        termsDict = {
            'building': xstr(building),
            'room': roomNum,
            'client': '',
            'stDate': xstr(startDate),
            'endDate': xstr(endDate)
        }
        preRes = doSearch(termsDict)
        if bookDateCompare(preRes, termsDict):
            return render_template(
                'error.html',
                msg="There is an issue with that room and date combination")
        try:
            db.session.add(res)
            db.session.commit()
        except (exc.InvalidRequestError, exc.ProgrammingError):
            db.session.rollback()
            err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
            return render_template('error.html', msg=err)

    return render_template('book.html', form=form)
Ejemplo n.º 4
0
def choose_hour(update, context):
    hours = get_hours()
    if update.message.text in hours:
        splitted_time = update.message.text.split(':')
        chosen_day = datetime(YEAR, int(context.user_data['month']), int(context.user_data['day']), int(splitted_time[0]), int(splitted_time[1]), 0)
        check = sess.query(Reservation).filter_by(
            day=chosen_day,
            slot=update.message.text
        ).first()
        if check is None:
            res = Reservation(
                user_id=update.message.chat.id,
                day=chosen_day,
                slot=update.message.text
            )
            sess.add(res)
            waitinglist = sess.query(WaitingList).filter(
                WaitingList.user_id == update.message.chat.id,
                WaitingList.day == date(chosen_day.year, chosen_day.month, chosen_day.day),
            ).first()
            if waitinglist:
                sess.delete(waitinglist)
            sess.commit()

            text = 'Time `' + chosen_day.strftime("%Y-%m-%d %H:%M") + '` reserved successfully'
            update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(base.main_menu, resize_keyboard=True), parse_mode=ParseMode.MARKDOWN)
            return ConversationHandler.END
        update.message.reply_text('This hour is already reserved')
    elif update.message.text == 'Back':
        context.user_data['wrong_day'] = True
        choose_month(update, context)
        return DAY
    elif update.message.text == 'Subscribe to waiting list':
        response = subscribe_user_to_waiting_list(context, update.message.chat.id)
        update.message.reply_text(response, parse_mode=ParseMode.MARKDOWN)
        base.cancel(update, context)
        return ConversationHandler.END
    elif update.message.text == 'Cancel':
        base.cancel(update, context)
        return ConversationHandler.END
    else:
        context.user_data['wrong_hour'] = True
        update.message.reply_text('Wrong hour')
    choose_day(update, context)
    return HOUR
Ejemplo n.º 5
0
def newRenter():
    form = NewRenterForm(request.form)
    cookieDir = json.loads(session['bookInfo'])
    form.name.data = cookieDir['newRenterName']
    if request.method == 'POST' and form.validate():
        aName = form.name.data
        aNumber = form.phone.data
        aEmail = form.email.data

        #get next client id from table
        newClientId = db.session.query(Client).order_by(desc(
            Client.clientId)).first().clientId + 1
        newClient = Client(name=aName,
                           clientId=newClientId,
                           phone=aNumber,
                           email=aEmail)
        db.session.add(newClient)
        db.session.commit()

        newRes = Reservation(arrive=parser.parse(cookieDir['stDate']),
                             depart=parser.parse(cookieDir['endDate']),
                             roomId=int(cookieDir['bookRoomId']),
                             clientId=newClientId)
        cookieDir['building'] = 'None'
        cookieDir['client'] = ''
        #cOPY From book
        cookieDir['building'] = 'None'
        preRes = doSearch(cookieDir)
        if bookDateCompare(preRes, cookieDir):
            return render_template(
                'error.html',
                msg=
                "There is an issue with that room and date combination. The new client was still added to the database."
            )
        try:
            db.session.add(newRes)
            db.session.commit()
        except (exc.InvalidRequestError, exc.ProgrammingError):
            db.session.rollback()
            err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
            return render_template('error.html', msg=err)

        return redirect(url_for('book'))

    return render_template('newClient.html', form=form)
Ejemplo n.º 6
0
def submit(start_date, end_date, barcodes, user_id):
    try:
        start_date = dateutil.parser.parse(start_date).date()
        end_date = dateutil.parser.parse(end_date).date()
    except ValueError:
        emit("error", "Please enter a valid start and end date.")
        return
    user_query = User.query.filter_by(t_number=user_id).first()
    if user_query:
        reservation = Reservation(
            user_id=user_id, start_date=start_date, end_date=end_date
        )
        db.session.add(reservation)
        for barcode in barcodes:
            gear = GearBarcode.query.filter_by(barcode=barcode).first()
            if gear:
                reservation.barcodes.append(gear)
        db.session.commit()
        emit("submit_success", f"{reservation.id:08d}")
    else:
        emit("error", "Please scan/enter a Student ID barcode or T-number")
Ejemplo n.º 7
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")
Ejemplo n.º 8
0
def addReservation(admin):
    if request.method == 'POST':
        name = request.form['name']
        phone = request.form['phone']
        numPeople = int(request.form['numPeople'])
        moreInfo = request.form['moreInfo']
        added_date = int(time.time())
        added_by = admin.username
        mytype = int(request.form['type'])

        if (name and phone and numPeople > 0 and (mytype in range(1, 4))):
            if (mytype == 1):
                table = request.form['table']
                withBBQ = strtobool(request.form['withBBQ'])
                date = int(request.form['date'])
                pricePerson = int(request.form['pricePerson'])
                if (date and pricePerson):
                    res = Reservation(name=name,
                                      phone=phone,
                                      numPeople=numPeople,
                                      moreInfo=moreInfo,
                                      isPicnic=True,
                                      isCamping=False,
                                      isResto=False,
                                      added_date=added_date,
                                      added_by=added_by)
                    db.session.add(res)
                    db.session.commit()
                    p = Picnic(table=table,
                               withBBQ=withBBQ,
                               date=date,
                               pricePerson=pricePerson,
                               res_id=res.id)
                    db.session.add(p)
                    db.session.commit()
                    return "1"

            if (mytype == 2):
                table = request.form['table']
                withBBQ = strtobool(request.form['withBBQ'])
                withMatress = strtobool(request.form['withMatress'])
                withTent = strtobool(request.form['withTent'])
                withFood = strtobool(request.form['withFood'])
                fromDate = int(request.form['fromDate'])
                toDate = int(request.form['toDate'])
                pricePerson = int(request.form['pricePerson'])
                if (fromDate and toDate and fromDate <= toDate
                        and pricePerson):
                    res = Reservation(name=name,
                                      phone=phone,
                                      numPeople=numPeople,
                                      moreInfo=moreInfo,
                                      isPicnic=False,
                                      isCamping=True,
                                      isResto=False,
                                      added_date=added_date,
                                      added_by=added_by)
                    db.session.add(res)
                    db.session.commit()
                    c = Camping(table=table,
                                withBBQ=withBBQ,
                                withMatress=withMatress,
                                withTent=withTent,
                                withFood=withFood,
                                fromDate=fromDate,
                                toDate=toDate,
                                pricePerson=pricePerson,
                                res_id=res.id)
                    db.session.add(c)
                    db.session.commit()
                    return "1"

            if (mytype == 3):
                table = request.form['table']
                date = int(request.form['date'])
                if (date):
                    res = Reservation(name=name,
                                      phone=phone,
                                      numPeople=numPeople,
                                      moreInfo=moreInfo,
                                      isPicnic=False,
                                      isCamping=False,
                                      isResto=True,
                                      added_date=added_date,
                                      added_by=added_by)
                    db.session.add(res)
                    db.session.commit()
                    r = Resto(table=table, date=date, res_id=res.id)
                    db.session.add(r)
                    db.session.commit()
                    return "1"

        return error("Missing parameters")
    return error("Send POST request")