Example #1
0
	def save(self, *args, **kwargs):
		# Saving the no. of days automatically from departure_date and arrival_date
		days_diff = self.arrival_date - self.departure_date
		diff = int(days_diff.days)
		self.no_of_days = diff
		# Saving the no. of person automatically by counting adult, children and infant
		self.total_person = int(self.no_of_adult + self.no_of_children + self.no_of_infant)

		if self.pk is not None and self.marketing_confirmation_status:
			print "update_form"
			
		# print self.accomodation
		if(self.marketing_confirmation_status):
			b = Booking.objects.filter(created_date__startswith = datetime.date.today()).count()
			if(self.created_date.month >= 10):
				month = str(self.created_date.month)
			else:
				month = '0' + str(self.created_date.month)
			if(self.created_date.day >= 10):
				day = str(self.created_date.day)
			else:
				day = '0' + str(self.created_date.day)
			book = Booking(customer = self.customer, remarks = self.remarks, departure_date = self.departure_date, arrival_date = self.arrival_date, no_of_days = self.no_of_days, 
				no_of_nights = self.no_of_nights, no_of_adult = self.no_of_adult, no_of_infant = self.no_of_infant, no_of_children = self.no_of_children, total_person = self.total_person,
				booking_id = 'BOOKID' + '_' + unicode(day +  month + str(self.created_date.year)) + '_' + str(b+1))
			# myMovieGenre = Movie_Info_genre.objects.create(genre='horror')
			# accomodation = AccomodationStar.objects.create(accomodation_star = )
			book.save()
			# for item in self.accomodation:
			# 	book.accomodation.add(item)

		super(Marketing, self).save(*args, **kwargs)
Example #2
0
    def post(self, request, bookable):
        booking = Booking()
        booking.user = self.context['user']
        booking.bookable = self.context['bookable']
        form = get_form_class(booking.bookable.metadata_form)(request.POST, instance=booking)
        self.context['form'] = form

        if form.is_valid():
            booking = form.instance
            booking.metadata = json.dumps(form.get_cleaned_metadata())

            if request.POST.get('repeat') and _is_admin(request.user, booking.bookable):
                repeatdata = {
                    'frequency': request.POST.get('frequency'),
                    'repeat_until': request.POST.get('repeat_until')
                }
                repeat_form = RepeatingBookingForm(repeatdata)
                if repeat_form.is_valid():
                    # Creates repeating bookings as specified, adding all created bookings to group
                    skipped_bookings = repeat_form.save_repeating_booking_group(booking)
                    return JsonResponse({'skipped_bookings': skipped_bookings})
                else:
                    return render(request, self.template, context=self.context, status=400)

            else:
                form.save()
        else:
            return render(request, self.template, context=self.context, status=400)

        booking.bookable.notify_external_services()

        return HttpResponse()
Example #3
0
 def setUp(self):
     self.loc = Location.objects.create(
         name="BroGym",
         address="Brophessor st. 12",
         description=
         "best gym get swole 100\%\ gains guaranteed live large die large leave a huge coffin"
     )
     self.user = User.objects.create_superuser(customer_number="92837465",
                                               email="*****@*****.**",
                                               password="******")
     self.b1 = Booking(id=1,
                       person=self.user,
                       title="Baiceps",
                       description="get de big baiceps",
                       location=self.loc,
                       start="2019-05-15T12:00:00Z",
                       end="2019-05-15T14:00:00Z")
     self.b1.save()
     self.b2 = Booking(id=2,
                       person=self.user,
                       title="legs",
                       description="skip legday",
                       location=self.loc,
                       start="2019-05-15T12:00:00Z",
                       end="2019-05-15T14:00:00Z")
     self.b2.save()
Example #4
0
 def setUp(self):
     self.restaurant = Restaurant.objects.create(
         name='da mario',
         city='vignola',
         address='via baracchini, 95',
         n_places=50,
         booking_duration=120)
     self.client_user = User.objects.create(first_name='paolo',
                                            last_name='verdi',
                                            email='*****@*****.**',
                                            username='******',
                                            user_type=User.TYPES[0][0])
     self.client_user.set_password('password')
     self.restaurant_user = User.objects.create(
         first_name='mario',
         last_name='rossi',
         email='*****@*****.**',
         username='******',
         user_type=User.TYPES[1][0],
         restaurant_information=self.restaurant)
     self.restaurant_user.set_password('password')
     restaurant_position = get_coordinates(self.restaurant.city + ', ' +
                                           self.restaurant.address)
     self.restaurant.latitude = restaurant_position['lat']
     self.restaurant.longitude = restaurant_position['lng']
     self.booking = Booking(
         client=self.client_user,
         restaurant=self.restaurant,
         n_places=2,
         start_time=timezone.make_aware(
             datetime.now(),
             timezone.get_current_timezone()).replace(microsecond=0),
         state=Booking.STATES[0][0])
     self.booking.end_time = self.booking.calculate_end_time()
Example #5
0
def booking(request):
    #THIS IS COSTYL
    cart_list = Cart.objects.all()
    CART_ID='CART-ID'
    cart_id=request.session[CART_ID]
    print(request.session[CART_ID])
    user_cart = Cart.objects.get(id=cart_id)
    item_list = Item.objects.filter(cart = user_cart)
    mailing_list = Mail.objects.all()
    if request.method == 'POST':
        form = BookingForm(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            #form.save()
            total_price = 0
            for item in item_list:
                total_price += item.product.price
            user_name = form.cleaned_data['user_name']
            user_sec_name = form.cleaned_data['user_sec_name']
            user_mail = form.cleaned_data['user_mail']
            user_phone =form.cleaned_data['user_phone']
            num  = random.randint(1, 10000)
            booking_item = Booking(name = "Заказ id" + " " + str(num), user_name = user_name, user_sec_name=user_sec_name, user_mail=user_mail, user_phone = user_phone, total_sum=total_price)
            booking_item.save()
            message = email_message(user_name, user_sec_name, user_mail, user_phone, total_price)
            print(item_list)
            for item in item_list:
                booking_item.items.add(item)
        return HttpResponseRedirect("/thanx/")
    else:
        form = BookingForm()
    data = {'form': form}

    return render(request, 'bookings.html', data)
Example #6
0
def book(request):
    pickup_location = request.session['pickup_location']
    dropoff_location = request.session['dropoff_location']
    pickup_date = request.session['pickup_date']
    dropoff_date = request.session['dropoff_date']
    pickup_time = request.session['pickup_time']
    dropoff_time = request.session['dropoff_time']
    driver = request.session['driver']
    username = request.session['name1']
    car_id = request.session['car_id']
    s = Booking(car_id=car_id,
                pickup_location=pickup_location,
                dropoff_location=dropoff_location,
                pickup_date=pickup_date,
                dropoff_date=dropoff_date,
                pickup_time=pickup_time,
                dropoff_time=dropoff_time,
                driver=driver,
                username=username)
    s.save()
    subject = 'Confirmation Mail For Booking'
    message = 'Your booking details are below.' + '\n' + '\nCar_id:' + car_id + '\nPickuplocation:' + pickup_location + '\nPickupDate:' + pickup_date + '\nPickupTime:' + pickup_time + ':00' + '\nDropoffLocation:' + dropoff_location + '\nDropoffDate:' + dropoff_date + '\nDropoffTime:' + dropoff_time + ':00' + '\nDriver:' + driver
    from_email = settings.EMAIL_HOST_USER
    to_list = [request.session['email']]
    send_mail(subject, message, from_email, to_list, fail_silently=True)
    booking = Booking.objects.filter(username=username)
    del request.session['pickup_location']
    del request.session['dropoff_location']
    del request.session['pickup_date']
    del request.session['dropoff_date']
    del request.session['pickup_time']
    del request.session['dropoff_time']
    del request.session['driver']
    del request.session['car_id']
    return HttpResponseRedirect('/booking/bookingHistory/')
Example #7
0
def run():
    # Delete db
    dealers = Dealer.objects.all()
    dealers.delete()
    vehicles = Vehicle.objects.all()
    vehicles.delete()
    bookings = Booking.objects.all()
    bookings.delete()

    json_data = open("datafile/dataset.json")
    data1 = json.load(json_data)

    # Create and save dealers
    for dealer in data1["dealers"]:
        dealer_to_save = Dealer()
        dealer_to_save.id = dealer["id"]
        dealer_to_save.name = dealer["name"]
        dealer_to_save.latitude = dealer["latitude"]
        dealer_to_save.longitude = dealer["longitude"]
        times = ""
        for time in dealer["closed"]:
            times = times + time + " "
        dealer_to_save.closed = times.rstrip()
        dealer_to_save.save()

        # Create and save vehicles
        for vehicle in dealer["vehicles"]:
            vehicle_to_save = Vehicle()
            vehicle_to_save.id = vehicle["id"]
            vehicle_to_save.dealerId = dealer_to_save
            vehicle_to_save.model = vehicle["model"]
            vehicle_to_save.fuel = vehicle["fuel"]
            vehicle_to_save.transmission = vehicle["transmission"]
            # Create availability strings
            availability_to_save = ""
            for availability in vehicle["availability"]:
                availability_to_save += availability
                times = " "
                for time in vehicle["availability"][availability]:
                    times += time + " "
                availability_to_save += times.rstrip() + "\n"
            vehicle_to_save.availability = availability_to_save
            vehicle_to_save.save()

    # Create booking
    for booking in data1["bookings"]:
        booking_to_save = Booking()
        booking_to_save.id = booking["id"]
        booking_to_save.firstName = booking["firstName"]
        booking_to_save.lastName = booking["lastName"]
        booking_to_save.vehicleId = Vehicle.objects.get(
            id=booking["vehicleId"])
        booking_to_save.pickupDate = datetime.strptime(booking["pickupDate"],
                                                       '%Y-%m-%dT%H:%M:%S')
        booking_to_save.createdAt = datetime.strptime(booking["createdAt"],
                                                      '%Y-%m-%dT%H:%M:%S.%f')
        booking_to_save.save()

    json_data.close()
Example #8
0
 def create(self, validated_data):
     booking = Booking(
         user=validated_data.get('user'),
         number_of_passengers=validated_data.get('number_of_passengers'),
         bus_route=validated_data.get('bus_route'),
         destination=validated_data.get('destination'),
         amount_paid=validated_data.get('amount_paid'))
     booking.save()
     return booking
Example #9
0
 def mutate(self, info, booking_data):
     if info.context.user.is_anonymous:
         raise GraphQLError('User not authenticated')
     customer = Customer.objects.get(id=booking_data.customer_id)
     property = Property.objects.get(id=booking_data.property_id)
     booking = Booking(property=property, customer=customer,
                       message=booking_data.booking_message)
     booking.save()
     return CreateBooking(booking=booking)
Example #10
0
def make_booking_in_past(start_date, end_date, title):
    """Save a booking without cleaning (validating) the data."""
    b = Booking(**dict(
        start_date=start_date,
        end_date=end_date,
        title=title,
    ))
    b.save()
    return b
def Book(request, *args, **kwargs):
    #API to check in to park
    #Needed parameters: userID and locationID
    if (request.method == 'POST'):
        user_id = request.POST.get('userID')
        u = User.objects.get(userID=user_id)
        location_id = request.POST.get('locationID')
        lot = Lot.objects.get(lotID=location_id)

        if (User.objects.filter(userID=user_id) and (u.userType >= lot.auth)
                and not Booking.objects.filter(user=u, status="Reserved")):

            time = request.POST.get('bookingTime')
            bookingPrice = 5000

            if (u.userBalance >= bookingPrice) and (lot.capacity > 0):
                b = Booking(user=(User.objects.get(userID=user_id)),
                            location=lot,
                            bookingTime=time,
                            status="Reserved")
                if (lot.lotID == "Motor_Sipil" or lot.lotID == "Motor_SR"
                        or lot.lotID == "Mobil_SR"):
                    lot.capacity -= 1
                    lot.save()
                b.save()
                u.userBalance = u.userBalance - bookingPrice
                u.save()

                #Send Check In Notification
                subject = 'Your booking are reserved!'
                message = 'Congratulations! \nYour booking at ' + str(
                    b.location.lotName
                ) + ' is reserved from ' + str(
                    b.bookingTime
                ) + ' until 1 hour after that. \nThe booking will cost you IDR 5,000 exclude parking fees.'
                to_list = [b.user.userEmail]
                send_mail(subject,
                          message,
                          settings.EMAIL_HOST_USER,
                          to_list,
                          fail_silently=True)

                #Generate output
                output = {
                    'bookingID': str(b.bookingID),
                    'bookingTime': str(b.bookingTime),
                    'location': str(b.location.lotName),
                }

                return JsonResponse(output)
            else:
                return HttpResponseBadRequest("ERR: Booking failed")
        else:
            return HttpResponseBadRequest("ERR: You are not allowed to book")
    else:
        return HttpResponseForbidden(
            "ERR: You are not allowed to access this endpoint.")
Example #12
0
 def test_is_current_in_the_past(self):
     """A simple booking."""
     today = datetime.today().date()
     last_week = today + timedelta(days=-7)
     b = Booking(**dict(
         start_date=last_week,
         end_date=last_week + timedelta(days=3),
         title='Three days in the sun'
     ))
     b.save()
     self.assertFalse(b.is_current())
Example #13
0
    def test_repeatBooking(self, repeat=True):
        dayofweek = 0  # day_map[form.cleaned_data['dayID'].upper()]
        cleaned_data = self.data
        start = cleaned_data['start']
        end = cleaned_data['end']
        year = int(start.year)
        month = int(start.month)
        day = int(start.day)  #[8:10])
        loc = cleaned_data['location']
        s_time = str(start)[-8:]  #get time substring
        e_time = str(end)[-8:]
        title = cleaned_data['title']
        descr = cleaned_data['description']
        b_list = []

        if True:
            cal = Calendar()
            ydcal = cal.yeardays2calendar(year, width=6)
            if month > 5:
                w = ydcal[1]
            else:
                w = ydcal[0]
            for m in range(len(w)):
                if m + 1 < month:
                    continue  #skip past months
                for k in range(len(w[m])):  #week in a month
                    for d in range(len(w[m][k])):  #days in a week
                        cal_day = w[m][k][d]
                        if (cal_day[0] < day
                                and m + 1 == month) or cal_day[0] == 0:
                            continue
                        if cal_day[1] == dayofweek:
                            # print("here")
                            if m < 9:  #format month
                                cal_m = "0" + str(m + 1)
                            else:
                                cal_m = str(m + 1)
                            if cal_day[0] < 9:  #format day
                                cal_d = "0" + str(cal_day[0])
                            else:
                                cal_d = str(cal_day[0])
                            date_format = str(year) + "-" + cal_m + "-" + cal_d
                            start_rec = date_format + " " + s_time
                            end_rec = date_format + " " + e_time
                            b = Booking(location=loc,
                                        start=start_rec,
                                        end=end_rec,
                                        title=title,
                                        description=descr)
                            b.save()
                            b_list.append(b)
        self.assertTrue(False)
        return b_list
Example #14
0
def addBooking(request):
    booking_id = request.POST.get('booking_id')
    booking_title = request.POST.get('booking_title')
    booking_type = request.POST.get('booking_type')
    booking_date = request.POST.get('booking_date')
    booking_desc = request.POST.get('booking_desc')
    add_booking = Booking(booking_id=booking_id,
                          booking_title=booking_title,
                          booking_type=booking_type,
                          booking_date=booking_date,
                          booking_description=booking_desc)
    add_booking.save()
    return showBooking(request)
def booking(request, pk=None):
    if request.method == "POST":
        if pk:
            hotel = Hotel.objects.get(pk=pk)
            guest = request.user
            check_in = request.POST['check_in_date']
            check_out = request.POST['check_out_date']
            no_of_guest = request.POST['bookingGuest']

            if not no_of_guest.isdigit():
                messages.error(request, 'Please Enter valid No of Guests.')
                return redirect(home)

            # check wether the dates are valid
            # case 1: a room is booked before the check_in date, and checks out after the requested check_in date
            case_1 = Booking.objects.filter(hotel=hotel,
                                            check_in__lte=check_in,
                                            check_out__gte=check_in).exists()

            # case 2: a room is booked before the requested check_out date and check_out date is after requested check_out date
            case_2 = Booking.objects.filter(hotel=hotel,
                                            check_in__lte=check_out,
                                            check_out__gte=check_out).exists()

            case_3 = Booking.objects.filter(hotel=hotel,
                                            check_in__gte=check_in,
                                            check_out__lte=check_out).exists()

            # if either of these is true, abort and render the error
            if case_1 or case_2 or case_3:
                messages.warning(
                    request,
                    'The room is not available on your selected dates')
                return redirect(home)

            # dates are valid
            booking = Booking(
                hotel=hotel,
                guest=guest,
                no_of_guest=no_of_guest,
                check_in=check_in,
                check_out=check_out,
            )

            booking.save()

            messages.success(request,
                             'Your Hotel has been Booked Successfully!')
            return redirect(dashboard)

        return render(request, 'users/home.html')
Example #16
0
def booking(request):
    template_name = 'app/booking-single.html'
    context = {'demo': "demo"}

    if request.method == "POST":
        hotel_id = request.POST['hotel_id']
        hotel = request.POST['hotel']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        person = request.POST['person']
        message = request.POST['msg']
        user_id = request.POST['user_id']

        enq = Booking(hotel_id=hotel_id, hotel=hotel, name=name, email=email, phone=phone, person=person,
                      message=message, user_id=user_id)
        enq.save()
        # send_mail(
        #     'Tour Enquiry for ' + tour.id,
        #     'There has been an enquiry for '+ tour.city_name + tour.id + 'for more detail please login in admin panel.',
        #     '*****@*****.**',
        #     [email, '*****@*****.**'],
        #     fail_silently=False
        # )
        # sender = '*****@*****.**'
        # recipient = '*****@*****.**'
        # msg = MIMEText("Message text")
        # msg = MIMEMultipart('alternative')
        # msg['Subject'] = "Tour Enquiry for " + tour_id
        # # msg['From'] = sender
        # msg['To'] = recipient
        #
        # html = message
        #
        # part2 = MIMEText(html, 'html')
        # msg.attach(part2)
        # server = smtplib.SMTP_SSL('smtp.zoho.com', 465)
        # server.login('*****@*****.**', 'Finflock123!')
        # server.sendmail(sender, [msg['To']], msg.as_string())
        # server.quit()

        messages.success(request, "Your enquiry has been submitted, our representative will call you!!!")

        # tours = Tour.objects.filter(available=True)
        # context = {"msg": "Your enquiry has been submitted, our representative will call you!!!"}

        return render(request, template_name, context)
    else:
        return render(request, template_name, context)
Example #17
0
    def create(self, validated_data):
        email = validated_data.pop('email')
        first_name = validated_data.pop('name')
        personal_number = validated_data.pop('personal_number')
        user_obj, created = User.objects.get_or_create(email=email)
        if created:
            user_obj.username = email
            user_obj.first_name = first_name
            user_obj.profile.personal_number = personal_number
            user_obj.save()
        # print(validated_data)
        booking = Booking(user=user_obj, **validated_data)
        booking.save()

        return booking
Example #18
0
    def __init__(self, *args, **kwargs):
        super(SearchBookingForm, self).__init__(*args, **kwargs)
        self.fields['booking_name'] = forms.ChoiceField(
            choices=Booking.get_bookings(),
            label=_('Booking:'),
            required=False,
            widget=forms.widgets.Select(attrs={'class': 'select2 optional'}))

        self.fields['responsible'] = forms.CharField(
            label=_('Responsible:'),
            required=False,
            widget=forms.widgets.Select(
                attrs={'class': 'select2 optional'},
                choices=Booking.get_responsibles(),
            ))
    def get_entity1(self):
        entity1 = Booking()
        entity1.booking_date = datetime.strptime("2015-02-01", "%Y-%m-%d")
        entity1.booking_timeslot = "0900"
        entity1.time_unit = "H"
        entity1.duration = 2
        entity1.notes = "Please prepare Tennis rackets for us."
        entity1.num_of_booking = 2
        entity1.rate = 100
        entity1.currency = "USD"

        return entity1
Example #20
0
    def setUp(self):
        # User objects.Non auth user
        self.user1 = OAuthUser.objects.create_user("temporary", "*****@*****.**", "temporary")
        # Auth user
        self.user2 = OAuthUser.objects.create_user("temporary2", "*****@*****.**", "temporary")

        self.user2.is_auth = True
        self.user2.save()

        # Auth user
        self.user3 = OAuthUser.objects.create_user("temporary3", "*****@*****.**", "temporary")

        self.user3.is_banned = True
        self.user3.save()

        # Create Booking object
        self.order = Booking(
            user=self.user2,
            swim_lane=3,
            start_date=datetime.datetime.now().date(),
            start_time="11:30:00",
            end_time="12:00:00",
        )
        self.order.save()
        # non exists order id
        self.fake_id = 9999

        self.client = Client()
Example #21
0
    def clean(self):
        """
        Custom form validation
        """
        cleaned_data = super().clean()

        # Check if the edited or created booking is not in the past (or currently effective)
        if timezone.now() > cleaned_data.get("start_date"):
            raise ValidationError(
                _("Start date cannot be in the past"), code="start_date_past"
            )

        # Check if start_date is before end_date
        if cleaned_data.get("end_date") < cleaned_data.get("start_date"):
            raise ValidationError(
                _("Start date cannot be after end date"), code="end_before_start"
            )

        # Check if the dates don't overlap an existing booking
        if Booking.check_overlap(
            cleaned_data.get("resource"),
            cleaned_data["start_date"],
            cleaned_data["end_date"],
        ):
            raise ValidationError(
                _("The resource is not available during this time range"),
                code="not_available",
            )
Example #22
0
 def test_get_places(self):
     self.booking = Booking.objects.all()
     self.place = Place.objects.get(id=8)
     result_place, result_place_name = Booking.get_places(self.booking)
     place_name = self.place.name.split('-')
     self.assertEqual(result_place[0], self.place)
     self.assertEqual(result_place_name[0], place_name[1])
Example #23
0
 def setUp(self):
     with open('secrets.json', 'r') as f:
         secret_key = json.load(f)
     LoginPlatform(name="airbnb").save()
     User(id=1,
          email='*****@*****.**',
          password=bcrypt.hashpw("qweasd123!".encode('utf-8'),
                                 bcrypt.gensalt()).decode('utf-8'),
          first_name='jiwon',
          last_name='ko',
          birth_date=datetime.datetime.strptime("1997-2-20", "%Y-%m-%d"),
          is_host=False,
          platform=LoginPlatform.objects.get(name="airbnb")).save()
     Amenity(name='amenity').save()
     Room(id=1,
          title='Room title',
          address='Room 주소',
          max_personnal='10',
          bed_room='침실',
          bed='퀸 사이즈',
          bath_room='욕실 한 개',
          price=100000,
          latitude=30,
          longitude=50,
          description='room 설명').save()
     BookingStatus(status='예약완료').save()
     PaymentMethod(name='체크카드').save()
     Booking(id=1,
             check_in=datetime.datetime.strptime("2020-08-10", "%Y-%m-%d"),
             check_out=datetime.datetime.strptime("2020-08-12", "%Y-%m-%d"),
             price=100000,
             cleaning_expense=10000,
             service_tax=3000,
             accomodation_tax=3000,
             adult=3,
             children=1,
             infants=0,
             user=User.objects.get(email='*****@*****.**'),
             room=Room.objects.get(title='Room title'),
             status=BookingStatus.objects.get(status='예약완료'),
             payment_method=PaymentMethod.objects.get(name='체크카드'),
             created_at=datetime.datetime.strptime("2020-08-09",
                                                   "%Y-%m-%d")).save()
     Review(booking=Booking.objects.get(id=1),
            content='리뷰 내용',
            cleanliness_score=4.0,
            communication_score=5.0,
            check_in_score=3.0,
            accuracy_score=2.5,
            location_score=3.5,
            satisfaction_score=4.0,
            created_at=datetime.datetime.strptime("2020-09-01",
                                                  "%Y-%m-%d")).save()
     self.token = jwt.encode(
         {
             'email': User.objects.get(email='*****@*****.**').email
         },
         secret_key['SECRET_KEY'],
         algorithm=ALGORITHM).decode('utf-8')
Example #24
0
def remove(roomnumber, bookingid):
    booking = Booking.query.filter_by(id=bookingid).first_or_404()
    db.session.delete(booking)
    db.session.commit()
    return render_template(
        'room.html',
        room=Room.query.filter_by(number=roomnumber).first(),
        bookings=Booking.getroombooking(roomnumber))
Example #25
0
def room(roomnumber):
    if request.method == "POST":
        room = Room.query.filter_by(number=roomnumber).first()
        date = request.form['date']
        start_time = request.form['from']
        end_time = request.form['to']
        roomnumber = roomnumber
        booking = Booking(date=date,
                          start_time=start_time,
                          end_time=end_time,
                          room=room)
        db.session.add(booking)
        db.session.commit()
    return render_template(
        'room.html',
        room=Room.query.filter_by(number=roomnumber).first(),
        bookings=Booking.getroombooking(roomnumber))
Example #26
0
File: tests.py Project: josh04/WTV
    def test_booking_creation(self):

        time_period = datetime.timedelta(30)

        b = Booking()
        b.user = self.test_user
        b.start_date = datetime.datetime.now()
        b.end_date = datetime.datetime.now()+time_period
        b.save()

        items = Kit.objects.all()
        b.kits = items

        b.save()
Example #27
0
def registered_booking(request):
    user_cart = Cart.objects.all()
    item_list = Item.objects.filter(cart = user_cart)
    mailing_list = Mail.objects.all()
    total_price=0
    if request.user.is_authenticated():
        user=request.user
        custom_user = CustomUser.objects.get(user=user)
        for item in item_list:
            total_price += item.product.price
        #Unblock on production
        #discount_total_price = total_price*(custom_user.discount/100)
        discount_total_price = total_price*0.2
        booking_item = Booking(name = "Заказ номер" + " " + str(1), user_name = user. first_name, user_sec_name=user.last_name, user_mail=user.email, user_phone = custom_user.phone, total_sum=discount_total_price)
        booking_item.save()
        for item in item_list:
                booking_item.items.add(item)
        return HttpResponseRedirect("/thanx/")
    def get_entity2(self):
        entity2 = Booking()
        entity2.booking_date = datetime.strptime("2015-03-01", "%Y-%m-%d")
        entity2.booking_timeslot = "1400"
        entity2.time_unit = "H"
        entity2.duration = 2
        entity2.num_of_booking = 2
        entity2.rate = 60
        entity2.currency = "EUR"

        return entity2
Example #29
0
def get_bookings_for_avail_cal(lYear, lMonth, shoulder_days, num_days_in_month,
                               first_day):
    # https://stackoverflow.com/questions/36155332/how-to-get-the-first-day-and-last-day-of-current-month-in-python
    last_day = dateutil.parser.parse(
        str(lYear) + '-' + str(lMonth) + '-' + str(num_days_in_month))
    # 6 days either side so we can do the shoulder days
    from_date = first_day - timedelta(days=shoulder_days)
    to_date = last_day + timedelta(days=shoulder_days)
    my_bookings = Booking.get_bookings_in_range(from_date, to_date, True)
    return my_bookings
Example #30
0
    def test_check_overlap(self):
        result = Booking.check_overlap(
            1,
            datetime(2020, 3, 1, 14, tzinfo=timezone("UTC")),
            datetime(2020, 3, 1, 18, tzinfo=timezone("UTC")),
        )
        self.assertFalse(result)

        result = Booking.check_overlap(
            1,
            datetime(2020, 3, 1, 7, tzinfo=timezone("UTC")),
            datetime(2020, 3, 1, 11, 30, tzinfo=timezone("UTC")),
        )
        self.assertTrue(result)

        result = Booking.check_overlap(
            1,
            datetime(2020, 3, 1, 10, tzinfo=timezone("UTC")),
            datetime(2020, 3, 1, 14, tzinfo=timezone("UTC")),
        )
        self.assertTrue(result)
Example #31
0
def book(request, bookable):
    if not request.user.is_authenticated:
        return render(request, 'modals/forbidden.html')
    booking = Booking()
    bookable_obj = get_object_or_404(Bookable, id_str=bookable)
    context = {
        'url': request.path,
        'bookable': bookable_obj,
        'user': request.user,
    }

    if request.method == 'GET':
        booking.start = dateutil.parser.parse(request.GET['st']) if 'st' in request.GET else datetime.now()
        booking.end = dateutil.parser.parse(request.GET['et']) if 'et' in request.GET else start + timedelta(hours=1)
        booking.bookable = bookable_obj
        booking.user = request.user
        form = BookingForm(instance=booking)
        status = 200
    elif request.method == 'POST':
        form = BookingForm(request.POST, instance=booking)
        if form.is_valid():
            form.save()
            return HttpResponse()
        else:
            status = 400
    else:
        raise Http404
    context['form'] = form
    return render(request, 'book.html', context=context, status=status)
Example #32
0
    def form_valid(self, form):
        if not self.request.user.is_authenticated:
            messages.add_message(self.request, messages.ERROR,
                                 'You need to be logged in to book a Pod.')
            return super(BookingFormView, self).form_invalid(form)

        user = self.request.user
        booking = Booking(start=form.cleaned_data['start'],
                          end=form.cleaned_data['end'],
                          purpose=form.cleaned_data['purpose'],
                          installer=form.cleaned_data['installer'],
                          scenario=form.cleaned_data['scenario'],
                          resource=self.resource,
                          user=user)
        try:
            booking.save()
        except ValueError as err:
            messages.add_message(self.request, messages.ERROR, err)
            return super(BookingFormView, self).form_invalid(form)
        try:
            if settings.CREATE_JIRA_TICKET:
                create_jira_ticket(user, booking)
        except JIRAError:
            messages.add_message(
                self.request, messages.ERROR, 'Failed to create Jira Ticket. '
                'Please check your Jira '
                'permissions.')
            booking.delete()
            return super(BookingFormView, self).form_invalid(form)
        messages.add_message(self.request, messages.SUCCESS, 'Booking saved')
        return super(BookingFormView, self).form_valid(form)
Example #33
0
    def post_render(self, request):
        form = BookingMetaForm(data=request.POST, owner=request.user)

        forms = self.repo_get(self.repo.BOOKING_FORMS, {})

        forms["meta_form"] = form
        self.repo_put(self.repo.BOOKING_FORMS, forms)

        if form.is_valid():
            models = self.repo_get(self.repo.BOOKING_MODELS, {})
            if "booking" not in models:
                models['booking'] = Booking()
            models['collaborators'] = []
            confirm = self.repo_get(self.repo.CONFIRMATION)
            if "booking" not in confirm:
                confirm['booking'] = {}

            models['booking'].start = timezone.now()
            models['booking'].end = timezone.now() + timedelta(
                days=int(form.cleaned_data['length']))
            models['booking'].purpose = form.cleaned_data['purpose']
            models['booking'].project = form.cleaned_data['project']
            for key in ['length', 'project', 'purpose']:
                confirm['booking'][key] = form.cleaned_data[key]

            if form.cleaned_data["deploy_opnfv"]:
                self.repo_get(self.repo.SESSION_MANAGER).set_step_statuses(
                    OPNFV_EnablePicker, desired_enabled=True)
            else:
                self.repo_get(self.repo.SESSION_MANAGER).set_step_statuses(
                    OPNFV_EnablePicker, desired_enabled=False)

            userprofile_list = form.cleaned_data['users']
            confirm['booking']['collaborators'] = []
            for userprofile in userprofile_list:
                models['collaborators'].append(userprofile.user)
                confirm['booking']['collaborators'].append(
                    userprofile.user.username)

            info_file = form.cleaned_data.get("info_file", False)
            if info_file:
                self.repo_put(self.repo.BOOKING_INFO_FILE, info_file)

            self.repo_put(self.repo.BOOKING_MODELS, models)
            self.repo_put(self.repo.CONFIRMATION, confirm)
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Form Validated',
                                 fail_silently=True)
            self.set_valid("Step Completed")
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 "Form didn't validate",
                                 fail_silently=True)
            self.set_invalid(
                "Please complete the fields highlighted in red to continue")
        return self.render(request)
Example #34
0
def booking(request):
    if request.method == 'POST':
        form = DateForm(request.POST)
        if form.is_valid():
            new_booking = Booking()
            new_booking.date = form.cleaned_data['date']
            new_booking.seats = form.cleaned_data['seats']
            new_booking.info = form.cleaned_data['info']
            new_booking.phone_number = form.cleaned_data['phone_number']

            opendate = OpenDate.objects.get(date = form.cleaned_data['date'])
            remaining = opendate.seats - int(form.cleaned_data['seats'])
            if remaining == 0:
                opendate.seats -= int(form.cleaned_data['seats'])
                opendate.is_booked = 1
            elif remaining == 1:
                opendate.seats = 0
                opendate.is_booked = 1
            else:
                opendate.seats = remaining
            opendate.save()

            new_booking.save()
            request.session['form-submitted'] = True
            try:
                send_mail(
                    subject = "Booking for " + new_booking.date.strftime('%Y-%m-%d'),
                    message = "A booking for " + new_booking.seats + " seats on " + new_booking.date.strftime('%Y-%m-%d') + " was made.",
                    from_email = "*****@*****.**",
                    recipient_list = ['*****@*****.**']
                )
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('confirmation')
    else:
        form = DateForm(initial = {'information' : 'Please enter all the information necessary as explained above.\nAny incomplete booking or without enough information will be automatically cancelled.'})

    dates = OpenDate \
            .objects \
            .filter(date__gte=datetime.date.today()) \
            .filter(is_booked = False)

    if dates:
        empty = 0
    else:
        empty = 1

    return render(request, 'booking/booking.html', dict(form=form, empty=empty))
Example #35
0
def search_booking_responsible(request, form_booking):
    form_day = form_booking.get_day()
    search_booking_responsible = form_booking["responsible"].data
    booking_responsible = form_booking["responsible"].data
    hours = [(6, "06-07"), (7, "07-08"), (8, "08-09"), (9, "09-10"),
             (10, "10-11"), (11, "11-12"), (12, "12-13"), (13, "13-14"),
             (14, "14-15"), (15, "15-16"), (16, "16-17"), (17, "17-18"),
             (18, "18-19"), (19, "19-20"), (20, "20-21"), (21, "21-22"),
             (22, ("22-23"))]

    table = []
    responsible = booking_responsible.split('\r')

    bookings = Booking.objects.filter(responsible__contains=responsible[0])

    if len(responsible) > 1:
        responsible_ = responsible[1].split('\n')
        bookings = Booking.objects.filter(
            responsible__contains=responsible_[1])

    places, place_names = Booking.get_places(bookings)

    for place in place_names:
        aux = []
        for booking in bookings:
            p = booking.place.name.split('-')
            if (booking.status > 1 and p[1] == place):
                book = booking.time.get(date_booking=str(form_day))
                aux_tuple = (book.start_hour.hour, booking)
                aux.append(aux_tuple)

        table.append(aux)

    n = len(places) + 1

    print(table)
    return render(
        request, 'booking/template_table.html', {
            'days': form_day,
            'table': table,
            'column_header': place_names,
            'hours': hours,
            'n': n,
            'name': _(' Responsible'),
            'place': places
        })
Example #36
0
    def get(self, request, bookable):
        booking = Booking()
        booking.start = dateutil.parser.parse(request.GET['st']) if 'st' in request.GET else datetime.now()
        # Remove the seconds and microseconds if they are present
        booking.start = booking.start.replace(second=0, microsecond=0)
        booking.end = dateutil.parser.parse(request.GET['et']) if 'et' in request.GET else booking.start + timedelta(hours=1)
        booking.bookable = self.context['bookable']

        booking.user = request.user
        form = get_form_class(booking.bookable.metadata_form)(instance=booking)
        self.context['form'] = form

        if _is_admin(request.user, booking.bookable):
            self.context['repeatform'] = RepeatingBookingForm()

        return render(request, self.template, context=self.context)
Example #37
0
def get_details(request, listing_id):
    user = request.user
    search_query = request.session.get('search_query')
    json_query = json.loads(search_query)

    available_dates_with_price = DBManager.get_available_dates_with_price(
        listing_id)
    listing = DBManager.get_listing_for_id(listing_id)
    best_time = DBManager.get_best_time_to_visit(listing_id)

    check_in_string = json_query.get('from_date')
    check_out_string = json_query.get('to_date')

    dict_dates = {
        'check_in': check_in_string,
        'check_out': check_out_string,
        'available_dates_with_price': available_dates_with_price
    }

    if request.method == "POST":
        booking_form = BookingForm(data=request.POST)

        if booking_form.is_valid():
            booking = booking_form.cleaned_data
            success = DBManager.add_booking(booking)
            if success == True:
                return render(request, 'listing/confirmation.html',
                              {'listing': listing})
            else:
                booking_form.errors['DB Error '] = success
        return render(
            request, 'listing/details/details.html', {
                'listing': listing,
                'booking_form': booking_form,
                'dict_dates': dict_dates,
                'best_time': best_time
            })
    else:
        booking = Booking()
        booking.customer_id = user.user_id
        booking.listing_id = listing_id
        booking.number_of_guests = json_query.get('num_guests')
        booking.price = 0
        booking_form = BookingForm(instance=booking)

        return render(
            request, 'listing/details/details.html', {
                'listing': listing,
                'booking_form': booking_form,
                'dict_dates': dict_dates,
                'best_time': best_time
            })
Example #38
0
def edit_booking(request, booking_id=None):
    """
    View for adding a new booking to the database.

    :param booking_id:
    :param request:
    :return:
    """
    if booking_id:
        booking = get_object_or_404(Booking, pk=booking_id)
    else:
        booking = Booking(requester=request.user)

    form = BookingForm(request.POST or None, instance=booking)
    if request.POST and form.is_valid():
        # check the permissions
        if not request.user.has_perm("booking.change_booking", booking):
            raise PermissionDenied("User may not edit booking")

        booking = form.save()

        form_html = render_crispy_form(
            BookingForm(instance=booking),
            context=csrf(request),
        )
        booking_html = render_to_string(
            "booking/partials/booking-item.html",
            {
                "booking": booking,
                "form": BookingForm(instance=booking),
                "include_game": bool(request.GET.get("include_game", False)),
                "include_group": bool(request.GET.get("include_group", False)),
            },
            request=request,
        )

        return JsonResponse({
            "success": True,
            "form_html": form_html,
            "booking_html": booking_html,
        })

    form_html = render_crispy_form(form, context=csrf(request))
    return JsonResponse({"success": False, "form_html": form_html})
Example #39
0
class SimpleTest(TestCase):
    def setUp(self):
        # User objects.Non auth user
        self.user1 = OAuthUser.objects.create_user("temporary", "*****@*****.**", "temporary")
        # Auth user
        self.user2 = OAuthUser.objects.create_user("temporary2", "*****@*****.**", "temporary")

        self.user2.is_auth = True
        self.user2.save()

        # Auth user
        self.user3 = OAuthUser.objects.create_user("temporary3", "*****@*****.**", "temporary")

        self.user3.is_banned = True
        self.user3.save()

        # Create Booking object
        self.order = Booking(
            user=self.user2,
            swim_lane=3,
            start_date=datetime.datetime.now().date(),
            start_time="11:30:00",
            end_time="12:00:00",
        )
        self.order.save()
        # non exists order id
        self.fake_id = 9999

        self.client = Client()

    def tearDown(self):
        self.user1.delete()
        self.user2.delete()
        self.order.delete()

    ########################
    # List of orders - GET #
    ########################
    def test_get_booking_list(self):
        url = reverse("booking_list_api")

        # Get by non login user
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)

        # Get by no auth user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)

        # Get by banned user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)

        # Get by auth user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    #########################
    # List of orders - POST #
    #########################
    def test_post_booking_list(self):
        url = reverse("booking_list_api")
        post = {"start_date": datetime.datetime.now().date(), "start_time": "11:30:00", "end_time": "12:00:00"}
        post_invalid_date_max = {
            "start_date": datetime.datetime.now().date() + datetime.timedelta(days=6),
            "start_time": "11:30:00",
            "end_time": "12:00:00",
        }
        post_invalid_date_min = {
            "start_date": datetime.datetime.now().date() - datetime.timedelta(days=2),
            "start_time": "11:30:00",
            "end_time": "12:00:00",
        }
        post_invalid_time = {
            "start_date": datetime.datetime.now().date(),
            "start_time": "11:31:00",
            "end_time": "12:00:00",
        }

        # Post by non login user
        response = self.client.post(url, post)
        self.assertEqual(response.status_code, 403)

        # Post by no auth user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.post(url, post)
        self.assertEqual(response.status_code, 403)

        # Post by banned user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.post(url, post)
        self.assertEqual(response.status_code, 403)

        # Post by auth user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.post(url, post)
        self.assertEqual(response.status_code, 201)

        # Post by auth user with invalid date - max
        response = self.client.post(url, post_invalid_date_max)
        self.assertEqual(response.status_code, 400)

        # Post by auth user with invalid date - post past date
        response = self.client.post(url, post_invalid_date_min)
        # print(response.content)
        self.assertEqual(response.status_code, 400)

        # Post by auth user with invalid time
        response = self.client.post(url, post_invalid_time)
        self.assertEqual(response.status_code, 400)

        # Post if fully booked at this time(6 lines)
        self.client.post(url, post)  # 3
        self.client.post(url, post)  # 4
        self.client.post(url, post)  # 5
        self.client.post(url, post)  # 6
        response = self.client.post(url, post)  # 7
        self.assertEqual(response.status_code, 400)

    def test_delete_order(self):
        url_detail = reverse("booking_detail_api", args=(self.order.id,))

        # delete order by no login user
        response = self.client.delete(url_detail)
        self.assertEqual(response.status_code, 403)

        # delete order by no auth user
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.delete(url_detail)
        self.assertEqual(response.status_code, 403)
        """
        # delete order by auth user, but no owner this order
        self.client.login(email='*****@*****.**', password='******')
        response = self.client.delete(url_detail)
        self.assertEqual(response.status_code, 403)
        """
        # delete order by auth user and owner this order
        self.client.login(email="*****@*****.**", password="******")
        response = self.client.delete(url_detail)
        self.assertEqual(response.status_code, 204)