def reservation(room=None): form = ReservationForm() form.room.choices = getavailable() if form.validate_on_submit(): room = Room.query.filter_by(rname=form.room.data).first() reserve = Reservation(name=form.name.data, email=form.email.data, room=form.room.data, adults=form.adults.data, children=form.children.data, checkin=form.checkin.data, checkout=form.checkout.data, user=current_user) if form.NationalID.data: reserve.gender = male_or_female(int(form.NationalID.data)) reserve.birthdate = Date_from_ID(int(form.NationalID.data)) reserve.NationalID = form.NationalID.data room.number -= 1 db.session.add(reserve) db.session.commit() flash('Your Reservation is Succesfull', 'success') return redirect(url_for('home')) elif request.method == 'GET' and current_user.is_authenticated: form.name.data = current_user.username form.email.data = current_user.email if room: form.room.data = room return render_template('reservation.html', form=form)
def makeReservation(): data = request.get_json()['trip_id'] try: pattern = Pattern.query.filter(Pattern.trip_id==data).first() new_reservation = Reservation(user_id=current_user.id, trip_id=data) if pattern != None: new_reservation.date = pattern.date_time db.session.add(new_reservation) db.session.commit() except Exception as ex: print(ex) db.session.rollback() return make_response('An error ocurred', 500) return make_response('Reservation successful', 200)
def test_create_a_reservation_missing_key(self): reservation = Reservation() error = False try: reservation.deserialize({ 'resource_id' : 1, 'user_id' : 1, 'start_time' : datetime.now(), 'end_time': datetime.now() + timedelta(minutes=30), 'duration': '00:30' }) except KeyError as e: self.assertTrue("Invalid reservation: missing" in e.message) error = True self.assertTrue(error)
def update_reservation(id: int): reservation = Reservation.query.filter_by(id=id).first() if reservation is None: return not_found('reserva não encontrada') data = request.get_json() or {} error = Reservation.check_data(data=data) if 'user_id' in data and data['user_id'] is not None and \ User.query.get(data['user_id']) is None: error = 'usuário não existe' if 'thirdparty_id' in data and data['thirdparty_id'] is not None and \ Thirdparty.query.get(data['thirdparty_id']) is None: error = 'terceiro não existe' if Reservation.query.filter( Reservation.date_start >= data['date_start']).filter( Reservation.date_start <= data['date_end']).all( ) or Reservation.query.filter( Reservation.date_end >= data['date_start']).filter( Reservation.date_end <= data['date_end']).all(): error = 'já existe um evento nesse período' if error: return bad_request(error) reservation.from_dict(data) try: db.session.commit() except Exception: return internal_server() return jsonify(reservation.to_dict())
def index(): form = ReservationForm() if form.validate_on_submit(): if Classroom.query.filter_by( ClassroomNum=form.classroom.data).first() == None: flash("No such classroom") else: inf = validate_all( form.From.data, form.To.data, form.reservationDate.data, form.endreservationDate.data, Classroom.query.filter_by( ClassroomNum=form.classroom.data).first().id) if (inf == True): reservation = Reservation( user_id=current_user.id, classroom_num=form.classroom.data, classroom_id=Classroom.query.filter_by( ClassroomNum=form.classroom.data).first().id, fromTime=datetime.combine(form.reservationDate.data, form.From.data), toTime=datetime.combine(form.endreservationDate.data, form.To.data)) db.session.add(reservation) db.session.commit() flash("New reservation added!") else: flash(inf) return render_template('index.html', title="Home", form=form, classrooms=Classroom.query.all())
def test_create_a_reservation_wrong_value(self): reservation = Reservation() error = False try: reservation.deserialize({ 'resource_id' : 1, 'resource_name' : "test_res", 'user_id' : "not_integer", 'start_time' : datetime.now(), 'end_time': datetime.now() + timedelta(minutes=30), 'duration': '00:30' }) except ValueError as e: self.assertTrue("body of request contained bad or no data" in e.message) error = True self.assertTrue(error)
def make_reservation(): """ make a reservation """ user_id = current_user.id form = ReservationForm() rid = None if form.validate_on_submit(): res_datetime = None reservation_obj = Reservation( user_id=user_id, num_of_customer=form.num_of_customers.data, res_datetime=form.reservation_dateTime.data.strftime( '%Y-%m-%d %H:%M'), special_desc=form.special_desc.data) try: # add reservation_obj to the database, default status = 0; 1 for created (confirmed by user) db.session.add(reservation_obj) db.session.commit() # r = Reservation.query.filter(and_(Reservation.user == user_id, # Reservation.res_datetime == res_datetime)).first() # rid=r.id flash('You have submitted a reservation request.') except: # flash('Error: unknown!') session['rid'] = rid # redirect to reservation confirmation page return redirect(url_for('reservation.confirm_reservation')) # load reservation template return render_template('reservation/reservation.html', form=form, title="Make a Reservation")
def write_db(con, typ, com, sta, end, cos): #Convert to Python datetime sta = datetime.strptime(sta, '%Y-%m-%d') end = datetime.strptime(end, '%Y-%m-%d') #Add new entry entry = Reservation(confirmation=con, type=typ, company=com, start_date=sta, end_date=end, cost=cos) db.session.add(entry) db.session.commit() #Verify that new entry has been added result = Reservation.query.filter_by(confirmation=con).first() return jsonify({ 'confirmation': result.confirmation, 'type': result.type, 'company': result.company, 'start_date': result.start_date, 'end_date': result.end_date, 'cost': result.cost })
def search(): data = request.get_json() startDate = data["startDate"] endDate = data["endDate"] guest_id = data["user"] num_guest = data["numGuest"] property_id = data["property"] date = data["startDate"] date_format = "%Y-%m-%d" first = startDate[0:10] second = endDate[0:10] a = datetime.strptime(first, date_format) b = datetime.strptime(second, date_format) delta = b - a numdays = delta.days for i in range(numdays + 1): # a = timedelta(days=1) increase = a + timedelta(days=i) newReservation = Reservation(guest_id=guest_id, property_id=property_id, date=increase, numGuests=num_guest, date_range=f'{first} - {second}') db.session.add(newReservation) db.session.commit() return jsonify(data)
def book(): form = FormBook() if form.validate_on_submit(): name = form.name.data lastname = form.lastname.data date_from = form.date_from.data date_to = form.date_to.data select_adult = form.select_adult.data select_child = form.select_child.data reservation = Reservation(name, lastname, date_from, date_to, select_adult, select_child) reservation.add() return redirect(url_for("thank_you.thank_you")) return render_template('book_now.html', form=form, pages=pages)
def get_reservations_of_user(u_id): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) user = User.query.get_or_404(u_id) data = Reservation.to_collection_dict(user.reservations, page, per_page, 'api.get_reservations_of_user', u_id=u_id) return jsonify(data)
def add_one_reservation(self, resource_id, resource_name, user_id): reservation = Reservation() reservation.deserialize({ 'resource_id': resource_id, 'resource_name': resource_name, 'user_id': user_id, 'start_time': datetime.now(), 'end_time': datetime.now() + timedelta(minutes=90), 'duration': '01:30' }) db.session.add(reservation) db.session.commit() return reservation.id
def create_reservation(): data = request.get_json() or {} error = Reservation.check_data(data=data, new=True) if 'user_id' in data and data['user_id'] is not None and \ User.query.get(data['user_id']) is None: error = 'usuário não existe' if 'thirdparty_id' in data and data['thirdparty_id'] is not None and \ Thirdparty.query.get(data['thirdparty_id']) is None: error = 'terceiro não existe' if Reservation.query.filter( Reservation.date_start >= data['date_start']).filter( Reservation.date_start <= data['date_end']).all( ) or Reservation.query.filter( Reservation.date_end >= data['date_start']).filter( Reservation.date_end <= data['date_end']).all(): error = 'já existe um evento nesse período' if error: return bad_request(error) reservation = Reservation() reservation.from_dict(data) try: db.session.add(reservation) db.session.commit() except Exception: return internal_server() return jsonify(reservation.to_dict()), 201
def test_create_a_reservation(self): user, resource, tag, tag_2 = self.setup_dummy_data() reservation = Reservation() # business logic in enforced in server level. reservation.deserialize({ 'resource_id' : resource.id, 'resource_name' : resource.name, 'user_id' : user.id, 'start_time' : datetime.now(), 'end_time': datetime.now() + timedelta(minutes=30), 'duration': '00:30' }) db.session.add(reservation) db.session.commit() user = User.query.filter_by(email="*****@*****.**").first() resource = [res for res in user.resources][0] user_res = [res for res in user.reservations][0] resource_res = [res for res in resource.reservations][0] self.assertEqual(user_res, resource_res) self.assertEqual(user_res.resource_id, resource.id) self.assertEqual(user_res.user_id, user.id) self.assertEqual(user_res.resource_name, resource.name) self.assertEqual(user_res.duration, '00:30')
def create_reservation(): data = request.get_json() or {} u_id = g.current_user.id if 'listingId' not in data: return bad_request('Must include listing ID') data['user_id'] = u_id reservation = Reservation() reservation.from_dict(data) db.session.add(reservation) # block the date check_in_date = reservation.check_in_date check_out_date = reservation.check_out_date # check not continuously dates listingDates = ListingDate.query.filter_by( listing_id=reservation.listing_id).filter( ListingDate.date <= check_out_date).filter( ListingDate.date >= check_in_date).all() if len(listingDates) > 0: return error_response(202, 'Please choose a continuous dates range') # serve the date date_generated = [ check_in_date + timedelta(days=x) for x in range(0, (check_out_date - check_in_date).days + 1) ] for gen_d in date_generated: print(gen_d.strftime('%d/%m/%Y')) listingDate = ListingDate() listingDate.listing_id = data['listingId'] listingDate.date = gen_d listingDate.date_type = 'reserved' db.session.add(listingDate) db.session.commit() response = jsonify(reservation.to_dict()) response.status_code = 201 return response
def validation_reservations(request): reponse = trierDemande(request, False) Reservations = reponse[0] reservations = list() #Pour afficher dans la template l'ensemble des réservations effectué par commerce et afficher la date limite de retrait for reservation in Reservations: montant_reservation = float() for produit in reservation[1]: montant_reservation = montant_reservation + round( ( (produit[0].prixproduit - ((produit[0].prixproduit * produit[0].tauxremise)/100)) * produit[1]),2 ) datelimite = datetime.now() + timedelta(days=reservation[0].joursretrait) client = Client.objects.get(numclient =request.user.id) new_reservation = Reservation(numclient=client, montantreservation = montant_reservation, numcommerce=reservation[0], datelimitereservation=datelimite, paiementrealise=False) new_reservation.save() reservations.append(new_reservation) for produit in reservation[1]: new_reserver = Reserver(numproduit=produit[0], numreservation=new_reservation, quantitereserve=produit[1]) new_reserver.save() produit[0].quantitedisponible = produit[0].quantitedisponible - produit[1] produit[0].save() type_demande = "reservation" request = init_reservation(request) return render(request, 'panier/valide.html', locals())
def reserve_room_page(id): room = Room.get_by_id(id) if request.method == 'POST': data = request.form reservation = Reservation.create(**data, room_id=id, user_id=current_user.id) return redirect(url_for('bookings_page')) data = { 'room': room, 'check_in_date': session.pop('check_in_date', date.today().strftime("%Y-%m-%d")), 'check_out_date': session.pop('check_out_date', date.today().strftime("%Y-%m-%d")), 'num_occupants': session.pop('num_occupants', 1), } return render_template('reserve.html', **data)
def reservation(): ses_id = request.args.get('session_id') if ses_id is None: return '', 404 sessio = Session_cinema.query.filter_by(film_id=ses_id).first() if sessio is None: pass randomNumber = random.randrange(1000, 10000) res1 = ResSeats.query.order_by( ResSeats.id.desc()).filter_by(res_id=sessio.film_id).limit(1).first() resIDsave = Reservation(res1.res_id, res1.summa, randomNumber) db.session.add(resIDsave) db.session.commit() res = ResSeats.query.order_by(ResSeats.id.desc()).filter_by( res_id=sessio.film_id).limit(1).first() #выбрал последнее return render_template('reservation.html', sessio=sessio, res=res, randomNumber=randomNumber)
def book_studyroom(slot_id): slot = get_slot(slot_id) existing_reservation = False reservations = Reservation.query.filter_by( user_email=current_user.get_id()).all() for reservation in reservations: reservation_slot = get_slot(reservation.slot_id) if reservation_slot.date == slot.date and reservation_slot.morning == slot.morning: existing_reservation = True break if slot.morning: time = StudyRoom.query.filter_by( id=slot.studyroom_id).first().close_morning close = datetime(year=slot.date.year, month=slot.date.month, day=slot.date.day, hour=time.hour, minute=time.minute) else: time = StudyRoom.query.filter_by( id=slot.studyroom_id).first().close_evening close = datetime(year=slot.date.year, month=slot.date.month, day=slot.date.day, hour=time.hour, minute=time.minute) if slot.available_seats > 0 and not existing_reservation and datetime.utcnow( ) < close: reservation = Reservation(user_email=current_user.get_id(), slot_id=slot_id) setattr(slot, 'available_seats', slot.available_seats - 1) db.session.add(reservation) db.session.commit() return redirect(url_for('users.dashboard')) else: flash( 'You can\'t reserve this study room: there are not available seats or you already have a reservation or the time is over.', 'error') return redirect( url_for('studyrooms.view_availability', id=slot.studyroom_id))
def reserve(): data = request.get_json() startDate = data["startDate"] endDate = data["endDate"] num_guest = data["numGuest"] property_id = data["property"] date = data["startDate"] date_format = "%Y-%m-%d" first = startDate[0:10] second = endDate[0:10] a = datetime.strptime(first, date_format) b = datetime.strptime(second, date_format) delta = b - a numdays = delta.days for i in range(numdays + 1): date = a + timedelta(days=i) newReservation = Reservation(user=current_user, property_id=property_id, date=date, numGuests=num_guest, date_range=f'{first} - {second}') db.session.add(newReservation) db.session.commit() return {"success": True}
def create_reservation(data): response = {'status': 'success'} reservation_time = datetime.datetime.strptime(data.get('reservation_datetime'), '%Y-%m-%d %H:%M:%S') if datetime.datetime.now() > reservation_time: response.update({'status': 'error', 'message': f'cannot book for date {reservation_time}'}) return response user = User.query.filter_by(phone_number=data.get('phone_number')).first() if user is None: print('user not present') user = User(name=data.get('user_name'), phone_number=data.get('phone_number'), email=data.get('email')) db.session.add(user) # now check table availability capacity = int(data.get('num_guest')) tables = Table.query.filter(Table.restaurant_id == data.get('restaurant_id'), Table.capacity >= capacity).order_by( Table.capacity.asc()).all() t_ids = [t.id for t in tables] print(f'table ids which has the capacity : {t_ids}') if not t_ids: # no tables with that size print(f'no tables available for the capacity : {capacity}') response.update({'status': 'error', 'message': f'no tables available for the capacity : {capacity}'}) return response # check reservations begin_range = reservation_time - datetime.timedelta(hours=DEFAULT_RESERVATION_LENGTH) end_range = reservation_time + datetime.timedelta(hours=DEFAULT_RESERVATION_LENGTH) reservations = Reservation.query.join(Reservation.table).filter(Table.id.in_(t_ids), Reservation.reservation_time >= begin_range, Reservation.reservation_time <= end_range).order_by( Table.capacity.desc()).all() # Reservation.query.join(Reservation.table).filter(Table.id.in_([2,3])).order_by(Table.capacity.desc()).all() print(f'reservations : {reservations}') if reservations: if len(t_ids) == len(reservations): # no available tables, sorry # still add guest print(f'not available') db.session.commit() response.update({'status': 'error', 'message': f'tables not available for given time'}) return response else: # get available table table_id = (set(t_ids) - set([r.table.id for r in reservations])).pop() print(f' available table: {table_id}') user_id = int(User.query.filter_by(phone_number=data.get('phone_number')).with_entities(User.id).first()[0]) print(f'user id : {user_id}') reservation = Reservation(restaurant_id=data.get('restaurant_id'), table_id=table_id, user_id=user_id, num_guests=capacity, reservation_time=reservation_time) else: # we are totally open user_id = int(User.query.filter_by(phone_number=data.get('phone_number')).with_entities(User.id).first()[0]) table_id = int(Table.query.filter_by(id=int(t_ids[0]), restaurant_id=data.get('restaurant_id')).with_entities( Table.id).first()[0]) reservation = Reservation(restaurant_id=data.get('restaurant_id'), table_id=table_id, user_id=user_id, num_guests=capacity, reservation_time=reservation_time) db.session.add(reservation) db.session.commit() response.update({'message': f'reservation successful', 'details': data}) print(response) if response['status'] == 'success': pass # notify(response) return response
def bookings_page(): reservations = Reservation.fetch_users_reservation(current_user.id) data = { 'reservations' : reservations } return render_template('bookings.html', **data)
def insert_data(app): with app.app_context(): # insert test user new_user = User(id=1, username='******', email='*****@*****.**', gender='male', phone='123123123') new_user.set_password('test') other_user = User(id=2, username='******', email='*****@*****.**', gender='female', phone='234234234') other_user.set_password('other') # insert test accommodation new_acc = Accommodation(id=1, host_id=new_user.id, num_guests=2, num_bedrooms=2, num_beds=2, num_bathrooms=2, description='Such a good house', city='Sydney', country='Australia', price=99999, property_type='Space ship', num_reviews=999, amenities=['wifi', 'tv', 'kangaroo-friendly'], is_deleted=False) # insert deleted test accommodation deleted_acc = Accommodation( id=2, host_id=new_user.id, num_guests=2, num_bedrooms=2, num_beds=2, num_bathrooms=2, description='This house is deleted', city='Sydney', country='Australia', price=99999, property_type='Space ship', num_reviews=999, amenities=['wifi', 'tv', 'kangaroo-friendly'], is_deleted=True) now = datetime.now() yesterday = (now - timedelta(days=1)).strftime('%Y-%m-%d') today = now.strftime('%Y-%m-%d') tomorrow = (now + timedelta(days=1)).strftime('%Y-%m-%d') tomorrow_tomorrow = (now + timedelta(days=2)).strftime('%Y-%m-%d') # insert reservation with check in date in the past past_reservation = Reservation(id=1, accommodation_id=new_acc.id, guest_id=new_user.id, check_in_date=yesterday, check_out_date=today, status='checked_out') # insert reservation with check in date in the past and check out date in future current_reservation = Reservation(id=4, accommodation_id=new_acc.id, guest_id=new_user.id, check_in_date=today, check_out_date=tomorrow, status='checked_in') # insert reservation with check in date in the future future_reservation = Reservation(id=2, accommodation_id=new_acc.id, guest_id=new_user.id, check_in_date=tomorrow, check_out_date=tomorrow_tomorrow, status='booked') cancelled_reservation = Reservation(id=3, accommodation_id=new_acc.id, guest_id=new_user.id, check_in_date=yesterday, check_out_date=today, status='cancelled') db.session.add(new_user) db.session.add(other_user) db.session.add(new_acc) db.session.add(deleted_acc) db.session.add(past_reservation) db.session.add(current_reservation) db.session.add(future_reservation) db.session.add(cancelled_reservation) db.session.commit()
def post(self): parser = reqparse.RequestParser() parser.add_argument('guest_id', type=int, required=True, help='guest_id cannot be blank.') parser.add_argument('accommodation_id', type=int, required=True, help='accommodation_id cannot be blank.') parser.add_argument('num_guests', type=int, required=True, help='num_guests cannot be blank.') parser.add_argument('check_in', required=True, type=DateType) parser.add_argument('check_out', required=True, type=DateType) parser.add_argument('token', required=True, help='Token required.') args = parser.parse_args() user = User.check_token(args.token) if not user: return { 'msg': 'You must be logged in to create a reservation.' }, 401 acc = Accommodation.query.filter( (Accommodation.id == args.accommodation_id) & (Accommodation.is_deleted == False)).first() if not acc: return { 'msg': 'Reservation could not be made as the accommodation does not exist' }, 404 # ensure check out is after check in if datetime.strptime(args.check_in, '%Y-%m-%d') >= datetime.strptime( args.check_out, '%Y-%m-%d'): return {'msg': 'check in date must be before check out date'}, 400 # use accommodation_id to find all reservations that conflict with given checkin/out dates # TODO: need to consider reservation status as well reservations = Reservation.query.filter( (Reservation.accommodation_id == args.accommodation_id) & ((Reservation.check_in_date < args.check_out) & (Reservation.check_out_date > args.check_in))).all() if len(reservations): return {'msg': 'Reservation not available for these dates'}, 400 # check that num_guests is <= acc's num_guests acc = Accommodation.query.filter_by(id=args.accommodation_id).first() if acc.num_guests < args.num_guests: return { 'msg': 'num_guests is too many for this accommodation' }, 400 # create new reservation for given guest_id and dates new_res = Reservation(accommodation_id=args.accommodation_id, guest_id=args.guest_id, check_in_date=args.check_in, check_out_date=args.check_out, status='booked') db.session.add(new_res) db.session.commit() return {'msg': new_res.to_dict()}, 201