예제 #1
0
def render_booking(teacherid, day, time):
    form = BookingForm(teacher=teacherid, day=day, time=time)
    if request.method == 'POST':
        name = form.name.data
        phone = form.phone.data
        teacher = form.teacher.data
        day = form.day.data
        time = form.time.data
        db.session.add(
            Booking(created=datetime.now(),
                    remote_addr=request.remote_addr,
                    name=name,
                    phone=phone,
                    day=day,
                    time=time,
                    teacher_id=teacherid))
        db.session.commit()

        return render_template('booking_done.html',
                               name=name,
                               phone=phone,
                               teacher=teacher,
                               time=time,
                               day=days[day])

    return render_template(
        'booking.html',
        teacherid=teacherid,
        teacher=db.session.query(Teacher).get_or_404(teacherid),
        daydesc=days[day],
        day=day,
        time=time,
        form=form)
예제 #2
0
def book_appointment(request):
    # check if the request is of type post and if the user is Donor
    if request.method == 'POST' and request.user.is_donor:

        # get the required format of the data
        appointment = request.POST['time']
        donor_id = request.POST['donor']
        hospital_id = request.POST['hospital']
        data = {
            'hospital': Hospital.objects.get(pk=hospital_id),
            'donor': Donor.objects.get(pk=donor_id),
            'appointment': request.POST.get("time")
        }
        # Try to create a new Booking with provided data
        try:
            booking = Booking()
            booking.new_appointment(data)
            return JsonResponse({
                'success':
                True,
                'message':
                "The appointment has been created successfully"
            })
        except:
            return JsonResponse({
                'success':
                False,
                'message':
                "You might have booking at this time at different hospital. Please, try different slot."
            })
    else:
        return redirect("app:app")
예제 #3
0
    def db_access(first, middle, last, work, email, arrival, departure):
        """
        # Now setup an instance of the tables we are going 
        to interact with in order to store data
        # instantiate the variables just declared up there with 
        the relevant field in the table that the data will go to
        # giving it a path

        :param first:
        :param middle:
        :param last:
        :param work:
        :param email:
        :return:
        """
        email_string = "Hello, " + first + middle + last + \
            " you have made a reservation for " + arrival + " to " + departure
        clients = Users(f_name=first, m_name=middle, l_name=last,
                        occupation=work, email_address=email)

        duration = Booking(arrival_date=arrival, departure_date=departure)
        Functionality.send_email(email_string, email)

        # then add these new stored infor to the current user session
        # commit the changes
        sessionRep.add(clients)
        sessionRep.add(duration)
        sessionRep.commit()
예제 #4
0
    def post(self, request, *args, **kwargs):
        staff_data = get_object_or_404(Staff, id=self.kwargs['pk'])
        year = self.kwargs.get('year')
        month = self.kwargs.get('month')
        day = self.kwargs.get('day')
        hour = self.kwargs.get('hour')
        start_time = make_aware(datetime(year=year, month=month, day=day, hour=hour))
        end_time = make_aware(datetime(year=year, month=month, day=day, hour=hour + 1))
        booking_data = Booking.objects.filter(staff=staff_data, start=start_time)
        form = BookingForm(request.POST or None)
        if booking_data.exists():
            form.add_error(None, '既に予約があります。\n別の日時で予約をお願いします。')
        else:
            if form.is_valid():
                booking = Booking()
                booking.staff = staff_data
                booking.start = start_time
                booking.end = end_time
                booking.first_name = form.cleaned_data['first_name']
                booking.last_name = form.cleaned_data['last_name']
                booking.tel = form.cleaned_data['tel']
                booking.remarks = form.cleaned_data['remarks']
                booking.save()
                return redirect('thanks') 

        return render(request, 'app/booking.html', {
            'staff_data': staff_data,
            'year': year,
            'month': month,
            'day': day,
            'hour': hour,
            'form': form,
        })
예제 #5
0
def booking(teacher_id, day, hour):
    form = BookingForm()
    if form.validate_on_submit():
        bk = Booking(teacher_id=teacher_id, day=day, hour=hour)
        bk.student_name = form.contact_info.student_name.data
        bk.student_phone = form.contact_info.student_phone.data
        teacher = Teacher.query.get(teacher_id)
        teacher.set_hour_state(day, hour, False)  # теперь время - занято
        bk.save()
        return render_template("done.html",
                               title={
                                   "label": "Тема",
                                   "value": "Пробный урок"
                               },
                               time={
                                   "label": days[bk.day],
                                   "value": f"{bk.hour}:00"
                               },
                               name=bk.student_name,
                               phone=bk.student_phone)

    return render_template("booking.html",
                           teacher=Teacher.query.get(teacher_id),
                           time={
                               "day": day,
                               "hour": hour
                           },
                           days=days,
                           form=form)
예제 #6
0
def render_booking_done():
    teacher = Teacher.query.filter(
        Teacher.id == int(request.form.get("clientTeacher"))).first()
    schedule = Schedule.query.filter(
        Schedule.id == int(request.form.get("schedule"))).first()

    form = BookingForm()
    if form.validate_on_submit():
        name = form.clientName.data
        phone = form.clientPhone.data

        client = Client(name=name, phone=phone)

        db.session.add(client)
        # TODO
        # изменить ли структуру модели Client
        # так что бы хранил не id и ссылку
        # тогда можно без коммита
        db.session.commit()

        db.session.add(
            Booking(client=client.id, teacher=teacher.id,
                    schedule=schedule.id))
        db.session.commit()

        return render_template(
            "booking_done.html",
            name=name,
            phone=phone,
            day=ReadData.day_week.get(schedule.day_week, ""),
            time=schedule.time,
        )
    else:
        return url_for("booking.html")
예제 #7
0
def index():
    contact_form = ContactForm(request.form)

    if request.method == "POST":
        if contact_form.validate_on_submit():
            name = contact_form.name.data
            email = contact_form.email.data
            arrival = contact_form.arrival_date.data
            departure = contact_form.departure_date.data

            user = Users(f_name=name,
                         m_name="middle",
                         l_name="last",
                         occupation="work",
                         email_address=email)

            duration = Booking(arrival_date=arrival, departure_date=departure)

            db.session.add(user)
            db.session.add(duration)
            db.session.commit()

            email_string = "Hello, " + name + \
                           " you have made a reservation for " + arrival + " to " + departure
            send_email(email_string, email)
            generate_pdf(name)

        return redirect(url_for('home.index'))

    return render_template('home/index.html', contact_form=contact_form)
예제 #8
0
def book(event_id):
    data = db.session.query(Event).join(
        Location, Location.id == Event.location_id).with_entities(
            Event.name, Event.capacity, Event.start, Event.end,
            Location.name.label('location_name'), Location.address,
            Event.img_name).filter(Event.id == event_id).first()

    ticket_amt = [(i, i) for i in range(1, data.capacity + 1)]
    form = BookingForm()
    form.amount.choices = ticket_amt

    if data is None:
        return render_template('error_event.html')
    if form.validate_on_submit():
        event = Event.query.get(event_id)
        event.capacity -= form.amount.data
        booking = Booking(user_id=current_user.id,
                          event_id=event_id,
                          quantity=form.amount.data,
                          book_time=datetime.utcnow(),
                          last_modified=datetime.utcnow())
        db.session.add(booking)
        db.session.commit()
        app.logger.info(
            'User ID {} has booked {} tickets (Booking ID {}) for Event ID {} at {}.'
            .format(booking.user_id, booking.quantity, booking.id,
                    booking.event_id, datetime.now()))
        flash(
            'Successfully purchased {} tickets for {}'.format(
                form.amount.data, data.name), "info")
        return redirect(url_for('main_panel.events'))
    return render_template('book.html',
                           event_id=event_id,
                           data=data,
                           form=form)
예제 #9
0
 def register_booking(self, model: RegisterBookingDto):
     booking = Booking()
     booking.flight_id = model.flight_id
     booking.passenger_id = model.passenger_id
     booking.flight_class = model.flight_class
     booking.price = model.price
     booking.booking_reference = model.booking_reference
     booking.save()
예제 #10
0
def create_booking(bus_id):
    bus = Bus.query.get(bus_id)
    if not bus.booking_time_expired():
        create_booking_form = CreateBookingForm(data=request.form, bus=bus)
        if create_booking_form.validate_on_submit():
            # create booking
            grid_id = create_booking_form.grid_id.data
            pricing_id = create_booking_form.pricing_id.data
            passenger_name = create_booking_form.passenger_name.data
            passenger_telephone = create_booking_form.passenger_telephone.data
            pickup = create_booking_form.pickup.data
            pricing = Pricing.query.get(pricing_id)
            grid = Grid.query.get(grid_id)
            branch = bus.branch
            user = current_user
            if not user.is_authenticated:
                user = None

            fare = pricing.price
            stop = pricing.stop
            booking = Booking(passenger_name=passenger_name,
                              passenger_telephone=passenger_telephone,
                              seat_number=grid.number,
                              pickup=pickup,
                              fare=fare,
                              stop=stop,
                              grid_id=grid_id,
                              pricing_id=pricing_id,
                              paid=True,
                              branch=branch,
                              bus=bus,
                              created_by=user.id)

            db.session.add(booking)
            grid.booking = booking

            create_payment(booking)
            db.session.commit()
            bookings = bus.bookings
            booking_fields = Fields().booking_fields()
            bookings_json = json.loads(
                json.dumps(marshal_data(bookings, booking_fields)))
            res = json.dumps({
                "handle": "create_booking_passed",
                "data": {
                    "grid": grid.grid_dict(),
                    "bookings": bookings_json
                }
            })
            redis.publish(app.config.get("REDIS_CHAN"), res)
            flash(f'Booked Seat {grid.number}', 'success')
            return redirect(url_for('bus.get_bus', bus_id=bus.id))
        else:
            flash(f'Failed', 'danger')
            return render_template("bus/bus.html",
                                   bus=bus,
                                   create_booking_form=create_booking_form)
예제 #11
0
def create_booking():
    data = request.get_json() or {}
    if 'name' not in data or 'date' not in data or 'phone' not in data:
        return bad_request('name,date,phone are required')
    item = Booking()
    item.from_dict(data)
    db.session.add(item)
    db.session.commit()
    response = jsonify(item.to_dict())
    response.status_code = 201
    return response
예제 #12
0
def create_booking():
    form = BookingForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print()
    if form.validate_on_submit():
        booking = Booking(book_date=form.data['book_date'],
                          book_start_time=form.data['book_start_time'],
                          book_end_time=form.data['book_end_time'],
                          user_id=form.data['user_id'],
                          service_id=form.data['service_id'])
    db.session.add(booking)
    db.session.commit()
    newbooking = Booking.query.filter_by(id=booking.id).join(Aircraft).one()
    return to_booking(newbooking)
예제 #13
0
def CreateBooking(request):
    print("Request is : ", request.json)
    if not request.json:
        return jsonify({'message': 'No input data provided '}), 400
    content = request.get_json()
    schema = BookingSchema()
    bookingData = schema.load(content)
    newAsset = bookingData.data
    a = Booking(**newAsset)
    db.session.add(a)
    try:
        db.session.commit()
        return jsonify({"sucess": True})
    except IntegrityError:
        return jsonify({"sucess": False})
        db.session.rollback()
예제 #14
0
def booking(teacher_id):
    teacher = db.session.query(Teacher).get_or_404(teacher_id)
    form = BookingForm()
    
    if form.validate_on_submit():
        weekday_ru = request.args.get('day')
        time = request.args.get('time')
        weekday_slug = next(
            (day_en for day_en, day_ru in RU_DAYS.items() if weekday_ru == day_ru),
            None
        )

        booking = Booking(
            username=form.name.data,
            phone=form.phone.data,
            weekday=weekday_ru,
            time=time
        )

        teacher_schedule = json.loads(teacher.schedule)
        teacher_schedule[weekday_slug][time] = False
        teacher.schedule = json.dumps(teacher_schedule)
        teacher.bookings.append(booking)
        db.session.add(teacher)
        db.session.add(booking)
        db.session.commit()

        context = {
            'name': booking.username,
            'phone': booking.phone,
            'lesson_day':  booking.weekday ,
            'lesson_time': booking.time,
            'subject': 'trial',
            'subject_description': 'Пробное занятие'
        }
        return redirect(url_for('sent', context=json.dumps(context)))

    context = {
        'teacher': teacher,
        'lesson_day': RU_DAYS[request.args.get('day')],
        'lesson_time': request.args.get('time')
    }

    return render_template('booking.html', form=form, **context)
예제 #15
0
def create_booking():
    if not request.json or not 'book_id' in request.json or not 'user_id' in request.json or not 'start_date' in request.json or not 'end_date' in request.json:
        abort(400)
    u = User.query.get(int(request.json['user_id']))
    b_id = request.json['book_id']
    if not u or not b_id:
        abort(500)
    book_id_api = requests.get("http://63.34.166.57:8080/book/id/{0}".format(b_id))
    if book_id_api.status_code != 200:
        abort(500)
    book_id = book_id_api.json()
    check = Booking.query.filter(and_(Booking.book_id == book_id["id"], Booking.start_date <= request.json["end_date"], request.json["start_date"] <= Booking.end_date)).all()
    print(check, file=sys.stderr)
    if check:
        return jsonify({'message': 'Booking overlap.'}), 200
    b = Booking(book_id=book_id["id"], booker=u, start_date=request.json["start_date"], end_date=request.json["end_date"])
    db.session.add(b)
    db.session.commit()
    return jsonify({'message': 'Booking completed.'}), 201
예제 #16
0
def property(request, property_id):
    prop = Property.objects.get(id=property_id)
    bookings = Booking.objects.filter(property=property_id)
    checker = None
    guest = None

    if request.method == 'POST':
        guest = request.POST.get('guest')
        start_date = request.POST.get('start_date')
        start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date = request.POST.get('end_date')
        end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        price = prop.price * (end_date - start_date).days * 1.08

        if len(bookings) > 0:
            for booking in bookings:
                if (booking.start_date <= start_date <= booking.end_date
                        or booking.start_date <= end_date <= booking.end_date
                    ) or (start_date <= booking.start_date
                          and end_date >= booking.end_date):
                    checker = False
                else:
                    checker = True
        else:
            checker = True

        if checker:
            p = Booking(property=prop,
                        start_date=start_date,
                        end_date=end_date,
                        price=price,
                        guest=guest)
            p.save()

    context = {
        'property': prop,
        'checker': checker,
        'guest': guest,
    }

    return render(request, 'app/property.html', context)
예제 #17
0
def saveBooking(request):
    name = request.POST.get('u_name')
    block_name = request.POST.get('bn')
    flat_type = request.POST.get('ft')
    flat_no = request.POST.get('fno')
    email = request.POST.get('u_email')
    purpose = request.POST.get('u_pur')
    date = request.POST.get('u_date')
    message = request.POST.get('u_mes')
    # print(name,block_name,flat_type,flat_no,email,purpose,date,message)
    bk = Booking(name=name,
                 flat_no=flat_no,
                 booking_purpose=purpose,
                 booking_date=date,
                 message=message,
                 email=email,
                 flat_type=flat_type,
                 block_name=block_name)
    bk.save()
    res = UserRegister.objects.get(flat_no=flat_no)
    return render(request, 'userhome.html', {'res': res})
예제 #18
0
def test_json(data):
    data = json.loads(data)
    try:
        b = Booking(id=data['id'],
                    user_id=data['user_id'],
                    vehicle_model_id=data['vehicle_model_id'],
                    package_id=data['package_id'],
                    travel_type_id=data['travel_type_id'],
                    from_area_id=data['from_area_id'],
                    to_area_id=data['to_area_id'],
                    from_city_id=data['from_city_id'],
                    to_city_id=data['to_city_id'],
                    from_date=data['from_date'],
                    to_date=data['to_date'],
                    online_booking=data['online_booking'],
                    mobile_site_booking=data['mobile_site_booking'],
                    booking_created=data['booking_created'],
                    from_lat=data['from_lat'],
                    from_long=data['from_long'],
                    to_lat=data['to_lat'],
                    to_long=data['to_long'],
                    Car_Cancellation=data['Car_Cancellation'])
        db.session.add(b)
        db.session.commit()
        # log succesful addition
        emit('my_response', {'success': True, 'id': data['id']})
    except KeyError:
        # log data with exception
        emit('my_response', {
            'success': False,
            'id': data['id'],
            'cause': 'Unrecognised attribute'
        })
    except:
        # log data
        emit('my_response', {
            'success': False,
            'id': data['id'],
            'cause': 'Unknows error'
        })
예제 #19
0
    def on_create_booking(self, query_string):
        form_data = parse_query_string(query_string)
        grid_id = form_data.get("grid_id")
        grid = Grid.query.get(grid_id)
        bus = grid.bus
        if not bus.booking_time_expired():
            create_booking_form = CreateBookingForm(data=form_data, grid=grid)
            if create_booking_form.validate():
                # create booking
                grid_id = create_booking_form.grid_id.data;
                pricing_id = create_booking_form.pricing_id.data
                passenger_name = create_booking_form.passenger_name.data
                passenger_telephone = create_booking_form.passenger_telephone.data
                pickup = create_booking_form.pickup.data
                paid = create_booking_form.paid.data
                pricing = Pricing.query.get(pricing_id)
                branch = bus.branch
                user = current_user
                if not user.is_authenticated:
                    user = None

                fare = pricing.price;
                stop = pricing.stop;
                booking = Booking(
                    passenger_name=passenger_name, passenger_telephone=passenger_telephone, seat_number=grid.number, pickup=pickup, 
                    fare=fare, stop=stop, paid=paid, grid_id=grid_id, pricing_id=pricing_id, branch=branch, 
                    bus=bus, created_by=user.id
                )

                db.session.add(booking)
                grid.booking = booking
            	
                create_payment(booking)
                db.session.commit()
                room = grid.bus.number
                emit("create_booking_passed", grid.grid_dict(), room=room, broadcast=True)
            else:
                emit("create_booking_failed", create_booking_form.errors, broadcast=False)
        else:
            emit("create_booking_failed", {"error": "Booking Time Ellapsed!"}, broadcast=False)
예제 #20
0
def create_booking(query_string):
    form_data = parse_query_string(query_string)
    grid_id = form_data.get("grid_id")
    grid = Grid.query.get(grid_id)
    bus = grid.bus
    if not bus.booking_time_expired():
        create_passenger_booking_form = CreatePassengerBookingForm(data=form_data, bus=bus)
        if create_passenger_booking_form.validate():
            # create booking
            grid_id = create_passenger_booking_form.grid_id.data;
            pricing_id = create_passenger_booking_form.pricing_id.data
            passenger_name = create_passenger_booking_form.passenger_name.data
            passenger_telephone = create_passenger_booking_form.passenger_telephone.data
            pickup = create_passenger_booking_form.pickup.data
            pricing = Pricing.query.get(pricing_id)
            branch = bus.branch
            user = current_user
            if not user.is_authenticated:
                user = None

            fare = pricing.price;
            stop = pricing.stop;
            booking = Booking(
                passenger_name=passenger_name, passenger_telephone=passenger_telephone, seat_number=grid.number, pickup=pickup, 
                fare=fare, stop=stop, grid_id=grid_id, pricing_id=pricing_id, paid=True, branch=branch, 
                bus=bus, created_by=user.id
            )

            db.session.add(booking)
            grid.booking = booking
        	
            create_payment(booking)
            db.session.commit()
            room = grid.bus.number
            return json.dumps({"handle": "create_booking_passed", "data": grid.grid_dict()})
        else:
            return json.dumps({"handle": "create_booking_failed", "data":create_passenger_booking_form.errors})
    else:
        return json.dumps({"handle":"create_booking_failed", "data":{"error": "Booking Time Ellapsed!"}})
예제 #21
0
def book():
    form=BookingForm()
    if form.validate_on_submit():
        
        # check time collision
        bookingcollisions=Booking.query.filter_by(date=datetime.combine(form.date.data,datetime.min.time())).filter_by(pitchId=form.pitchs.data).all()
        print(len(bookingcollisions))
        for bookingcollision in bookingcollisions:
            if (form.startTime.data<bookingcollision.endTime and (form.startTime.data+form.duration.data)>bookingcollision.startTime):
                flash(f'The time from {bookingcollision.startTime} to {bookingcollision.endTime} is already booked by {User.query.filter_by(id=bookingcollision.bookerId).first().fullname}.')
                return redirect(url_for('main.book'))

        # make booking
        booker=current_user
        pitch=Pitch.query.filter_by(id=form.pitchs.data).first()
        endTime=form.startTime.data+form.duration.data
        booking=Booking(pitchId=pitch.id,bookerId=booker.id,date=form.date.data,startTime=form.startTime.data,endTime=endTime,duration=form.duration.data)
        db.session.add(booking)
        db.session.commit()
        flash('Booking success!')
        return redirect(url_for('main.index'))
    return render_template('book.html',title='Book Booking',form=form)
예제 #22
0
def make_booking(room_id):
    form = BookingForm()
    room = Room.query.filter_by(id=room_id).first()
    if form.validate_on_submit():
        reservation = Booking(
            host_id=current_user.id,
            room_id=room_id,
            booking_date=datetime.utcnow(),
            meeting_title=form.meeting_title.data,
            meeting_date=form.meeting_date.data,
            description=form.description.data,
        )
        db.session.add(reservation)
        db.session.commit()

        flash('Reservation has been made')
        return redirect(url_for('rooms.list_rooms'))
    return render_template('booking/create_booking.html',
                           title='make_reservation',
                           form=form,
                           legend='New booking',
                           room=room,
                           user=current_user)
예제 #23
0
파일: database.py 프로젝트: roesel/book
def create_booking(who, when, room_id):
    new_booking = Booking(who=who, when=when, room=room_id, status="pending")
    # new_booking = Booking(who=who, when=when, room=room_id)
    new_booking.save()
    return new_booking.id
예제 #24
0
from app.models import Booking
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tabledef import *

engine = create_engine('mysqldb:///tutorial.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

user = User("admin","*****@*****.**","password")
session.add(user)

user = User("python","*****@*****.**","python")
session.add(user)

user = User("jumpiness","*****@*****.**","python")
session.add(user)

booking = Booking("March 18,2021","9:00 am")
session.add(booking)

# commit the record the database
session.commit()

session.commit()
예제 #25
0
def create_booking(who, when, room_id):
    new_booking = Booking(who=who, when=when, room=room_id)
    new_booking.save()
    return new_booking.id
예제 #26
0
def create_booking(current_user=None):
    data = request.get_json()
    start_time = data['datetime']
    # 900 * 1000 is 15 minutes
    end_time = start_time + 900 * 1000

    # check if input time clashes with existing timeslot
    clash = TimeSlot.query.filter(TimeSlot.vet_id == data['vetId'],
                                  TimeSlot.start_time <= start_time,
                                  TimeSlot.end_time >= end_time).first()
    if clash:
        return jsonify({'message': 'Conflict with existing bookings'}), 400

    # check if input time is within vet working hours
    start_datetime = datetime.datetime.fromtimestamp(start_time / 1e3)
    weekday = get_weekday(start_datetime)
    vet_working_hours = VetSchedule.query.filter(
        VetSchedule.day_of_week == weekday).first()
    if vet_working_hours is None:
        return jsonify({'message': 'Vet is not working on this day'}), 400

    vet_on_duty = check_vet_on_duty(start_datetime, vet_working_hours)
    if not vet_on_duty:
        return jsonify({'message': 'Not within vet working hour'}), 400

    # add booking to db
    new_time_slot = TimeSlot(start_time=start_time,
                             end_time=end_time,
                             vet_id=data['vetId'])
    db.session.add(new_time_slot)
    db.session.flush()
    db.session.refresh(new_time_slot)
    if current_user:
        pet_owner = PetOwner.query.filter_by(user_id=current_user.uid).first()
        pet_owner_id = pet_owner.id
        pet_id = data['petId']
    # create PetOwner and Pet row for guest
    else:
        pet_owner = PetOwner(phone=data['phone'], email=data['email'])
        animal_type = AnimalType.query.filter_by(
            name=data['animalType']).first()
        db.session.add(pet_owner)
        db.session.flush()
        db.session.refresh(pet_owner)
        pet = Pet(animal_id=animal_type.id, owner_id=pet_owner.id)
        db.session.add(pet)
        db.session.flush()
        db.session.refresh(pet)
        pet_owner_id = pet_owner.id
        pet_id = pet.id

    vet = Vet.query.filter_by(id=data['vetId']).first()
    new_booking = Booking(pet_id=pet_id,
                          owner_id=pet_owner_id,
                          time_slot_id=new_time_slot.id,
                          vet_id=data['vetId'],
                          clinic_id=vet.clinic[0].id)
    db.session.add(new_booking)
    db.session.commit()

    booking = Booking.query.filter_by(time_slot_id=new_time_slot.id).first()

    return jsonify({
        'message': 'New booking created!',
        'bookingNumber': booking.booking_number
    })
예제 #27
0
                for room in avail_rooms[0:rn]:
                    rn2 = random.randint(1, 3)
                    if in_building[building] < building_limit and rn2 == 1:
                        bookings.append({
                            "when": when,
                            "who": who,
                            "room": room,
                            "status": status
                        })
                        in_building[building] += 1

#print(bookings)

# Make demo bookings
#bookings = [
#    {"when":"2020-04-05-AM", "who":1, "room":1, "status":"approved"},
#{"when":"2020-04-05-AM", "who":3, "room":1, "status":"approved"},
#{"when":"2020-04-05-AM", "who":4, "room":10, "status":"approved"},
#{"when":"2020-04-08-AM", "who":3, "room":2, "status":"approved"},
#{"when":"2020-04-05-PM", "who":1, "room":35, "status":"approved"},
#{"when":"2020-04-06-PM", "who":3, "room":36, "status":"denied"},
#{"when":"2020-04-05-PM", "who":4, "room":37, "status":"pending"},
#{"when":"2020-04-05-PM", "who":4, "room":40, "status":"pending"},
#]

for bk in bookings:
    b = Booking(when=bk["when"],
                who=bk["who"],
                room=bk["room"],
                status=bk["status"])
    b.save()
예제 #28
0
def bookings():
    #""" Get All Bookings. """
    if request.method == 'GET':
        bookings = Booking.query.all()

        if bookings is None or bookings == []:
            return bad_request('No bookings exist.')

        else:
            response = jsonify({
                'bookings': [booking.to_dict() for booking in bookings],
                '_link':
                url_for('api.bookings')
            })
            response.headers['Location'] = url_for('api.bookings')
            return response

    elif request.method == 'POST':
        data = request.get_json() or {}

        if 'user_id' not in data and 'restr_id' not in data and 'table_id' not in data:
            return bad_request(
                'user_id, restr_id and table_id was missing in the request.')
        if 'user_id' not in data:
            return bad_request('user_id name was missing in the request.')
        if 'restr_id' not in data:
            return bad_request('restr_id was missing in the request.')
        if 'table_id' not in data:
            return bad_request('table_id was missing in the request.')

        user = requests.get('http://localhost:5001/api/v1/users/' +
                            data['user_id'])
        if user.status_code != 200:
            return bad_request('user_id in the request does not exist.')
        else:
            user_data = user.json()

        restr = requests.get('http://localhost:5002/api/v1/restaurants/' +
                             data['restr_id'])
        if restr.status_code != 200:
            return bad_request('restaurant_id in the request does not exist.')
        else:
            restr_data = restr.json()

        table = requests.get("http://localhost:5002/api/v1/restaurants/" +
                             data["restr_id"] + "/tables/" + data['table_id'])
        if table.status_code != 200:
            return bad_request(
                'table_id does not exist for restaurant_id in the request.')
        else:
            table_data = table.json()

        booking = Booking()
        booking.from_dict(data)
        db.session.add(booking)
        db.session.commit()
        response = jsonify(booking.to_dict())
        response.status_code = 201
        response.headers['Location'] = url_for('api.booking', id=booking.id)
        return response

    elif request.method == 'PUT':
        return bad_request(
            "You cannot update a booking on this end point. Use this for a PUT request: "
            + url_for('api.booking') + "/<id>")

    elif request.method == 'DELETE':
        return bad_request(
            "You cannot delete a booking on this end point. Use this for a DELETE request: "
            + url_for('api.booking') + "/<id>")

    else:
        return bad_request("That's a bad request.")
예제 #29
0
def seed_data():
    users = [
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        ),
        User(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password': '******'
            }
        )
    ]
    users[0].role = 0
    users[1].role = 1
    users[2].role = 3
    db.session.bulk_save_objects(users)

    cars = [
        Car(
            data={
                'name': 'car123',
                'make': 'tesla',
                'body_type': 1,
                'colour': 1,
                'seats': 4,
                'location': '[-37.177378, 144.159114]',
                'rate': 5.5,
                'status': 1
            }
        ),
        Car(
            data={
                'name': 'cybertruck',
                'make': 'tesla',
                'body_type': 2,
                'colour': 2,
                'seats': 6,
                'location': '[-37.277378, 144.259114]',
                'rate': 5.5,
                'status': 1
            }
        ),
        Car(
            data={
                'name': 'car2',
                'make': 'honda',
                'body_type': 3,
                'colour': 3,
                'seats': 4,
                'location': '[-37.377378, 144.359114]',
                'rate': 5.5,
                'status': 1
            }
        ),
        Car(
            data={
                'name': 'motorcycle',
                'make': 'kawasaki',
                'body_type': 4,
                'colour': 4,
                'seats': 4,
                'location': '[-37.477378, 144.459114]',
                'rate': 5.5,
                'status': 1
            }
        ),
        Car(
            data={
                'name': 'dragon',
                'make': 'SpaceX',
                'body_type': 6,
                'colour': 6,
                'seats': 7,
                'location': '[-37.577378, 144.559114]',
                'rate': 160000000,
                'status': 1
            }
        ),
        Car(
            data={
                'name': 'car1',
                'make': 'toyota',
                'body_type': 5,
                'colour': 5,
                'seats': 4,
                'location': '[-37.777378, 144.759114]',
                'rate': 5.5,
                'status': 1
            }
        )
    ]
    db.session.bulk_save_objects(cars)

    db.session.commit()

    bookings = [
        Booking(
            data={
                "car_id": 1,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-10T01:02:49",
                "timeend": "2020-06-10T03:16:24",
                "time_start": "2020-06-10T02:02:00",
                "user_id": 3
            }
        ),
        Booking(
            data={
                "car_id": 2,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 4
            }
        ),
        Booking(
            data={
                "car_id": 3,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-12T01:02:49",
                "timeend": "2020-06-12T03:16:24",
                "time_start": "2020-06-12T02:02:00",
                "user_id": 5
            }
        ),
        Booking(
            data={
                "car_id": 4,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-13T01:02:49",
                "timeend": "2020-06-13T03:16:24",
                "time_start": "2020-06-13T02:02:00",
                "user_id": 6
            }
        ),
        Booking(
            data={
                "car_id": 5,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-14T01:02:49",
                "timeend": "2020-06-14T03:16:24",
                "time_start": "2020-06-14T02:02:00",
                "user_id": 7
            }
        ),
        Booking(
            data={
                "car_id": 6,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-14T01:02:49",
                "timeend": "2020-06-14T03:16:24",
                "time_start": "2020-06-14T02:02:00",
                "user_id": 3
            }
        ),
        Booking(
            data={
                "car_id": 5,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-13T01:02:49",
                "timeend": "2020-06-13T03:16:24",
                "time_start": "2020-06-13T02:02:00",
                "user_id": 3
            }
        ),
        Booking(
            data={
                "car_id": 4,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-12T01:02:49",
                "timeend": "2020-06-12T03:16:24",
                "time_start": "2020-06-12T02:02:00",
                "user_id": 5
            }
        ),
        Booking(
            data={
                "car_id": 3,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 3
            }
        ),
        Booking(
            data={
                "car_id": 2,
                "hours": 1,
                "status": 2,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 7
            }
        ),
        Booking(
            data={
                "car_id": 1,
                "hours": 1,
                "status": 3,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 2
            }
        ),
        Booking(
            data={
                "car_id": 2,
                "hours": 1,
                "status": 3,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 2
            }
        ),
        Booking(
            data={
                "car_id": 2,
                "hours": 1,
                "status": 3,
                "timebooked": "2020-06-11T01:02:49",
                "timeend": "2020-06-11T03:16:24",
                "time_start": "2020-06-11T02:02:00",
                "user_id": 2
            }
        )
    ]
    db.session.bulk_save_objects(bookings)

    db.session.commit()
예제 #30
0
def build_room_slots():
    """
    Populate every room with an empty booking slot for every hour. 
    Every booking slot can hold a multiple days bookings for that hour.
    """
    from .models import Booking, BookingSlots, BookingRoom, Room

    bookable_room_ids = [14, 15, 16, 18, 23, 24]
    all_rooms = Room.query.filter(Room.id.in_(bookable_room_ids)).all()
    if all_rooms:
        all_rooms.sort(key=lambda r: r.id)

        bookable_rooms = []
        for r in all_rooms:
            bookable_rooms.append(BookingRoom(name=r.name))

        if bookable_rooms:
            bookable_rooms[0].is_quiet = False
            bookable_rooms[0].has_pc = False
            bookable_rooms[0].has_hdmi = True
            bookable_rooms[0].has_window = True
            bookable_rooms[0].max_occupancy = 8

            bookable_rooms[1].is_quiet = False
            bookable_rooms[1].has_pc = False
            bookable_rooms[1].has_hdmi = True
            bookable_rooms[1].has_window = True
            bookable_rooms[1].max_occupancy = 8

            bookable_rooms[2].is_quiet = False
            bookable_rooms[2].has_pc = False
            bookable_rooms[2].has_hdmi = True
            bookable_rooms[2].has_window = True
            bookable_rooms[2].max_occupancy = 8

            bookable_rooms[3].is_quiet = True
            bookable_rooms[3].has_pc = True
            bookable_rooms[3].has_hdmi = False
            bookable_rooms[3].has_window = False
            bookable_rooms[3].max_occupancy = 10

            bookable_rooms[4].is_quiet = True
            bookable_rooms[4].has_pc = False
            bookable_rooms[4].has_hdmi = True
            bookable_rooms[4].has_window = True
            bookable_rooms[4].max_occupancy = 8

            bookable_rooms[5].is_quiet = True
            bookable_rooms[5].has_pc = False
            bookable_rooms[5].has_hdmi = True
            bookable_rooms[5].has_window = True
            bookable_rooms[5].max_occupancy = 8

            for room in bookable_rooms:
                db.session.add(room)
            db.session.commit()

    else:
        # placeholder before real rooms imported
        for r in range(0, 4):

            name = 'room {}'.format(r)
            room = BookingRoom(name=name, max_occupancy=4)

            db.session.add(room)

        name = 'room with PC'
        pcroom = BookingRoom(name=name, max_occupancy=8, has_pc=True)
        db.session.add(pcroom)

        db.session.commit()

    rooms = BookingRoom.query.all()

    for room in rooms:
        days = []
        for s in range(0, 7):
            slots = BookingSlots()
            for b in range(0, 24):
                empty = Booking(user_id=None)
                slots.bookings.append(empty)

            days.append(slots)
        room.slots = days

        db.session.add(room)
        db.session.commit()