def init_db():
    booking1 = Booking(
        booking_price=66.6,
        start_time=datetime(2020, 3, 1, 0, 0 ,0),
        end_time=datetime(2020, 3, 4, 0, 0 ,0)
    )
    booking1.save()

    booking2 = Booking(
        booking_price=55.5,
        start_time=datetime(2020, 3, 5, 0, 0 ,0),
        end_time=datetime(2020, 3, 7, 0, 0 ,0)
    )
    booking2.save()

    vehicle1 = Vehicle(
        type="small car",
        make="Honda",
        model="Civic R",
        year=2020,
        registration_tag="A12345",
        current_mileage=123.12,
        condition="like new",
        capacity=4,
        is_available=True,
        booking=[booking1, booking2]
    )
    vehicle1.save()
示例#2
0
    def test_it_returns_an_empty_list_if_everything_has_a_cost(self):
        # given
        reimbursement1 = BookingReimbursement(
            Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(0))
        reimbursement2 = BookingReimbursement(
            Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(0))

        # when
        bookings_reimbursements_with_cost = filter_out_bookings_without_cost(
            [reimbursement1, reimbursement2])

        # then
        assert bookings_reimbursements_with_cost == []
示例#3
0
    def test_value_error_is_raised_if_payments_ids_do_not_match_payments(self):
        # given
        payments = [
            create_payment(Booking(), Offerer(), 10, idx=111),
            create_payment(Booking(), Offerer(), 10, idx=222)
        ]
        ids_to_ban = [222, 333]

        # when
        with pytest.raises(UnmatchedPayments) as e:
            apply_banishment(payments, ids_to_ban)

        # then
        assert e.value.payment_ids == {333}
示例#4
0
    def test_no_payments_are_returned_if_no_ids_are_provided(self):
        # given
        payments = [
            create_payment(Booking(), Offerer(), 10, idx=111),
            create_payment(Booking(), Offerer(), 10, idx=222)
        ]
        ids_to_ban = []

        # when
        banned_payments, retry_payments = apply_banishment(
            payments, ids_to_ban)

        # then
        assert banned_payments == []
        assert retry_payments == []
示例#5
0
    def test_no_payments_to_retry_if_all_are_banned(self):
        # given
        payments = [
            create_payment(Booking(), Offerer(), 10, idx=111),
            create_payment(Booking(), Offerer(), 10, idx=222)
        ]
        ids_to_ban = [111, 222]

        # when
        banned_payments, retry_payments = apply_banishment(
            payments, ids_to_ban)

        # then
        assert len(banned_payments) == 2
        assert retry_payments == []
示例#6
0
def render_booking_done():
    form = userForm()
    name = form.name.data
    phone = form.phone.data
    day = form.day.data
    time = form.time.data
    teacher_id = form.teacher_id.data
    teacher_name = form.teacher_name.data
    timetable_id = form.timetable_id.data

    print(50 * '*')
    print(form.timetable_id.data)

    student = Student.query.filter(Student.phone == phone).first()

    if not student:
        student = Student(name=name, phone=phone)
        db.session.add(student)
        db.session.commit()

    booking = Booking(student_id=student.id,
                      teacher_id=teacher_id,
                      timetable_id=timetable_id)

    db.session.add(booking)
    db.session.commit()

    return render_template('booking_done.html',
                           name=name,
                           phone=phone,
                           time=time,
                           day=day)
示例#7
0
    def getBookings(self, params=None):
        bookings = []
        # with no optional params all bookings can be fetched
        if not params:
            bookingTuples = db.getAllObjects('bookings')
        # otherwise only bookings matching the params may be fetched
        else:
            for param in params:
                if param not in Booking.attributesAsList():
                    return jsonify({'bookings': []})
            # obtain booking history for user_id param
                bookingTuples = db.getObjectsByFilter('bookings',
                                                      list(params.keys()),
                                                      list(params.values()))

        # construct the fetched bookings as objects
        for i in range(len(bookingTuples)):
            bookings.append(
                Booking(bookingTuples[i][0],
                        bookingTuples[i][1], bookingTuples[i][2],
                        self.__getUser(bookingTuples[i][3]),
                        self.__getCar(bookingTuples[i][4]),
                        bookingTuples[i][5]))

        # jsonify each booking object's dict
        return jsonify(bookings=[booking.asDict() for booking in bookings])
示例#8
0
def book_form(id, day, time):
    form = BookingForm()

    teacher = db.session.query(Teacher).filter(Teacher.id == int(id)).one()

    if form.validate_on_submit():
        name = form.name.data
        phone = form.phone.data
        day = form.day.data
        time = form.time.data
        id = form.id.data

        teacher = db.session.query(Teacher).filter(Teacher.id == int(id)).one()
        teacher.schedule[day][time] = False
        flag_modified(teacher, "schedule")
        new_booking = Booking(day=day,
                              time=time,
                              client_id=check_client(name, phone),
                              teacher_id=id)
        db.session.add(new_booking)
        db.session.commit()

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

    return render_template("booking.html",
                           form=form,
                           teacher=teacher,
                           day=day,
                           day_name=days[day],
                           time=time)
示例#9
0
def test_booking_completed_url_gets_normalized():
    # Given

    product = Product()
    product.url = 'javascript:alert("plop")'

    offer = Offer()
    offer.id = 1
    offer.product = product

    stock = Stock()

    user = User()
    user.email = '*****@*****.**'

    booking = Booking()
    booking.token = 'ABCDEF'
    booking.stock = stock
    booking.stock.offer = offer
    booking.user = user

    # When
    completedUrl = booking.completedUrl

    # Then
    assert completedUrl == 'http://javascript:alert("plop")'
示例#10
0
def post_booking():
    try:
        if 'user' in session:
            user_id = session["user"]["id"]
            booking = request.json
            attraction_id = booking["attractionId"]
            date = booking["date"]
            time = booking["time"]
            price = booking["price"]
            if attraction_id and (datetime.strptime(date, "%Y-%m-%d") >
                                  datetime.today() + timedelta(days=2)) and (
                                      (time == 'morning' and price == 2000) or
                                      (time == 'afternoon' and price == 2500)):
                # 建立行程成功
                new_booking = Booking(user_id=user_id,
                                      attraction_id=attraction_id,
                                      date=date,
                                      time=time,
                                      price=price)
                db.session.add(new_booking)
                db.session.commit()
                data = {"ok": True}
                return jsonify(data)
            # 輸入內容有誤
            data = {"error": True, "message": "行程建立失敗,輸入不正確或其他原因"}
            return jsonify(data), 400
        # 沒有登入
        data = {"error": True, "message": "未登入系統,行程建立失敗"}
        return jsonify(data), 403
    # 伺服器(資料庫)連線失敗
    except:
        data = {"error": True, "message": "伺服器內部錯誤"}
        return jsonify(data), 500
示例#11
0
    def test_it_returns_reimbursements_on_bookings_with_reimbursed_value_greater_than_zero(
            self):
        # given
        reimbursement1 = BookingReimbursement(
            Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(10))
        reimbursement2 = BookingReimbursement(
            Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(0))

        # when
        bookings_reimbursements_with_cost = filter_out_bookings_without_cost(
            [reimbursement1, reimbursement2])

        # then
        assert len(bookings_reimbursements_with_cost) == 1
        assert bookings_reimbursements_with_cost[
            0].reimbursed_amount > Decimal(0)
示例#12
0
def book(slot=None):
    if not slot:
        return redirect(url_for('viewspaces'))

    if request.method == "POST":
        daytime = request.form['arrivalday'] + " " + request.form['arrivaltime']
        daytime = datetime.datetime.strptime(daytime, "%Y-%m-%d %H:%M")
        duration = datetime.timedelta(hours=float(request.form['bookingdur']))
        finaltime = daytime + duration
        #conflicts1 = Booking.query.filter(Booking.parkingid==int(slot)).filter(daytime<=Booking.bookingto).filter(Booking.bookingto<=finaltime).count()
        #conflicts2 = Booking.query.filter(Booking.parkingid==int(slot)).filter(daytime<=Booking.bookingfrom).filter(Booking.bookingfrom<=finaltime).count()
        #conflicts = conflicts1+conflicts2
        #if conflicts:
        #    flash("The slot is already booked during that time period. Please try another day or time period.")
        #    return redirect(request.path)
        new_booking = Booking()
        new_booking.parkingid = int(slot)
        new_booking.userid = current_user.id
        new_booking.bookingfrom = daytime
        new_booking.bookingto = finaltime
        db.session.add(new_booking)
        db.session.commit()
        flash("Your booking was successfull")
        return redirect(url_for('viewspaces'))

    return render_template('book.html', title="Booking", slotno=slot)
示例#13
0
    def post(self):

        parking_spot_id = int(request.json.get('parking_spot_id'))
        user_id = int(request.json.get('user_id'))
        data = {}
        user_obj = session.query(User).filter(User.id == user_id).all()
        parking_obj = session.query(ParkingSpot).filter(
            ParkingSpot.id == parking_spot_id).all()
        user_obj_id = user_obj[0].to_dict()['id']
        parking_obj_id = parking_obj[0].to_dict()['id']
        parking_status = parking_obj[0].to_dict()['reserved']
        parking_obj = parking_obj[0].to_dict()
        if user_obj_id == user_id and parking_obj_id == parking_spot_id and parking_obj[
                'reserved'] == 0:
            data.update({'user_id': user_id})
            data.update({'parking_spot_id': parking_spot_id})
            data_obj = Booking(**data)
            session.add(data_obj)
            session.commit()
            parking_obj['reserved'] = 1
            parking_data = parking_obj
            parking = ParkingSpot(**parking_data)
            session.merge(parking)
            session.commit()
            return Response(json.dumps(
                {'message': 'booking successfully done'}),
                            status=201,
                            mimetype='application/json')
        else:
            return Response(json.dumps({
                'message':
                'please check your parking area existence,sorry not booked'
            }),
                            mimetype='application/json')
示例#14
0
def render_booking(lesson_id):
    error = ''
    form = BookingForm()
    lesson_id = int(lesson_id)
    lesson = Lesson.query.get_or_404(lesson_id)
    week_day = lesson.day_name.day_name
    _time = lesson.time.get_str_time()
    teacher = lesson.teacher
    if not lesson.status:
        error = f'Извините, у {teacher.name}  в  {week_day.lower()} {_time} нет свободного времени, ' \
                f'пожалуйста выберите другое время'
    if request.method == 'POST' and form.validate_on_submit() and error == '':
        form.lesson_id.data = int(lesson_id)
        booking = Booking()
        form.populate_obj(booking)
        client_name, client_phone = form.client_name.data, form.client_phone.data
        lesson.status = False
        db.session.add_all([lesson, booking])
        db.session.commit()
        return render_template('booking_done.html',
                               week_day=week_day,
                               day_time=_time,
                               name=client_name,
                               phone=client_phone)
    form.lesson_id.data = str(lesson_id)
    return render_template('booking.html',
                           teacher=teacher,
                           lesson_id=lesson_id,
                           week_day=week_day,
                           day_time=_time,
                           error=error,
                           form=form)
示例#15
0
def book_tickets(request):
    if request.method == 'POST':
        form = BookTicketsForm(request.POST)
        if form.is_valid():
            booking = Booking()
            booking.scheduled_show = form.cleaned_data['show']
            booking.name = form.cleaned_data['name']
            booking.email = form.cleaned_data['email']
            booking.number_of_tickets = form.cleaned_data['number_of_tickets']

            #            send_mail(
            #                subject=u'Rezervace: %s' % booking.scheduled_show,
            #                message=BOOKING_ADMIN_MAIL % form.cleaned_data,
            #                from_email='*****@*****.**',
            #                recipient_list=[BOOKING_ADMIN_EMAIL],
            #                fail_silently=False
            #            )

            send_mail(subject=u'Rezervace: %s' % booking.scheduled_show,
                      message=BOOKING_USER_MAIL % form.cleaned_data,
                      from_email='*****@*****.**',
                      recipient_list=[booking.email],
                      fail_silently=False)

            booking.save()

            messages.success(
                request, u'Děkujeme. Potvrzení bylo odesláno na váš email.')
            form = BookTicketsForm()
    else:
        form = BookTicketsForm()
    return render_to_response('booking/base.html', {
        'book_tickets_form': form,
    },
                              context_instance=RequestContext(request))
示例#16
0
 def getBooking(self, id):
     # locate a booking in the database
     bookingTuple = db.getObjectById('bookings', id)[0]
     # use data to create a booking object then jsonify it's dict
     return jsonify(
         Booking(bookingTuple[0], bookingTuple[1], bookingTuple[2],
                 self.__getUser(bookingTuple[3]),
                 self.__getCar(bookingTuple[4]), bookingTuple[5]).asDict())
示例#17
0
    def test_it_returns_an_empty_list_if_everything_has_been_reimbursed(self):
        # Given
        booking_paid1 = Booking()
        booking_paid1.payments = [Payment()]
        booking_reimbursement1 = BookingReimbursement(
            booking_paid1, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10))

        booking_paid2 = Booking()
        booking_paid2.payments = [Payment()]
        booking_reimbursement2 = BookingReimbursement(
            booking_paid2, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10))

        # When
        bookings_not_paid = filter_out_already_paid_for_bookings(
            [booking_reimbursement1, booking_reimbursement2])

        # Then
        assert bookings_not_paid == []
    def test_send_confirmation_email(self):
        # Send message.
        send_confirmation_email(Booking('a', 'b', '*****@*****.**'))

        # Test that one message has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'Confirmation Email')
    def test_send_initial_email(self):
        # Send message.
        send_initial_email(Booking('a', 'b', '*****@*****.**', '12345'),
                           '1q2w3e')

        # Test that one message has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'Initial Email')
示例#20
0
    def test_payments_not_matching_given_ids_must_be_retried(self):
        # given
        payments = [
            create_payment(Booking(), Offerer(), 10, idx=111),
            create_payment(Booking(), Offerer(), 10, idx=222),
            create_payment(Booking(), Offerer(), 10, idx=333),
            create_payment(Booking(), Offerer(), 10, idx=444)
        ]
        ids_to_ban = [222, 333]

        # when
        banned_payments, retry_payments = apply_banishment(
            payments, ids_to_ban)

        # then
        assert len(retry_payments) == 2
        for p in retry_payments:
            assert p.currentStatus.status == TransactionStatus.RETRY
            assert p.id not in ids_to_ban
示例#21
0
 def updateBooking(self, id, fieldsToUpdate, params):
     # update the booking with the specified id, indicating which fields to update and what to update them to
     db.updateObject('bookings', id, fieldsToUpdate, params)
     # retrieve the newly updated booking and create an object from it's data
     bookingTuple = db.getObjectById('bookings', id)[0]
     booking = Booking(bookingTuple[0], bookingTuple[1], bookingTuple[2],
                       self.__getUser(bookingTuple[3]),
                       self.__getCar(bookingTuple[4]), bookingTuple[5])
     # jsonify the booking to confirm the update
     return jsonify({'booking': booking.asDict()})
示例#22
0
def booking():
    postDict = request.get_json()
    if session['person_id']:
        booking = Booking(postDict['startDate'], postDict['endDate'],
                          postDict['planeId'], postDict['instructorId'],
                          session['person_id'])
        db.session.add(booking)
        db.session.commit()

    return str(booking.id)
示例#23
0
    def test_validated_label_when_event_is_expired(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.stock.beginningDatetime = datetime.utcnow() + timedelta(-1)

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == 'Validé'
示例#24
0
    def test_is_cancelled_label_when_booking_is_cancelled(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.isCancelled = True

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == "Réservation annulée"
示例#25
0
    def test_is_countermak_validated_label_when_booking_is_used(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.isUsed = True

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == 'Contremarque validée'
示例#26
0
def create_booking_for(user: User, stock: Stock, token: str) -> Booking:
    booking = Booking()
    booking.stock = stock
    booking.user = user
    booking.quantity = 1
    booking.amount = 0
    booking.dateCreated = datetime.utcnow()
    booking.isCancelled = False
    booking.isUsed = False
    booking.token = token
    return booking
示例#27
0
 def createBooking(self, params):
     # fetch the user and car corresponding to the user_id and car_id in the request body
     user = self.__getUser(params[3])
     car = self.__getCar(params[4])
     # construct a booking object from the gathered data
     booking = Booking(params[0], params[1], params[2], user, car,
                       params[5])
     # update the database with the new booking and respond with a confirmation of insertion
     db.insertObject('bookings', Booking.attributesAsList(),
                     booking.asTuple())
     return jsonify({'booking': booking.asDict()}), 201
示例#28
0
    def test_raises_api_error_when_offerer_cancellation_and_used_booking(self):
        # Given
        booking = Booking()
        booking.isUsed = True

        # When
        with pytest.raises(ApiErrors) as e:
            check_booking_is_cancellable(booking, is_user_cancellation=False)

        # Then
        assert e.value.errors['booking'] == ["Impossible d\'annuler une réservation consommée"]
示例#29
0
    def test_raises_resource_gone_error_if_is_used(self):
        # Given
        booking = Booking()
        booking.isUsed = True
        booking.stock = Stock()

        # When
        with pytest.raises(ResourceGoneError) as e:
            check_booking_is_usable(booking)
        assert e.value.errors['booking'] == [
            'Cette réservation a déjà été validée']
def addBooking(_, info, vehicle_id, booking_price, start_time, end_time):
    newbooking = Booking(
        booking_price=booking_price,
        start_time=datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S'),
        end_time=datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
    )
    newbooking.save()
    vehicle = Vehicle.objects(id=vehicle_id).first()
    vehicle.booking.append(newbooking)
    vehicle.save()
    return vehicle