def make_reservation(restaurant, guest, reservation_date_time, number_of_people, walkin, reminder, minutes_slot=120): # funksjon som bruker get_next_available_table for å reservere et ledig bord på et ledig tidspunkt # print("NUMBER OF PEOPLE:", number_of_people) # reservation_date_time = pytz.utc.localize(reservation_date_time) table = get_next_available_table(restaurant, reservation_date_time, number_of_people, minutes_slot) print("TABLE:", table) if table: delta = timedelta(seconds=60 * minutes_slot) reservation = Reservation(guest=guest, reminder=reminder, number_of_people=number_of_people, start_date_time=reservation_date_time, end_date_time=reservation_date_time + delta, created_date=datetime.now(), table=table, walkin=walkin) reservation.save() return {'reservation': reservation.id, 'table': table.id} else: return None
def reservation_date(request, room_id): room = Room.objects.get(id=room_id) if request.is_ajax(): if request.method == 'GET': date_range_invalid = [] min_date = room.calender.date_range.split(' - ')[0] max_date = room.calender.date_range.split(' - ')[1] try: reservations = room.reservation_set.all() for reservation in reservations: date_range_invalid.append(reservation.date_range) except Reservation.DoesNotExist: date_range_invalid = [] reservation = { 'min_date': min_date, 'max_date': max_date, 'date_range_invalid': date_range_invalid, 'price': room.price.price } return JsonResponse(reservation) if request.method == 'POST': total = request.POST['total'] date_range = request.POST['date_range'] reservation = Reservation(room=room, guest=request.user, total=total, date_range=date_range, price=room.price.price) reservation.save() messages.add_message(request, messages.SUCCESS, 'Book successfully!') print('success') return JsonResponse({'ok': 200})
class ModelTestCase(TestCase): """This class defines the test suite for the reservation model.""" def setUp(self): self.reservation = Reservation(**test_reservation_dict) def test_model_can_create_a_reservation(self): """Test the reservation model can create a reservation.""" old_count = Reservation.objects.count() self.reservation.save() new_count = Reservation.objects.count() self.assertNotEqual(old_count, new_count)
def test_store_and_retrive_reservation(self): first_reservation = Reservation() first_reservation.name = "first" first_reservation.save() second_reservation = Reservation() second_reservation.name = "second" second_reservation.save() saved_reservations = Reservation.objects.all() self.assertEqual(2, len(saved_reservations)) self.assertEqual("first", saved_reservations[0].name) self.assertEqual("second", saved_reservations[1].name)
def __save_new_reservation(form_cleaned_data): reservation = Reservation() reservation.name = form_cleaned_data['name'] reservation.date = form_cleaned_data['date'] reservation.table = form_cleaned_data['table'] reservation.telephone = form_cleaned_data['telephone'] reservation.save()
def __there_is_a_reservation(self, name, date=None, table=None, phone=None): reservation = Reservation() reservation.name = name reservation.date = date reservation.table = table reservation.telephone = phone reservation.save()
def process_formset(self, formset): """ Process the formset of the shopping cart. All interaction with the database is wrapped in a transaction. If there is an error while processing the formset the whole transaction is rolled back and no reservations are created. """ commit = True user=self.request.user pid_list = self.request.session.get('cart') if not pid_list: return False product_list = Product.objects.filter(id__in=pid_list) # Create a reservation for every timeframe and reservation entries # for all the products. for form in formset: start_date=form.cleaned_data.get('start_date') end_date=form.cleaned_data.get('end_date') # Empty form; process next if not (start_date and end_date): continue try: reservation = Reservation(user=user, start_date=start_date, end_date=end_date) reservation.clean() reservation.save() for product in product_list: # Make sure there is no resevation entry for the product # in the given timeframe. # We can't use the models clean() method here since we # are inside a transaction. collision = ReservationEntry.objects.filter( product=product, reservation__state=1).exclude( reservation__end_date__lt=start_date).exclude( reservation__start_date__gt=end_date).count() if collision > 0: raise ValidationError( _("There is already a reservation for %s " "product in this timeframe.") % product) e = ReservationEntry(reservation=reservation, product=product) e.save() except ValidationError, e: # Add the error message to the form, so that we can display # the error to the user. form.invalidate_form(e.messages) commit = False
def test_delete_reservation(self): first_reservation = Reservation() first_reservation.name = "first" first_reservation.save() second_reservation = Reservation() second_reservation.name = "second" second_reservation.save() reservation_to_be_deleted = Reservation.objects.get( id=first_reservation.id) reservation_to_be_deleted.delete() saved_reservations = Reservation.objects.all() self.assertEqual(1, len(saved_reservations)) self.assertEqual("second", saved_reservations[0].name)
def _get_reserved_days_as_strings(self): reservables = self._get_reservables() reserved_days = {} for reservable in reservables: days = Reservation.get_reserved_days_for_period(self.start_date, self.end_date, reservable) day_list = [] for day in days: day_list.append("%s" % day.strftime("%Y-%m-%d")) reserved_days[reservable.product.sku.replace("-", "_")] = day_list return reserved_days or {}
def test_start_date_should_be_before_end_date(self): reservation = Reservation( first_name='Greg', last_name='Greggie', room_number='28', start_date=timezone.now().date(), end_date=(timezone.now() - timezone.timedelta(minutes=1)).date()) serializer = ReservationSerializer(instance=reservation) serializer = ReservationSerializer(data=serializer.data) self.assertFalse(serializer.is_valid()) self.assertIn('end_date', serializer.errors)
def test_get_reserved_dates_for_period_returns_correct_dates__spanning_months(self): ReservationFactory( reservable=self.reservable, start_time=datetime.datetime(year=2015, month=6, day=30, hour=15), end_time=datetime.datetime(year=2015, month=8, day=5, hour=12) ) dates = Reservation.get_reserved_days_for_period( start_date=datetime.date(year=2015, month=7, day=15), end_date=datetime.date(year=2015, month=7, day=20) ) self.assertEquals(len(dates), 6)
def post(self, request, doc_id): form = self.form_class(request.POST) if form.is_valid(): doctor = Doctor.objects.get(pk=doc_id) reservation = Reservation() reservation.client = request.user reservation.doctor = doctor reservation.time = form.cleaned_data['time'] reservation.date = form.cleaned_data['date'] reservation.save() return HttpResponseRedirect('/reservations/') return render(request, 'reservation.html', {'form': form})
def reserve_view(request, menu_dish_id): """ Generate a new reservation of menu. """ menu_dish = MenuDishes.objects.get(pk=menu_dish_id) form = MenuFormReservation() if request.method == 'POST': form = MenuFormReservation(request.POST) if form.is_valid(): new_reservation = Reservation( user=request.user, menu_dish=menu_dish, date=timezone.now(), observations=form.cleaned_data['observations']) new_reservation.save() return HttpResponseRedirect(reverse('reservations:menu_list')) return render(request, 'reservations/user/confirm_reservation.html', context={ 'menu_dish': menu_dish, 'form': form })
def update_reservations(self): logger.info("Starting update reservations") recent_reservations = self.reservations_retriever.retrieve_recent_reservations() dest_list = [ Destination(place=r.destination) for r in recent_reservations ] created_destinations = self.destination_manager.bulk_destinations(dest_list) dict_destinations = {d.place: d for d in created_destinations} reservations_list = [ Reservation(destination=dict_destinations[r.destination], date=r.date, external_id=r.reservation_id) for r in recent_reservations ] created_objs = self.reservation_manager.bulk_reservations(reservations_list) logger.info("Update process finished") return len(recent_reservations) is not 0, created_objs
def test_get_reserved_dates_for_period_returns_correct_dates(self): self.reservable2 = ReservableProductFactory() ReservationFactory( reservable=self.reservable, start_time=datetime.datetime(year=2015, month=6, day=30, hour=15), end_time=datetime.datetime(year=2015, month=7, day=5, hour=12) ) ReservationFactory( reservable=self.reservable2, start_time=datetime.datetime(year=2015, month=7, day=10, hour=12), end_time=datetime.datetime(year=2015, month=7, day=15, hour=12) ) dates = Reservation.get_reserved_days_for_period( start_date=datetime.date(year=2015, month=6, day=30), end_date=datetime.date(year=2015, month=7, day=15) ) self.assertEquals(len(dates), 10)
def setUp(self): self.reservation = Reservation(**test_reservation_dict)
def view(request, slot_id): if request.method != 'POST': slot = Slot.objects.get(pk=slot_id) return render(request, 'reserve.html', {'slot': slot}) content = request.body.decode() try: data = json.loads(content) except ValueError as e: json_response = {'error_message': 'invalid json'} print(e, json_response) return HttpResponse(json.dumps(json_response), status=400) #400 bad request try: start = datetime.strptime(data['start_time'], '%Y-%m-%dT%H:%M') end = datetime.strptime(data['end_time'], '%Y-%m-%dT%H:%M') except ValueError as e: json_response = {'error_message': 'invalid time format'} pritn(e, json_response) return HttpResponse(json.dumps(json_response), status=400) #400 bad request now = datetime.now() if now >= start: response_json = { 'error_message': 'invalid input; start time must be set for later' } return HttpResponse(json.dumps(response_json), status=400) if start >= end: response_json = { 'error_message': 'invalid input; start time must be smaller than end time' } return HttpResponse(json.dumps(response_json), status=400) try: reserved_slot = Slot.objects.get(pk=int(data['slot_id'])) except Slot.DoesNotExist as e: json_response = {'error_message': 'slot does not exist'} print(e, json_response) return HttpResponse(json.dumps(response_json), status=400) #400 bad request if reserved_slot.disabled: json_response = {'error_message': 'slot is disabled'} print(json_response) return HttpResponse(json.dumps(response_json), status=403) #403 forbidden reservations = Reservation.objects.filter(expired=False, slot=reserved_slot) now = datetime.now() for r in reservations: if now >= r.end_time: r.expired = True r.save() continue if (start >= r.start_time and start <= r.end_time) or (end >= r.start_time and end <= r.end_time): response_json = { 'error_message': 'this time has been taken, please choose another time' } return HttpResponse(json.dumps(response_json)) claims = { 'Building': reserved_slot.segment.floor.building.label, 'Floor': reserved_slot.segment.floor.label, 'Segment': reserved_slot.segment.label, 'Slot': reserved_slot.label, 'start': data['start_time'], 'end': data['end_time'], } token = jwt.encode(claims, SECRET_KEY).decode() reservation = Reservation(user=request.user, slot=reserved_slot, start_time=start, end_time=end, jwt_token=token) reservation.save() response_json = { 'redirect_url': reverse('front_view:building', args=[reserved_slot.segment.floor.building.id]), 'jwt_token': token, } return HttpResponse(json.dumps(response_json), status=201) #201 created
def _test_field_cannot_be_empty(self, field_name): reservation = Reservation() with self.assertRaises(ValidationError): Reservation._meta.get_field(field_name).clean(getattr(reservation, field_name), reservation)