def test_start_end_time_inverstion_raises_exception(self): """ Reservation with begin after end must raise ValidationError """ r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc) self.assertRaises(ValidationError, r.save)
def new_reservation(request): data = dict() try: if request.method == 'POST': customer = Customer.objects.get(id=request.POST['customer_id']) reservation_service = Service.objects.get(id=request.POST['service_id']) reservation_length = int(request.POST['reservation_length']) start_datetime = datetime.datetime.strptime(request.POST['reservation_date'] + ' ' + request.POST['reservation_time'] , '%Y-%m-%d %H:%M') end_datetime = start_datetime + datetime.timedelta(minutes=reservation_length) date = start_datetime.date() start_time = start_datetime.time() end_time = end_datetime.time() reservation_obj = Reservation(customer=customer, date=date, start_time=start_time, end_time=end_time, reservation_service=reservation_service) reservation_obj.full_clean() validate_past_time(reservation_obj) validate_self(reservation_obj) validate_other(reservation_obj) validate_checked_in(customer) reservation_obj.save() data['ret'] = 0 except ValidationError as e: data['ret'] = 1 data['message'] = str(e) return JsonResponse(data)
def test_ended_reservation_termination_raises_exception(self): """ Ended reservations may not be terminated """ r = Reservation(user=self.user) now = datetime.datetime.utcnow().replace(tzinfo=utc) r.startTime = now + datetime.timedelta(days=-14) r.endTime = now + datetime.timedelta(days=-7) r.save(full_clean=False) self.assertRaises(ValidationError, r.terminate)
def test_future_reservation_termination_raises_exception(self): """ Future reservations may not be terminated """ r = Reservation(user=self.user) now = datetime.datetime.utcnow().replace(tzinfo=utc) r.startTime = now + datetime.timedelta(days=10) r.endTime = now + datetime.timedelta(days=12) r.save() self.assertRaises(ValidationError, r.terminate)
def mutate(root, info, input=None): ok = True reservation_instance = Reservation( start_time = input.start_time, end_time = input.end_time, client = input.client, # TODO: create new client or assign existing calendar = input.calendar # TODO: create new calendar or assign existing ) reservation_instance.save() return CreateReservation(ok=ok, reservation=reservation_instance)
def reserve_flat(request): # data from url flat_id = request.GET.get('flat_id', '') rsd = request.GET.get('rsd', '') red = request.GET.get('red', '') if not (flat_id and rsd and red): raise Http404('Something went wrong') try: flat = Flat.check__if_flat_is_available(rsd, red, flat_id) except Flat.DoesNotExist: request.session['message'] = 'It seems that such flat does not exist' return redirect('reserve_flat_result') if request.method == 'POST': form = ReserveFlat(request.POST) if form.is_valid(): rb = form.cleaned_data['reserved_by'] try: flat_is_reserved = Reservation.check_if_flat_is_reserved( flat_id, rsd, red) except ValidationError: raise Http404('Something went wrong') if flat_is_reserved: request.session[ 'message'] = 'It seems that this flat is no longer available for this time frame' return redirect('reserve_flat_result') else: Reservation(reservation_start_date=rsd, reservation_end_date=red, reserved_by=rb, flat=flat).save() request.session[ 'message'] = 'You have reserved the flat successfully' return redirect('reserve_flat_result') else: return render(request, 'reserve_flat.html', { 'form': form, 'rsd': rsd, 'red': red, 'flat': flat }) else: form = ReserveFlat() return render(request, 'reserve_flat.html', { 'form': form, 'rsd': rsd, 'red': red, 'flat': flat })
def reserve_nearest_parking(request): """The nearest parking slot would be reserved if, the user does not provide a parking slot id. """ request_body = request.body.decode("utf-8") data = json.loads(request_body) current_user = request.user data["user_id"] = current_user.id start_date = data.get("start_date") finish_date = data.get("finish_date") # check the chosen date is valid if not check_time_validity(start_date, finish_date): return JsonResponse({"result": "Please choose a valid time range!"}, status=400) reserved_parking_slots = (Reservation.objects.filter( finish_date__gt=timezone.now()).select_related( "parking_slot").values_list("parking_slot_id", flat=True)) all_parking_slots = ParkingSlot.objects.values_list("id", flat=True) # retrieve the first available parking that isn't reserved now available_parking = all_parking_slots.exclude( id__in=set(reserved_parking_slots)).first() if not available_parking: return JsonResponse( {"result": "No parking is available for reserve right now!"}, status=404) data["parking_slot_id"] = available_parking Reservation(**data).save() return JsonResponse(data={"result": "Reservation done!"}, status=200)
def reserv(): form = ReservationForm() if form.validate_on_submit(): reservation = Reservation( Room.query.filter_by(room_num=session['room_num']).first(), form.first_name.data, form.last_name.data, form.date_in.data, form.date_out.data, form.members.data, form.email.data, form.phone_num.data, form.address.data, form.city.data, form.state.data, form.zip_code.data, False, False) room = Room.query.filter_by(room_num=session['room_num']).first() room.book_from = form.date_in.data room.book_release = form.date_out.data first_name = form.first_name.data last_name = form.last_name.data date_in = form.date_in.data date_out = form.date_out.data ##confirmation email msg = Message('Magnet Reservation', sender='*****@*****.**', recipients=[form.email.data]) msg.body = "This is the email body" msg.html = render_template('reservation/booking_confirm.html', first_name=first_name, last_name=last_name, date_in=date_in, date_out=date_out) mail.send(msg) db.session.commit() db.session.add(reservation) db.session.commit() return redirect('/res_confirm') return render_template('reservation/reserv.html', form=form)
def display_reservation_list(request): if request.method == 'POST': form = DisplayFlatReservations(request.POST) if form.is_valid(): flat = form.cleaned_data['flat'] list_of_dates_flat_can_be_reserved = [ e.strftime("%Y-%m-%d") for e in date_range( flat.available_from, flat.available_to, freq='D') ] reservations_list = Reservation.reservation_list_for_flat(flat) return render( request, 'display_reservation_list.html', { 'dates': list_of_dates_flat_can_be_reserved, 'dates2': reservations_list, 'month': flat.available_from.month, 'year': flat.available_from.year, 'form': form }) else: return render(request, 'display_reservation_list.html', {'form': form}) else: flat_id = request.GET.get('flat_id', '') form = DisplayFlatReservations() if flat_id: try: flat = Flat.objects.get(pk=flat_id) except Flat.DoesNotExist: raise Http404('It seem that this flat dose not exists') list_of_dates_flat_can_be_reserved = [ e.strftime("%Y-%m-%d") for e in date_range( flat.available_from, flat.available_to, freq='D') ] reservations_list = Reservation.reservation_list_for_flat(flat) form = DisplayFlatReservations(initial={'flat': flat}) return render( request, 'display_reservation_list.html', { 'dates': list_of_dates_flat_can_be_reserved, 'dates2': reservations_list, 'month': flat.available_from.month, 'year': flat.available_from.year, 'form': form }) else: return render(request, 'display_reservation_list.html', {'form': form})
def test_device_reservability(self): # add a basic reservation r = Reservation(user=self.user) r.startTime = datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.save() # device can be reserved if not blocked self.assertEqual(True, self.d1.isReservable( datetime.datetime(2112, 10, 12, 8, 0, 0).replace(tzinfo=utc), datetime.datetime(2112, 10, 12, 9, 0, 0).replace(tzinfo=utc) )) self.assertEqual(True, self.d1.isReservable( datetime.datetime(2112, 10, 12, 8, 0, 0).replace(tzinfo=utc), datetime.datetime(2112, 10, 12, 9, 59, 59).replace(tzinfo=utc) )) self.assertEqual(False, self.d1.isReservable( datetime.datetime(2112, 10, 12, 8, 0, 0).replace(tzinfo=utc), datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc) )) self.assertEqual(False, self.d1.isReservable( datetime.datetime(2112, 10, 11, 8, 0, 0).replace(tzinfo=utc), datetime.datetime(2112, 10, 16, 10, 0, 0).replace(tzinfo=utc) )) self.assertEqual(True, self.d1.isReservable( datetime.datetime(2112, 10, 18, 8, 0, 0).replace(tzinfo=utc), datetime.datetime(2112, 10, 20, 10, 0, 0).replace(tzinfo=utc) ))
def create_reservation(request): reservation = Reservation() if request.method == "POST": reservation_form = ReservationForm(request.POST) contact_form = ContactForm(request.POST) pickup_address_form = AddressForm(request.POST, prefix="pickup") dropoff_address_form = AddressForm(request.POST, prefix="dropoff") if reservation_form.is_valid() and contact_form.is_valid() and pickup_address_form.is_valid() and dropoff_address_form.is_valid(): contact = contact_form.save() pickup_address = pickup_address_form.save() dropoff_address = dropoff_address_form.save() reservation = reservation_form.save(commit=False) reservation.customer = contact reservation.pickup_address = pickup_address reservation.dropoff_address = dropoff_address reservation.company = request.user.profile.client reservation.save() reservation_form.save_m2m() return HttpResponseRedirect('/reservation/') else: reservation_form = ReservationForm(instance=Reservation()) contact_form = ContactForm(instance=Contact()) pickup_address_form = AddressForm(instance=Address(), prefix="pickup") dropoff_address_form = AddressForm(instance=Address(), prefix="dropoff") return render_to_response('reservation/update.html', { 'reservation_form' : reservation_form, 'reservation':reservation, 'contact_form':contact_form, 'pickup_address_form':pickup_address_form, 'dropoff_address_form':dropoff_address_form }, context_instance=RequestContext(request))
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data serializer.save(queue=Reservation.count()) # serializer.save(queue=Reservation.count(), user=request.user) headers = self.get_success_headers(serializer.data) # return Response(self.get_serializer(reservation).data, status=status.HTTP_201_CREATED, headers=headers) return Response(data, status=status.HTTP_201_CREATED, headers=headers)
def test_active_reservation_termination(self): """ Active reservations should not be running after termination """ r = Reservation(user=self.user) now = datetime.datetime.utcnow().replace(tzinfo=utc) r.startTime = now + datetime.timedelta(days=-1) r.endTime = now + datetime.timedelta(days=10) r.save(full_clean=False) r.terminate(full_clean=False) self.assertFalse(r.is_running())
def finish(request): if request.method == "POST": positions_json = request.POST.get('positions', None) schedule_id = request.POST.get('schedule_id', None) if positions_json and schedule_id: booked_tickets = [] # Save user's selected to session for reselect request.session['positions'] = positions_json request.session['schedule_id'] = schedule_id # Create new reservation reservation = Reservation(customer=request.user) reservation.save() positions = json.loads(positions_json) try: with transaction.atomic(): for position in positions: ticket = Ticket.objects.get( row=position[0], column=position[1], schedule__id=schedule_id, ) ticket.reservation = reservation ticket.save() booked_tickets.append(ticket) except InternalError as e: schedule = Schedule.objects.get(pk=schedule_id) ticket_types = TicketType.objects.all() messages.add_message(request, messages.INFO, e.message) return render(request, 'make-reservation.html', { 'schedule': schedule, 'ticket_types': ticket_types} ) return render(request, 'final-step.html', { 'booked_tickets': booked_tickets, 'schedule': Schedule.objects.get(pk=schedule_id), } )
def reserve_table(restaurant_name, dt, people, reservation_length_hrs=None): if dt.tzinfo is None: dt = pytz.utc.localize(dt) try: restaurant = Restaurant.objects.get(name=restaurant_name) except Restaurant.DoesNotExist: raise NoSuchRestaurantError( "Could not retrieve restaurant named %s" % (restaurant_name, ) ) if restaurant.is_closed(dt): raise RestaurantClosedError current_reservations = restaurant.reservations_ongoing(dt) if reservation_length_hrs is None: # 5400 seconds = 1.5hrs _length = 5400 else: _length = reservation_length_hrs * 3600 new_res = Reservation( restaurant=restaurant, datetime=dt, people=people, _length=_length ) if restaurant.is_closed(new_res.endtime): raise ReservationNotPossibleError try: pack_tables(current_reservations + [new_res], restaurant.tables) new_res.save() return new_res.id except UnableToPackTablesError: raise ReservationNotPossibleError( "Not enough tables available to accomodate %s people" % ( people, ) ) raise ReservationNotPossibleError
def test_simple_reservation_creation(self): r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.save() self.assertEqual(Reservation.objects.get(id=1).devices.all()[0], self.d1)
def post(self, request, car): form = ReservationForm(request.POST) description = Car.objects.get(id=car) if not request.user.is_authenticated: return redirect('/login') if form.is_valid(): data1 = form.cleaned_data['start_date'] data2 = form.cleaned_data['end_date'] reservation = Reservation(user=request.user, car=description, start_date=data1, end_date=data2) is_available = reservation.check_dates() if data1 > data2: return render( request, 'car_view.html', { 'description': description, 'form': form, 'message': 'Data zakończenia wynajmu jest wcześniejsza niż rozpoczęcia!' }) if is_available: reservation.save() return redirect('/email') else: return render( request, 'car_view.html', { 'description': description, 'form': form, 'message': 'Auto jest niedostępne w tym terminie!' }) else: return render(request, 'car_view.html', { 'description': description, 'form': form })
def test_no_reservation_creation_in_the_past(self): """ Reservations must begin at or after the current system now """ r = Reservation(user=self.user) r.startTime = datetime.datetime(2011, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2011, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.save() self.assertRaises(ValidationError, r.save)
def reservations(request): data = dict() try: if request.method == 'GET': valid_reservations = Reservation.objects.filter(date__gte=current_time().date()).filter(status__exact='N') data['reservations'] = [dumpJson(r) for r in valid_reservations] else: customer = Customer.objects.filter(id == request.POST['customer_id']) reservation_service = Service.objects.filter(id == request.POST['service_id']) reservation_length = request.POST['reservation_length'] reservation_date_time = datetime.datetime.strptime(request.POST['reservation_time'], '%Y-%m-%d %H:%M') reservation_obj = Reservation(customer=customer, reservation_date_time=reservation_date_time, reservation_length=reservation_length, reservation_service=reservation_service) reservation_obj.save() data['service'] = dumpJson(reservation_obj) data['ret'] = 0 except ValidationError as e: data['ret'] = 1 data['message'] = str(e) return JsonResponse(data)
def test_adding_devices_to_reservation(self): # add a basic reservation r = Reservation(user=self.user) r.startTime = datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.save() newRes = r.addDevices(datetime.datetime(2112, 10, 12, 12, 0, 0).replace(tzinfo=utc), [self.d2]) self.assertEqual(newRes.endTime, datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc)) self.assertEqual(newRes.startTime, datetime.datetime(2112, 10, 12, 12, 0, 0).replace(tzinfo=utc)) self.assertEqual(Reservation.objects.get(id=1).endTime, datetime.datetime(2112, 10, 12, 11, 59, 59).replace(tzinfo=utc)) self.assertEqual(self.d1 in newRes.devices.all(), True) self.assertEqual(self.d2 in newRes.devices.all(), True)
def new_reservation(): form = reservationForm() if form.validate_on_submit(): if form.date.data < datetime.now().date(): flash("You cannot book dates in the past") return redirect(url_for('new_reservation')) user = User.query.filter_by(email=str(current_user.email)).first() reservation = Reservation(package=form.package.data, date=form.date.data, location=form.location.data, occasion=form.occasion.data, addons=form.addons.data, user_id=user.id) db.session.add(reservation, current_user) db.session.commit() flash("Reservation created!") return redirect(url_for('index')) return render_template('reservation.html', title="Make Reservation", form=form)
def index(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): city = form.cleaned_data['city'] rsd = form.cleaned_data['reservation_start_date'] red = form.cleaned_data['reservation_end_date'] available_flats = Flat.display_available_flats(city, rsd, red) unavailable_reservations = Reservation.display_unavailable_reservations( rsd, red) unavailable_flats_pk_set = [ e.flat.pk for e in unavailable_reservations ] available_flats = available_flats.exclude( pk__in=unavailable_flats_pk_set) if available_flats: return render( request, 'index.html', { 'form': form, 'available_flats': available_flats, 'rsd': rsd.isoformat(), 'red': red.isoformat() }) else: message = 'There are no available flats for your query! ' \ 'Maybe try another city or date ranges' return render(request, 'index.html', { 'form': form, 'message': message }) else: return render(request, 'index.html', {'form': form}) else: form = SearchForm() return render(request, 'index.html', {'form': form})
def reserve_parking(request): """User can choose a desired parking spot. If the spot isn't reserved in the chosen time range, the reservation objects will be saved. """ request_body = request.body.decode("utf-8") data = json.loads(request_body) current_user = request.user data["user_id"] = current_user.id start_date = data.get("start_date") finish_date = data.get("finish_date") # check the chosen date is valid if not check_time_validity(start_date, finish_date): return JsonResponse({"result": "Please choose a valid time range!"}, status=400) if not ParkingSlot.objects.filter(id=data.get("parking_slot_id")).exists(): return JsonResponse( {"result": "The requested Parking slot doesn't exist!"}, status=400) if Reservation.objects.filter( Q(parking_slot_id=data.get("parking_slot_id")) & (Q(start_date__range=[start_date, finish_date]) | Q(finish_date__range=[start_date, finish_date]))).exists(): return JsonResponse( { "result": "Dates overlaps. Try other dates and / or parking space." }, status=403, ) else: Reservation(**data).save() return JsonResponse(data={"result": "Reservation done!"}, status=200)
def post(self, request, branch_code): reservation = Reservation() reservation.branch = Branch.objects.get(code=branch_code) reservation.first_name = request.POST.get('first-name') reservation.last_name = request.POST.get('last-name') reservation.email = request.POST.get('email') reservation.special_request = request.POST.get('special-request') reservation.date = request.POST.get('date') reservation.time = request.POST.get('time') reservation.persons = int(request.POST.get('persons')) reservation.save() context = { 'reservation': reservation, 'url': request.build_absolute_uri( reverse('acknowledge-reservation', args=[reservation.id])) } send_mail( 'reservation-mail.html', context, '*****@*****.**', # from [reservation.branch.admin_email] # to ) return redirect('reservation-complete', reservation.id)
def reservationConfirm(request): setting = Settings.objects.get(pk=1) category = Category.objects.all() current_user = request.user if request.method == 'POST': form = ReservationConfirmForm(request.POST) if form.is_valid(): data = Reservation() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = form.cleaned_data['total'] data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() detail = ReservationRoom() detail.reservation_id = data.id detail.room_id = form.cleaned_data['roomid'] detail.user_id = current_user.id detail.checkin = form.cleaned_data['checkin'] detail.checkout = form.cleaned_data['checkout'] detail.person = form.cleaned_data['person'] detail.quantity = 1 room = Room.objects.get(id=detail.room_id) room.amount -= 1 room.save() detail.price = room.price detail.amount = room.amount detail.save() messages.success( request, "Rezervasyonunuz işleminiz başarı ile gerçekleştirildi. Teşekkür Ederiz." ) context = { 'setting': setting, 'category': category, 'ordercode': ordercode, } return render(request, "reservation_complated.html", context) messages.error(request, form.errors) return HttpResponseRedirect('/reservation/details/')
def request_reservation(request, pk): global count customer = request.user shop_name = get_object_or_404(Store, pk=pk) macaron_name = request.POST.get('choice') if not macaron_name: messages.error(request, 'ERROR: Please choice MACARON TYPE!') return HttpResponseRedirect(reverse('reservation:reserve', args=(pk, ))) quantity = int(request.POST.get(macaron_name)) if quantity == 0: messages.error(request, 'ERROR: Please fill the form of COUNT') return HttpResponseRedirect(reverse('reservation:reserve', args=(pk, ))) reser_request_time = timezone.datetime.now() #convert date value and time value to Datetime form if (request.POST.get('date') == '' or request.POST.get('time') == ''): messages.error(request, 'ERROR: Please fill the form of DATE and TIME') return HttpResponseRedirect(reverse('reservation:reserve', args=(pk, ))) date = datetime.datetime.strptime(request.POST.get('date'), "%Y-%m-%d").date() time = datetime.datetime.strptime(request.POST.get('time'), "%H:%M").time() reser_time = datetime.datetime.combine(date, time) if request.method == 'POST': reservation = Reservation() count += 1 if (count > 999): count = 1 reservation.reser_num = int( reser_request_time.strftime('%Y%m%d') + str(shop_name.id).zfill(4) + str(count).zfill(3)) reservation.customer = customer reservation.shop_name = shop_name reservation.quantity = quantity macaron_list = shop_name.macarons_set.all() for macaron in macaron_list: if macaron.name == macaron_name: price = macaron.price if quantity > macaron.stock: messages.error( request, "ERROR: You can only reserve less than left macaron") return HttpResponseRedirect( reverse('reservation:reserve', args=(pk, ))) macaron.stock -= quantity macaron.save() break reservation.amount = int(quantity * price) reservation.choice_macaron = macaron_name reservation.reser_request_time = reser_request_time reservation.reser_time = reser_time reservation.save() messages.success(request, 'Reservation success!') return HttpResponseRedirect(reverse('reservation:reserve', args=(pk, ))) return HttpResponseRedirect(reverse('reservation:reserve', args=(pk, )))
def reservationvehicle(request): category = Category.objects.all() current_user = request.user schopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in schopcart: total += rs.vehicle.price * rs.quantity if request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): data = Reservation() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.kalkisyeri = form.cleaned_data['kalkisyeri'] data.varisyeri = form.cleaned_data['varisyeri'] data.date = form.cleaned_data['date'] data.total = total data.ip = request.META.get('REMOTE_ADDR') reservationcode = get_random_string(5).upper() data.code = reservationcode data.save() schopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in schopcart: detail = ReservationVehicle() detail.reservation_id = data.id detail.vehicle_id = rs.vehicle_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.varisyeri = form.cleaned_data['varisyeri'] detail.kalkisyeri = form.cleaned_data['kalkisyeri'] detail.date = form.cleaned_data['date'] vehicle = Vehicle.objects.get(id=rs.vehicle_id) vehicle.amount -= rs.quantity vehicle.save() detail.price = rs.vehicle.price detail.amount = rs.amount detail.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 profile = UserProfile.objects.get(user_id=current_user.id) messages.success(request, "Your Reservation has been completed!") return render( request, 'user_profile.html', { 'reservationcode': reservationcode, 'category': category, 'profile': profile }) else: messages.warning(request, form.errors) return HttpResponseRedirect("/reservation/reservationvehicle") form = ReservationForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'schopcart': schopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, } return render(request, 'Reservation_Form.html', context)
def setUpClass(cls): print( '\n ============== JEDNOSTKOWE TESTY WYŚWIETLANIA DOSTĘPNYCH SAL ============== \n' ) test_room_1 = Room(id=1, number=126, wing='B2', number_of_seats=125, number_of_computers=0) test_room_2 = Room(id=2, number=127, wing='B2', number_of_seats=125, number_of_computers=0) test_room_3 = Room(id=3, number=128, wing='B2', number_of_seats=125, number_of_computers=0) test_room_4 = Room(id=4, number=129, wing='B2', number_of_seats=125, number_of_computers=0) test_room_5 = Room(id=5, number=130, wing='B2', number_of_seats=125, number_of_computers=0) cls.room_list = [ test_room_1, test_room_2, test_room_3, test_room_4, test_room_5 ] test_reservation_1 = Reservation(date=date(2019, 10, 3), hour=time(8, 0), user_id=1, room=test_room_1, is_cyclic=False, is_every_two_weeks=False) test_reservation_2 = Reservation(date=date(2019, 10, 3), hour=time(9, 45), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_3 = Reservation(date=date(2019, 10, 3), hour=time(11, 30), user_id=1, room=test_room_3, is_cyclic=False, is_every_two_weeks=False) test_reservation_4 = Reservation(date=date(2019, 10, 3), hour=time(16, 45), user_id=1, room=test_room_4, is_cyclic=False, is_every_two_weeks=False) test_reservation_5 = Reservation(date=date(2019, 10, 3), hour=time(15, 0), user_id=1, room=test_room_5, is_cyclic=False, is_every_two_weeks=False) cls.reservation_list = [ test_reservation_1, test_reservation_2, test_reservation_3, test_reservation_4, test_reservation_5 ] test_reservation_6 = Reservation(date=date(2019, 10, 9), hour=time(8, 0), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_7 = Reservation(date=date(2019, 10, 9), hour=time(9, 45), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_8 = Reservation(date=date(2019, 10, 9), hour=time(11, 30), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_9 = Reservation(date=date(2019, 10, 9), hour=time(13, 15), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_10 = Reservation(date=date(2019, 10, 9), hour=time(15, 0), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_11 = Reservation(date=date(2019, 10, 9), hour=time(16, 45), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) test_reservation_12 = Reservation(date=date(2019, 10, 9), hour=time(18, 30), user_id=1, room=test_room_2, is_cyclic=False, is_every_two_weeks=False) cls.busy_reservation_list = [ test_reservation_6, test_reservation_7, test_reservation_8, test_reservation_9, test_reservation_10, test_reservation_11, test_reservation_12 ]
def reservationcar(request, id): url = request.META.get('HTTP_REFERER') # get last url current_user = request.user # access user session information car = Car.objects.get(pk=id) carUrl = "/car/" + str(id) + "/" + car.slug if request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): data = Reservation() data.first_name = current_user.first_name data.last_name = current_user.last_name data.phone = form.cleaned_data['phone'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.country = form.cleaned_data['country'] data.date = form.cleaned_data['date'] data.time = form.cleaned_data['time'] data.quantity = form.cleaned_data['quantity'] data.take_off = form.cleaned_data['take_off'] data.arrive = form.cleaned_data['arrive'] data.user_id = current_user.id data.price = form.cleaned_data['price'] data.ip = request.META.get('REMOTE_ADDR') reservationcode = get_random_string(5).upper() data.code = reservationcode data.save() detail = ReservationCar() detail.reservation = data detail.car_id = id detail.user_id = current_user.id detail.quantity = car.amount detail.price = car.price detail.amount = car.amount detail.date = form.cleaned_data['date'] detail.save() car = Car.objects.get(id=id) car.amount -= 1 car.save() messages.success( request, "Your reservation has been completed. Thank you'") return HttpResponseRedirect("/reservation/reservationcompleted/" + str(data.id)) else: messages.warning(request, "Error <br>" + str(form.errors)) return HttpResponseRedirect(carUrl) else: messages.warning(request, "No Post") return HttpResponseRedirect(carUrl)
def continue_reservation(request, reservation_seat_ids, session_id): session = Session.objects.get(pk=session_id) seat_ids = reservation_seat_ids.split(',') seats = [] price = 0 for id in seat_ids: seat = get_object_or_None(Seat, pk=id) r = get_object_or_None(ReservationSeat, session=session, seat=seat) if not r: seats.append(seat) price += SessionSeatTypePrice.objects.get(seat_type=seat.type, session=session).price if seats: film_name = session.film_cinema.film.name date_time_start = session.datetime_start date_time_end = session.datetime_end else: return redirect(request.META['HTTP_REFERER']) if request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): tickets = [] name = form.cleaned_data['name'] surname = form.cleaned_data['surname'] email = form.cleaned_data['email'] for seat in seats: r = ReservationSeat(session=session, seat=seat) r.save() t = Ticket.objects.create(reservation_seat=r) t.save() tickets.append(t) reservation = Reservation(name=name, surname=surname, email=email) reservation.save() for ticket in tickets: reservation.tickets.add(ticket) reservation.save() send_mail( "Регестрация билета", f'Здравствуйте {name} {surname}.' f'Вы заказали билеты в количестве {len(tickets)}. Номер заказа - {reservation.id}' f' на фильм {film_name} который пройдет' f' {datetime.datetime.strftime(date_time_start,"%m.%d %a %H:%M")} - {datetime.datetime.strftime(date_time_end,"%H:%M")}.' f'Вы можете оплатить билеты на кассе. ' f'Помните, пока вы только забронировали билеты, их нужно выкупить', 'СinemaHouse+', [email], ) return redirect(reverse('main')) form = ReservationForm() return render( request, 'reservation/reservation.html', { 'seats': seats, 'name': film_name, 'datetime': date_time_start, 'price': price, 'form': form, 'hall': session.hall.name, 'seat_ids': reservation_seat_ids, 'session_id': session_id })
def test_multi_device_conflicting_reservations(self): r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.devices.add(self.d2) r.save() # this reservation has a device whose existing reservation conflicts r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 9, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 11, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d2) self.assertRaises(ValidationError, r.save)
def book(self, start=None, end=None, numero_ospiti=None, servizi_opzionali=[], user=None, session=None): print 'Alloggio book' print 'user:'******'session:', session day_count = end - start notti = day_count.days reservation = Reservation() if user.is_authenticated(): reservation.user = user # if not session.exists(session.session_key): # session.create() # # reservation.session = Session.objects.get(session_key=session.session_key) reservation.alloggio = self reservation.numero_ospiti = numero_ospiti alloggio_quote = self.getAlloggioPrice(notti, numero_ospiti) reservation.price = alloggio_quote['prezzo'] reservation.iva = alloggio_quote['iva'] reservation_event = Event(start=start, end=end, calendar=self.calendar, title='reservation ') reservation_event.save() reservation.event = reservation_event reservation.save() if user.is_authenticated(): reservation.notify_reservation() for service in servizi_opzionali: reservation_service = ReservationService(original_service=service, reservation=reservation) reservation_quote = service.getServicePrice(notti, numero_ospiti) reservation_service.costo = service.costo reservation_service.fattore_tempo = service.fattore_tempo reservation_service.price = reservation_quote['prezzo'] reservation_service.iva = reservation_quote['iva'] reservation_service.save() # reservation.servizi_opzional.add(reservation_service) # reservation.servizi_opzional = servizi_opzionali return reservation
def test_bordering_reservations(self): """ Reservations may begin at the time dependent reservations end """ r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) r.save() # test bordering reservation r = Reservation(user=self.user) r.startTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc) r.endTime = datetime.datetime(2016, 10, 12, 15, 0, 0).replace(tzinfo=utc) r.save() r.devices.add(self.d1) self.assertEqual(Reservation.objects.get(id=1).devices.all()[0], self.d1)