def test_booking_completed_url_gets_normalized(): # Given product = Product() product.url = 'javascript:alert("plop")' offer = Offer() offer.id = 1 offer.product = product stock = Stock() user = User() user.email = '*****@*****.**' booking = Booking() booking.token = 'ABCDEF' booking.stock = stock booking.stock.offer = offer booking.user = user # When completedUrl = booking.completedUrl # Then assert completedUrl == 'http://javascript:alert("plop")'
def post_add_event(): details = request.json med_id = details['med-id'] # PRELUCRARE DATA si ORA start = details['start'] date = start.split('T') date = date[0] duration = details['duration'] tempsplit = start.split('T')[1] hrs, mins, sec, timezone = tempsplit.split(':') start_time = datetime.time(int(hrs), int(mins)) timedelta = datetime.timedelta(minutes=int(duration)) y, m, d = date.split('-') tmp_datetime = datetime.datetime.combine( datetime.date(int(y), int(m), int(d)), start_time) endtime = (tmp_datetime + timedelta).time() name = details['name'] investigation = details['investigation'] added_by = details['added_by'] phone = details['phone'] email = details['email'] obs = details['obs'] cnp = details['cnp'] start_time = start end_time = date + 'T' + endtime.strftime('%H:%M') + ':00' all_day = details['all_day'] if cnp == '': cnp = None Booking.addbooking(med_id, date, name, investigation, added_by, phone, email, obs, start_time, end_time, all_day, cnp) response = 'ok' return json.dumps(response)
def api_bookings(): """ Creates the booking for user on selected hotel; Returns the list of bookings for the user. """ if request.method == "POST": errors = {} if not request.json: abort(400) # Validate required fields. for field in [ "hotel_id", "check_in", "check_out", "room_preference", "smoking_preference", "credit_card_number", "credit_card_name", "credit_card_expiry", ]: if not request.json.get(field): errors[field] = "This field is required" # Validate field value if not ("hotel_id" not in errors and Hotel.query.filter_by(id=request.json["hotel_id"])): errors["hotel_id"] = "No hotels found with the given id" if not ("check_in" not in errors and validate_date(request.json["check_in"])): errors["check_in"] = "Incorrect data format, should be YYYY-MM-DD" if not ("check_out" not in errors and validate_date(request.json["check_out"])): errors["check_out"] = "Incorrect data format, should be YYYY-MM-DD" if not ("credit_card_expiry" not in errors and validate_date(request.json["credit_card_expiry"])): errors["credit_card_expiry"] = "Incorrect data format, should be YYYY-MM-DD" if not ("room_preference" not in errors and request.json["room_preference"] in ["1", "2", "3"]): errors["room_preference"] = "Select a value between 1 to 3" if not ("smoking_preference" not in errors and isinstance(request.json["smoking_preference"], bool)): errors["smoking_preference"] = "Value should be either true or false" if not ("credit_card_number" not in errors and validate_credit_card_number(request.json["credit_card_number"])): errors["credit_card_number"] = "Invalid credit card number" if errors: return make_response(jsonify({"error": errors}), 400) booking = Booking( request.json["check_in"], request.json["check_out"], request.json["hotel_id"], request.json["room_preference"], request.json["smoking_preference"], request.json["credit_card_number"], request.json["credit_card_name"], request.json["credit_card_expiry"], request.json["user_id"], ) booking.add(booking) return make_response(jsonify({"booking_id": booking.id}), 201) else: token = request.headers["Authorization"] user = User.verify_auth_token(token) bookings = Booking.query.filter_by(user_id=user.id).all() return json.dumps(Booking.serialize_list(bookings))
def getBookings(self, params=None): bookings = [] # with no optional params all bookings can be fetched if not params: bookingTuples = db.getAllObjects('bookings') # otherwise only bookings matching the params may be fetched else: for param in params: if param not in Booking.attributesAsList(): return jsonify({'bookings': []}) # obtain booking history for user_id param bookingTuples = db.getObjectsByFilter('bookings', list(params.keys()), list(params.values())) # construct the fetched bookings as objects for i in range(len(bookingTuples)): bookings.append( Booking(bookingTuples[i][0], bookingTuples[i][1], bookingTuples[i][2], self.__getUser(bookingTuples[i][3]), self.__getCar(bookingTuples[i][4]), bookingTuples[i][5])) # jsonify each booking object's dict return jsonify(bookings=[booking.asDict() for booking in bookings])
def book_course(request, name): s = Session.objects.get(session_key=request.session["auth_token"]) user = User.objects.get(login=s.get_decoded()['login']) course = Course.objects.get(name=name) cost = course.price * course.discount book = Booking(user=user, course=course, cost=cost) book.save() return HttpResponse('Course booked successful')
def get(self, obj_id=None): """ Gets booking(s). Returns all bookings if no obj_id is passed --- tags: - bookings parameters: - in: path name: obj_id definitions: - schema: id: Booking required: - customerID - room_number optional: - is_active properties: customerID: type: string description: the customer's id room_number: type: integer description: the room's number is_booked: type: boolean description: the room's booking status responses: 200: description: Returns the specified booking or a list of bookings $ref: '#/definitions/Booking' """ if not obj_id: query = Booking.query().fetch() output = self.output_fields output.update(self.resource_fields) resp = { 'results': marshal(query, output), 'count': len(query) } return resp, 200 try: booking = Booking.get_by_id(int(obj_id)) if not booking: abort(404, message="Booking with key ({}) not found".format(obj_id)) output = self.output_fields output.update(self.resource_fields) return marshal(booking, output), 200 except Exception: abort(404, message="Booking with key ({}) not found".format(obj_id))
def block_days(): if request.method == 'POST': med_id = request.form['med_id'] start = request.form['start'] date = start end = request.form['end'] start = start + 'T00:01:00' end = end + 'T00:00:00' Booking.block(med_id, start, end, date) return url_for('index', message='Perioada blocata cu succes!')
def updateBooking(self, id, fieldsToUpdate, params): # update the booking with the specified id, indicating which fields to update and what to update them to db.updateObject('bookings', id, fieldsToUpdate, params) # retrieve the newly updated booking and create an object from it's data bookingTuple = db.getObjectById('bookings', id)[0] booking = Booking(bookingTuple[0], bookingTuple[1], bookingTuple[2], self.__getUser(bookingTuple[3]), self.__getCar(bookingTuple[4]), bookingTuple[5]) # jsonify the booking to confirm the update return jsonify({'booking': booking.asDict()})
def test_raises_api_error_when_offerer_cancellation_and_used_booking(self): # Given booking = Booking() booking.isUsed = True # When with pytest.raises(ApiErrors) as e: check_booking_is_cancellable(booking, is_user_cancellation=False) # Then assert e.value.errors['booking'] == ["Impossible d\'annuler une réservation consommée"]
def addBooking(_, info, vehicle_id, booking_price, start_time, end_time): newbooking = Booking( booking_price=booking_price, start_time=datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S'), end_time=datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S') ) newbooking.save() vehicle = Vehicle.objects(id=vehicle_id).first() vehicle.booking.append(newbooking) vehicle.save() return vehicle
def test_is_cancelled_label_when_booking_is_cancelled(self): # Given booking = Booking() booking.stock = Stock() booking.isCancelled = True # When statusLabel = booking.statusLabel # Then assert statusLabel == "Réservation annulée"
def test_is_countermak_validated_label_when_booking_is_used(self): # Given booking = Booking() booking.stock = Stock() booking.isUsed = True # When statusLabel = booking.statusLabel # Then assert statusLabel == 'Contremarque validée'
def createBooking(self, params): # fetch the user and car corresponding to the user_id and car_id in the request body user = self.__getUser(params[3]) car = self.__getCar(params[4]) # construct a booking object from the gathered data booking = Booking(params[0], params[1], params[2], user, car, params[5]) # update the database with the new booking and respond with a confirmation of insertion db.insertObject('bookings', Booking.attributesAsList(), booking.asTuple()) return jsonify({'booking': booking.asDict()}), 201
def test_validated_label_when_event_is_expired(self): # Given booking = Booking() booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta(-1) # When statusLabel = booking.statusLabel # Then assert statusLabel == 'Validé'
def create_booking_for(user: User, stock: Stock, token: str) -> Booking: booking = Booking() booking.stock = stock booking.user = user booking.quantity = 1 booking.amount = 0 booking.dateCreated = datetime.utcnow() booking.isCancelled = False booking.isUsed = False booking.token = token return booking
def test_raises_resource_gone_error_if_is_used(self): # Given booking = Booking() booking.isUsed = True booking.stock = Stock() # When with pytest.raises(ResourceGoneError) as e: check_booking_is_usable(booking) assert e.value.errors['booking'] == [ 'Cette réservation a déjà été validée']
def test_booking_on_thing_is_cancellable(self): # Given booking = Booking() booking.stock = Stock() booking.stock.offer = Offer() booking.stock.offer.product = create_product_with_thing_type() # When is_cancellable = booking.isUserCancellable # Then assert is_cancellable == True
def test_does_not_raise_api_error_when_user_cancellation_and_event_in_more_than_72h(self): # Given booking = Booking() booking.isUsed = False booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta(hours=73) # When check_output = check_booking_is_cancellable(booking, is_user_cancellation=False) # Then assert check_output is None
def test_it_returns_an_empty_list_if_everything_has_a_cost(self): # given reimbursement1 = BookingReimbursement( Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(0)) reimbursement2 = BookingReimbursement( Booking(), ReimbursementRules.PHYSICAL_OFFERS, Decimal(0)) # when bookings_reimbursements_with_cost = filter_out_bookings_without_cost( [reimbursement1, reimbursement2]) # then assert bookings_reimbursements_with_cost == []
def test_booking_on_event_is_not_cancellable_if_begining_date_time_before_72_hours( self): # Given booking = Booking() booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta( hours=71) # When is_cancellable = booking.isUserCancellable # Then assert is_cancellable == False
def test_booking_on_event_with_begining_date_in_more_than_72_hours_is_cancellable( self): # Given booking = Booking() booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta( hours=73) # When is_cancellable = booking.isUserCancellable # Then assert is_cancellable
def test_does_not_raise_api_error_when_offerer_cancellation_not_used_and_thing(self): # Given booking = Booking() booking.isUsed = False booking.stock = Stock() booking.stock.offer = Offer() booking.stock.offer.product = create_product_with_thing_type() # When check_output = check_booking_is_cancellable(booking, is_user_cancellation=False) # Then assert check_output is None
def test_raises_api_error_when_user_cancellation_and_event_in_less_than_72h(self): # Given booking = Booking() booking.isUsed = False booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta(hours=71) # When with pytest.raises(ApiErrors) as e: check_booking_is_cancellable(booking, is_user_cancellation=True) # Then assert e.value.errors['booking'] == [ "Impossible d\'annuler une réservation moins de 72h avant le début de l'évènement"]
def test_does_not_raise_error_if_not_cancelled_nor_used_and_no_beginning_datetime(self): # Given booking = Booking() booking.isUsed = False booking.isCancelled = False booking.stock = Stock() booking.stock.beginningDatetime = None # When try: check_booking_is_usable(booking) except ApiErrors: pytest.fail( 'Bookings which are not used nor cancelled and do not have a beginning datetime should be usable')
def test_raises_resource_gone_error_if_stock_beginning_datetime_in_more_than_72_hours(self): # Given in_four_days = datetime.utcnow() + timedelta(days=4) booking = Booking() booking.isUsed = False booking.isCancelled = False booking.stock = Stock() booking.stock.beginningDatetime = in_four_days # When with pytest.raises(ForbiddenError) as e: check_booking_is_usable(booking) assert e.value.errors['beginningDatetime'] == [ 'Vous ne pouvez pas valider cette contremarque plus de 72h avant le début de l\'évènement']
def init_db(): booking1 = Booking( booking_price=66.6, start_time=datetime(2020, 3, 1, 0, 0 ,0), end_time=datetime(2020, 3, 4, 0, 0 ,0) ) booking1.save() booking2 = Booking( booking_price=55.5, start_time=datetime(2020, 3, 5, 0, 0 ,0), end_time=datetime(2020, 3, 7, 0, 0 ,0) ) booking2.save() vehicle1 = Vehicle( type="small car", make="Honda", model="Civic R", year=2020, registration_tag="A12345", current_mileage=123.12, condition="like new", capacity=4, is_available=True, booking=[booking1, booking2] ) vehicle1.save()
def book_tickets(request): if request.method == 'POST': form = BookTicketsForm(request.POST) if form.is_valid(): booking = Booking() booking.scheduled_show = form.cleaned_data['show'] booking.name = form.cleaned_data['name'] booking.email = form.cleaned_data['email'] booking.number_of_tickets = form.cleaned_data['number_of_tickets'] # send_mail( # subject=u'Rezervace: %s' % booking.scheduled_show, # message=BOOKING_ADMIN_MAIL % form.cleaned_data, # from_email='*****@*****.**', # recipient_list=[BOOKING_ADMIN_EMAIL], # fail_silently=False # ) send_mail(subject=u'Rezervace: %s' % booking.scheduled_show, message=BOOKING_USER_MAIL % form.cleaned_data, from_email='*****@*****.**', recipient_list=[booking.email], fail_silently=False) booking.save() messages.success( request, u'Děkujeme. Potvrzení bylo odesláno na váš email.') form = BookTicketsForm() else: form = BookTicketsForm() return render_to_response('booking/base.html', { 'book_tickets_form': form, }, context_instance=RequestContext(request))
def test_value_error_is_raised_if_payments_ids_do_not_match_payments(self): # given payments = [ create_payment(Booking(), Offerer(), 10, idx=111), create_payment(Booking(), Offerer(), 10, idx=222) ] ids_to_ban = [222, 333] # when with pytest.raises(UnmatchedPayments) as e: apply_banishment(payments, ids_to_ban) # then assert e.value.payment_ids == {333}
def api_bookings(): """ Creates the booking for user on selected hotel; Returns the list of bookings for the user. """ if request.method == 'POST': errors = {} if not request.json: abort(400) # Validate required fields. for field in ['hotel_id', 'check_in', 'check_out', 'room_preference', 'smoking_preference', 'credit_card_number', 'credit_card_name', 'credit_card_expiry']: if not request.json.get(field): errors[field] = 'This field is required' # Validate field value if not ('hotel_id' not in errors and Hotel.query.filter_by(id=request.json['hotel_id'])): errors['hotel_id'] = 'No hotels found with the given id' if not ('check_in' not in errors and validate_date(request.json['check_in'])): errors['check_in'] = 'Incorrect data format, should be YYYY-MM-DD' if not ('check_out' not in errors and validate_date(request.json['check_out'])): errors['check_out'] = 'Incorrect data format, should be YYYY-MM-DD' if not ('credit_card_expiry' not in errors and validate_date(request.json['credit_card_expiry'])): errors['credit_card_expiry'] = 'Incorrect data format, should be YYYY-MM-DD' if not ('room_preference' not in errors and request.json['room_preference'] in ["1", "2", "3"]): errors['room_preference'] = 'Select a value between 1 to 3' if not ('smoking_preference' not in errors and isinstance(request.json['smoking_preference'], bool)): errors['smoking_preference'] = 'Value should be either true or false' if not ('credit_card_number' not in errors and validate_credit_card_number(request.json['credit_card_number'])): errors['credit_card_number'] = 'Invalid credit card number' if errors: return make_response(jsonify({'error': errors}), 400) booking = Booking(request.json['check_in'], request.json['check_out'], request.json['hotel_id'], request.json['room_preference'], request.json['smoking_preference'], request.json['credit_card_number'], request.json['credit_card_name'], request.json['credit_card_expiry'], request.json['user_id']) booking.add(booking) return make_response(jsonify({'booking_id': booking.id}), 201) else: token = request.headers['Authorization'] user = User.verify_auth_token(token) bookings = Booking.query.filter_by(user_id=user.id).all() return json.dumps(Booking.serialize_list(bookings))
def test_no_payments_are_returned_if_no_ids_are_provided(self): # given payments = [ create_payment(Booking(), Offerer(), 10, idx=111), create_payment(Booking(), Offerer(), 10, idx=222) ] ids_to_ban = [] # when banned_payments, retry_payments = apply_banishment( payments, ids_to_ban) # then assert banned_payments == [] assert retry_payments == []
def test_no_payments_to_retry_if_all_are_banned(self): # given payments = [ create_payment(Booking(), Offerer(), 10, idx=111), create_payment(Booking(), Offerer(), 10, idx=222) ] ids_to_ban = [111, 222] # when banned_payments, retry_payments = apply_banishment( payments, ids_to_ban) # then assert len(banned_payments) == 2 assert retry_payments == []
def test_does_not_raise_error_if_not_cancelled_nor_used_and_beginning_datetime_in_less_than_72_hours(self): # Given in_two_days = datetime.utcnow() + timedelta(days=2) booking = Booking() booking.isUsed = False booking.isCancelled = False booking.stock = Stock() booking.stock.beginningDatetime = in_two_days # When try: check_booking_is_usable(booking) except ApiErrors: pytest.fail( 'Bookings which are not used nor cancelled and do not have a beginning datetime should be usable')
def bookings(): user = current_user if user.is_active and not user.is_anonymous and user.auth_type == 'gafe': bookings = Booking.getBookingsForResource(user) return render_template('user-bookings.html', bookings=bookings) flash('Access denied. Please log in via Google Apps.', 'error') return redirect(url_for('index'))
def book_tickets(request): if request.method == 'POST': form = BookTicketsForm(request.POST) if form.is_valid(): booking = Booking() booking.scheduled_show = form.cleaned_data['show'] booking.name = form.cleaned_data['name'] booking.email = form.cleaned_data['email'] booking.number_of_tickets = form.cleaned_data['number_of_tickets'] # send_mail( # subject=u'Rezervace: %s' % booking.scheduled_show, # message=BOOKING_ADMIN_MAIL % form.cleaned_data, # from_email='*****@*****.**', # recipient_list=[BOOKING_ADMIN_EMAIL], # fail_silently=False # ) send_mail( subject=u'Rezervace: %s' % booking.scheduled_show, message=BOOKING_USER_MAIL % form.cleaned_data, from_email='*****@*****.**', recipient_list=[booking.email], fail_silently=False ) booking.save() messages.success(request, u'Děkujeme. Potvrzení bylo odesláno na váš email.') form = BookTicketsForm() else: form = BookTicketsForm() return render_to_response('booking/base.html', { 'book_tickets_form': form, }, context_instance=RequestContext(request))
def save(self, request): check_in = request.COOKIES.get("check_in") check_in = datetime.strptime(check_in, "%Y-%m-%d").date() check_out = request.COOKIES.get("check_out") check_out = datetime.strptime(check_out, "%Y-%m-%d").date() hotel_id = int(request.COOKIES.get("hotel_id")) room_type = int(request.COOKIES.get("room_type")) room_num = int(request.COOKIES.get("room_num")) booking = Booking() booking.hotel_id = hotel_id booking.room_type = room_type booking.check_in = check_in booking.check_out = check_out booking.room_num = room_num guest = Guest() guest.firstname = request.GET["firstname"] guest.lastname = request.GET["lastname"] guest.phone = request.GET["phone"] guest.save() booking.guest = guest booking.save()
def booking(uid, date_str, time_str): resource = User.getByUrlsafeId(uid) tz = resource.getTimezoneObject() duration = resource.prefs.duration dt_str = '%s %s' % (date_str, time_str.replace('-', ':', 1)) dt_start = tz.localize(date_parser.parse(dt_str)) dt_end = dt_start + timedelta(minutes=duration) form = BookingForm(start_time=dt_start, end_time=dt_end, timezone=tz.zone) if request.method == 'POST': if form.validate_on_submit(): booking = Booking.createFromPost(resource, form.data) flash('Your booking succeeded.', 'info') return redirect(url_for('calendar', uid=uid, date_str=date_str)) else: flash_form_errors('Your booking failed.', form) return render_template('booking-new.html', uid=uid, date_str=date_str, time_str=time_str, form=form, resource=resource, dt_start=dt_start, tz=tz, duration=duration)
def reminders(token=None): if token: email = RemindersToken.validateToken(token) if email: bookings = Booking.getBookingsForAttendeeEmail(email) return render_template('attendee-bookings.html', email=email, bookings=bookings) else: flash('Token invalid or expired', 'error') form = RemindersForm() if request.method == 'POST': if form.validate_on_submit(): RemindersToken.createAndSendToken(form.email.data, url_for('reminders', _external=True), app.config) flash('Please check your email inbox for a message', 'info') return redirect(url_for('index')) return render_template('reminders.html', form=form)
def addBooking(request): if request.method == "POST": f = BookingForm(request.POST, initial={'booker':request.user, 'room':0}) if f.is_valid(): first_booking = 0 #relatedBookings = [] submittedBookings = [] for room in f.cleaned_data['room']: newBooking = Booking(name=f.cleaned_data['name'], notes=f.cleaned_data['notes'], date=f.cleaned_data['date'], start=f.cleaned_data['start'], end=f.cleaned_data['end'], booker=get_object_or_404(User, pk=request.user.id), approved=False, category=get_object_or_404(BookingCategory, pk=request.POST['category']), room=get_object_or_404(Room, pk=room.pk)) #auto-approve if admin if request.user.is_staff: newBooking.approved = True newBooking.save() if first_booking == 0: first_booking = newBooking submittedBookings.append(newBooking) #relatedBookings.append([newBooking]) if (f.cleaned_data['repeat']): # repeat is specified curr_date = f.cleaned_data['date'] ''' Timestep will be the increment for the repeat ''' if f.cleaned_data['repeat_frequency_unit'] == 'day': timestep = datetime.timedelta(days=f.cleaned_data['repeat_frequency']) elif f.cleaned_data['repeat_frequency_unit'] == 'week': timestep = datetime.timedelta(weeks=f.cleaned_data['repeat_frequency']) elif f.cleaned_data['repeat_frequency_unit'] == 'month': timestep = datetime.timedelta(weeks=4 * f.cleaned_data['repeat_frequency']) while curr_date + timestep <= f.cleaned_data['repeat_end'] and timestep: curr_date += timestep ''' TODO: check if this booking conflicts with any others ''' repeatBooking = Booking(name=f.cleaned_data['name'], notes=f.cleaned_data['notes'], date=curr_date, start=f.cleaned_data['start'], end=f.cleaned_data['end'], booker=get_object_or_404(User, pk=request.user.id), approved=False, category=get_object_or_404(BookingCategory, pk=request.POST['category']), room=get_object_or_404(Room, pk=room.pk)) if request.user.is_staff: repeatBooking.approved = True repeatBooking.save() submittedBookings.append(repeatBooking) RepeatBooking(source=newBooking, target=repeatBooking).save() # relatedBookings[-1].append(repeatBooking) # #if len(relatedBookings[0]) > 1: # for i in range(0, len(relatedBookings)): # for j in range(1, len(relatedBookings[i])): # if not relatedBookings[i][j] is None: # RepeatBooking(source=relatedBookings[i][0], target=relatedBookings[i][j]).save() #if len(relatedBookings) > 1: # for j in range(0, len(relatedBookings[0])): # for i in range(1, len(relatedBookings)): # if not relatedBookings[i][j] is None: # MultiRoomBooking(source=relatedBookings[0][j], target=relatedBookings[i][j]).save() # notify all admins of booking request, dont send if admin makes a booking admins = User.objects.filter(is_staff=True) subject = "East Scarborough Storefront - Booking Request" message = request.user.username + " has requested a booking.\n\nBooking info:\nName: " + newBooking.name + "\nNotes: " + newBooking.notes + "\nDate: " + str(newBooking.date) +"\nTime: " + str(newBooking.start) + " - " + str(newBooking.end) + "\nCategory: " + newBooking.category.name + "\nRoom: " + newBooking.room.name if newBooking.booker.is_staff == False: for a in admins: a.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) return render(request, 'juakstore/booking_add.html', {'form':BookingForm(), 'all_bookings':Booking.objects.all().filter(approved=True), 'year': datetime.datetime.now().year, 'month': datetime.datetime.now().month, 'day': datetime.datetime.now().day, 'submittedBookings': submittedBookings, }) else: return render(request, 'juakstore/booking_add.html', {'form': f, 'all_bookings':Booking.objects.all().filter(approved=True), 'year': datetime.datetime.now().year, 'month': datetime.datetime.now().month, 'day': datetime.datetime.now().day, }) else: return HttpResponseRedirect(reverse('juakstore:bookingCreate'))
def mod_booking(request): errors = [] if request.method == 'POST': title = request.POST.get('title', '') start = request.POST.get('start', '') until = request.POST.get('until', '') location = request.POST.get('location', '') more = request.POST.get('more', '') id = request.POST.get('id', '') if not title: errors.append('Give a name for the time booking') if not start: errors.append('Enter a start date') elif not valid_date(start): errors.append('Enter a valid start date') start = '' if not until: errors.append('Enter an end date') elif not valid_date(until): errors.append('Enter a valid end date') until = '' if start and until: start_date = uk_str_to_date(start) until_date = uk_str_to_date(until) if start_date > until_date: errors.append('Start date is after the end date') if not errors: if id == '': b = Booking() else: b = Booking.objects.get(id=int(id)) b.start=start_date b.end=until_date b.name=title b.location=location b.more=more b.profile=request.user.get_profile() b.save() request.user.get_profile().save() # return HttpResponseRedirect("/users/" + request.user.username) return HttpResponseRedirect("/booking/id/" + str(b.id) + "/") else: id_param = request.GET.get('id', '') # If true, is a create rather than update call if id_param == '': title = '' start = '' until = '' more = '' location = '' id = '' else: try: booking = request.user.get_profile().booking_set.get(id=id_param) except: return HttpResponseNotFound("Booking does not correspond to this user") title = booking.name start = booking.start until = booking.end more = booking.more location = booking.location id = id_param return render_to_response('booking/book_time.html', { 'errors' : errors, 'title' : title, 'start' : start, 'until' : until, 'more' : more, 'location': location, 'id' : id, 'all_tags': Tag.objects.all() }, RequestContext(request) )