def setUp(self): Booking.objects.bulk_create([ Booking( name='Jennifer Walters', email='*****@*****.**', address='621 S Congress Ave Austin, TX 78701', booking_type=Booking.HOUSEKEEPING, booking_date=date(2019, 6, 24), booking_time=time(1, 2) ), Booking( name='Jane Foster', email='*****@*****.**', address='622 N Lamar Blvd Austin, TX 78751', booking_type=Booking.DOG_WALK, booking_date=date(2019, 6, 29), booking_time=time(3, 9) ), Booking( name='Kamala K.', email='*****@*****.**', address='226 Burnet Rd Austin, TX 78759', booking_type=Booking.DOG_WALK, booking_date=date(2019, 7, 15), booking_time=time(15, 39) ), ])
def post(self, request, *args, **kwargs): post_params = request.POST user = request.user form = PaymentForm(post_params) if form.is_valid(): booking = Booking() booking.customer = request.user.siteuser tour_id = kwargs.get("tour_id") tour = get_object_or_404(DayTour, id=tour_id) booking.tour = tour booking.tourdate = form.cleaned_data['tourdate'] booking.guide = booking.find_guide() booking.save() booking.pay(payment_method=form.cleaned_data['payment_method']) booking.save() booking.match_guide() booking.save() messages.info(self.request, f"{ user.username }, {self.success_message}") return HttpResponseRedirect(self.success_url) else: context = { "form": form, } return render(self.request, self.template_name, context)
def test_optimised_booking(self): """ Ensure that when using optimised, :return: """ form = BookingForm( self.restaurant, { 'restaurant': self.restaurant.pk, 'date': datetime.date.today(), 'time': datetime.time(10), 'length': datetime.timedelta(hours=1), 'party_size': 8 }) self.assertEqual(form.is_valid(), True) tables = form.cleaned_data.pop('table') booking = Booking(**form.cleaned_data) booking.save() booking.table.add(*tables) table = self.restaurant.find_table(datetime.date.today(), datetime.time(10), datetime.timedelta(hours=1), 8, optimise=True) self.assertIsInstance(table, list) self.assertGreater(len(table), 1) self.assertEqual(sum([x.size for x in table]), 8)
def webhook_post(request: HttpRequest): try: assert request.GET['token'] == config.WEBHOOK_TOKEN except Exception: return HttpResponseForbidden() json_text = request.body.decode() j = json.loads(json_text) payload = j['payload'] is_cancelled = False obj = None try: if j['event'] == 'invitee.canceled': is_cancelled = True obj = BookingCalendlyData.objects.get( calendly_uuid=payload['invitee']['uuid']) # if obj does not exist, jump to create new one obj.payload = payload obj.save() elif j['event'] == 'invitee.created': obj = BookingCalendlyData.objects.get( calendly_uuid=payload['invitee']['uuid']) # if exists, raise error return HttpResponse(status=409) else: # Don't know what to do return HttpResponseBadRequest('event not recognized') except KeyError: return HttpResponseBadRequest('data not complete') except BookingCalendlyData.DoesNotExist: try: values = { 'event_type_id': payload['event_type']['uuid'], 'email': payload['invitee']['email'], 'spot_start': payload['event']['invitee_start_time'], 'spot_end': payload['event']['invitee_end_time'], 'booked_at': payload['invitee']['created_at'], } booking = Booking(**values) booking.save() calendly_data = { 'calendly_uuid': payload['invitee']['uuid'], 'payload': payload, 'booking': booking, } obj = BookingCalendlyData(**calendly_data) obj.save() except KeyError: return HttpResponseBadRequest('data not complete') # final if is_cancelled: obj.booking.delete() # cancel # run approval obj.run_approval() return HttpResponse('OK')
def handle(self, *args, **options): # Get all the existing ids all_bookings = Booking.objects.all().values_list('pk', flat=True) # Download the CSV and parse it r = requests.get(CSV_URL) # Force encoding because it's a bitch r.encoding = 'utf-8' bookings = csv.DictReader(r.text.splitlines()) bookings_to_create = [] for booking in bookings: if int(booking['booking_id']) not in all_bookings: new_booking = Booking( booking_id=booking['booking_id'], car=booking['car'], station_name=booking['station'], booking_start=tzaware( booking['booking_time'].split(' - ')[0]), booking_end=tzaware( booking['booking_time'].split(' - ')[1]), used_start=tzaware(booking['used_time'].split(' - ')[0]), used_end=tzaware(booking['used_time'].split(' - ')[1]), distance=match(r'\d+', booking['distance'], 0), max_speed=match(r'\d+', booking['max_speed'], 0), sudden_accel=match(r'\d+', booking['sudden_accel'], 0), sudden_decel=match(r'\d+', booking['sudden_decel'], 0), time_charge=match(r'[\d,]+', booking['time_charge'], '0').replace(',', ''), distance_charge=match(r'[\d,]+', booking['distance_charge'], '0').replace(',', ''), penalty_charge=match(r'[\d,]+', booking['penalty_charge'], '0').replace(',', ''), insurance_charge=match(r'[\d,]+', booking['insurance_charge'], '0').replace(',', ''), discount=match(r'[-\d,]+', booking['discount'], '0').replace(',', ''), total_charge=match(r'[\d,]+', booking['total_charge'], '0').replace(',', ''), ) bookings_to_create.append(new_booking) Booking.objects.bulk_create(bookings_to_create) self.stdout.write( self.style.SUCCESS('Successfully retrieved {} new bookings'.format( len(bookings_to_create))))
def test_non_optimised_booking(self): form = BookingForm( self.restaurant, { 'restaurant': self.restaurant.pk, 'date': datetime.date.today(), 'time': datetime.time(10), 'length': datetime.timedelta(hours=1), 'party_size': 8 }) self.assertEqual(form.is_valid(), True) tables = form.cleaned_data.pop('table') booking = Booking(**form.cleaned_data) booking.save() booking.table.add(*tables) table = self.restaurant.find_table(datetime.date.today(), datetime.time(10), datetime.timedelta(hours=1), 8) self.assertIsNone(table) table = self.restaurant.find_table(datetime.date.today(), datetime.time(10, 30), datetime.timedelta(hours=1), 8) self.assertIsNone(table) table = self.restaurant.find_table(datetime.date.today(), datetime.time(11), datetime.timedelta(hours=1), 8) self.assertIsNone(table) table = self.restaurant.find_table(datetime.date.today(), datetime.time(11, 30), datetime.timedelta(hours=1), 8) self.assertIsInstance(table, list) self.assertEqual(table[0].size, 8)
def bookingsTableSeeder(apps, schema_editor): booking_name = ['Air Asia', 'Hotel Tentrem', 'Dufan'] Booking = apps.get_model('bookings', 'Booking') for i in range(1, 6): for j in range(0, 3): booking = Booking() booking.name = booking_name[j] booking.type = j booking.time_begin = timezone.now() booking.time_end = timezone.now() + datetime.timedelta( days=np.random.randint(0, 2), hours=np.random.randint(0, 23)) if (j != 0): booking.location = faker.address() else: booking.location = 'ID - JP' user = apps.get_model('bookings', 'User').objects.get(id=i) booking.user = user booking.save()
def post(self, request, *args, **kwargs): form = self.form_class(request.POST) interval_id = kwargs['id'] if form.is_valid(): # create booking object date_ = self.request.session['date'] #message_ = form.cleaned_data['message'] user_ = User.objects.get(id=request.user.id) interval_ = Interval.objects.get(id=interval_id) room_ = Room.objects.get(id=interval_.room_id) obj = Booking(user_id=user_.id, interval_id=interval_.id, room_id=room_.id, reservation_date=date_) obj.save() # update status room interval object i = Interval.objects.get(id=interval_id) i.status = 'Booked' i.save() return HttpResponseRedirect('/buildings/' + date_) return render(request, self.template_name, {'form': form})
def create_booking(request, soundman_id): args = {} args.update(csrf(request)) context = {} new_booking = [] soundman = get_object_or_404(User, id=soundman_id) if request.method == "POST": start = request.POST['start'] end = request.POST['end'] try: datetime.strptime(start, '%H:%M') datetime.strptime(end, '%H:%M') except ValueError: return HttpResponse("You are not so smart though") date = __date_for_booking schedule = Schedule.objects.all().filter(soundman=soundman, working_day=date.isoweekday()).first() user = request.user bookings = Booking.objects.all().filter(date=date, schedule=schedule, is_active=1) # Лист всех активных броней на текущую дату new_booking = Booking(user=user, start=start, end=end, is_active=1, date=date, schedule=schedule) flag = False start_time = parse_time(start) deltastart = timedelta(hours=start_time.hour, minutes=start_time.minute) end_time = parse_time(end) deltaend = timedelta(hours=end_time.hour, minutes=end_time.minute) delta = deltaend - deltastart for book in bookings: print(flag) if book.start <= parse_time(start) and book.end >= parse_time(end): flag = True if book.start >= parse_time(start) and book.end <= parse_time(end): flag = True if book.start <= parse_time(start) and book.end <= parse_time(end) and book.end >= parse_time(start): flag = True if book.start >= parse_time(start) and book.end >= parse_time(end) and book.start <= parse_time(end): flag = True if parse_time(start) < schedule.start_of_the_day or parse_time(end) > schedule.end_of_the_day or parse_time( start) > schedule.end_of_the_day or parse_time(end) < schedule.start_of_the_day: # for books in bookings: # ToDo: Надо сделать проверку в цикле времен создаваемой брони с временами активных броней других пользователей context['error'] = "Вы выбрали время, не совпадающее с временем работы звукорежиссера" return render(request, 'bookings/show_calendar.html', context) elif parse_time(start) >= parse_time(end): context['error'] = "Начало записи не может быть больше или равно концу записи" return render(request, 'bookings/show_calendar.html', context) elif flag: context['error'] = "На это время имеются брони" return render(request, 'bookings/show_calendar.html', context) elif delta < timedelta(minutes=30): context['error'] = "Минимальная подолжительность записи 30 минут" return render(request, 'bookings/show_calendar.html', context) else: new_booking.save() context['new_booking'] = new_booking context['duration'] = delta return render(request, 'bookings/show_calendar.html', context)