Exemplo n.º 1
0
def new(request):
    user = request.user
    if request.method == 'POST':
        print ("Post")
        form = ReservationForm(request.POST)
        if form.is_valid():
            reservation=form.save(commit=False)
            reservation.user=user
            reservation.save()
            #jump to payment processing
            redirect_url = reverse('reservation_payment',kwargs={'reservation_id':reservation.id})
            return HttpResponseRedirect(redirect_url)
        else:
            data = {
                'user': user,
                'form': form,
            }
            return render(request, 'reservations/new.html', data)

    else:
        reservation=Reservation()
        reservation.user=user
        form = ReservationForm(instance=reservation)
        data = {
            'user': user,
            'form': form,
        }
        return render_to_response('reservations/new.html', data, context_instance=RequestContext(request))
Exemplo n.º 2
0
def make_reservation():
    """
    make a reservation
    """
    user_id = current_user.id
    form = ReservationForm()
    rid = None
    if form.validate_on_submit():
        res_datetime = None
        reservation_obj = Reservation(
            user_id=user_id,
            num_of_customer=form.num_of_customers.data,
            res_datetime=form.reservation_dateTime.data.strftime(
                '%Y-%m-%d %H:%M'),
            special_desc=form.special_desc.data)

        try:
            # add reservation_obj to the database, default status = 0; 1 for created (confirmed by user)
            db.session.add(reservation_obj)
            db.session.commit()
            # r = Reservation.query.filter(and_(Reservation.user == user_id,
            #                                   Reservation.res_datetime == res_datetime)).first()
            # rid=r.id
            flash('You have submitted a reservation request.')
        except:
            #
            flash('Error: unknown!')
        session['rid'] = rid
        # redirect to reservation confirmation page
        return redirect(url_for('reservation.confirm_reservation'))

    # load reservation template
    return render_template('reservation/reservation.html',
                           form=form,
                           title="Make a Reservation")
Exemplo n.º 3
0
def edit(request, reservation_id=None):
    Reservation.cancel_pending_reservations(user=request.user)
    user = request.user
    if reservation_id != None:
        reservation=get_object_or_404(Reservation,pk=reservation_id)
        if reservation.user !=user or reservation.is_cancelled():
            return HttpResponseForbidden()
        edit=True
    else:
        reservation=Reservation()
        reservation.user=user
        edit=False
    form = ReservationForm(instance=reservation)
    data = {
        'user': user,
        'form': form,
        'edit': edit,
        'reservation': reservation,
    }
    if request.method == 'POST':
        form = ReservationForm(request.POST, instance=reservation)
        print ("Post")
        if form.is_valid():
            reservation=form.save(commit=False)
            reservation.save()
            #jump to payment processing
            redirect_url = reverse('reservation_payment',kwargs={'reservation_id':reservation.pk})
            return HttpResponseRedirect(redirect_url)
        else:
            data['form']=form
            return render(request, 'reservations/edit.html', data)
    #else:
    return render(request,'reservations/edit.html', data)
Exemplo n.º 4
0
def get_reservation(request):
    if request.method == 'GET':
        form = ReservationForm()
    else:
        form = ReservationForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email,
                          ['*****@*****.**'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, "reservation.html", {'form': form})
Exemplo n.º 5
0
def seats_selection(request, funcion):
	funcion1 = get_object_or_404(Funcion, idFuncion=funcion)
	if request.method == 'POST':
		user_data = {'funcion':funcion1}
		form = ReservationForm(request.user, request.POST, **user_data)
		if form.is_valid():
			data = form.cleaned_data
			# Reservar
			customer_user = request.user
			if data['for_user']:
				customer_user = data['for_user']
			if data['seat1']:
				# import pdb;pdb.set_trace()
				asiento = Asiento.objects.get(idSala=funcion1.sala,
											 numero=generatePosSeats(data['seat1']))
				Reserva.objects.create(idUsuario_asiste=customer_user,
									   idUsuario_asigna=request.user,
									   idFuncion=funcion1,
									   idAsiento=asiento)
			if data['seat2']:
				asiento = Asiento.objects.get(idSala=funcion1.sala,
											 numero=generatePosSeats(data['seat2']))
				Reserva.objects.create(idUsuario_asiste=customer_user,
									   idUsuario_asigna=request.user,
									   idFuncion=funcion1,
									   idAsiento=asiento)
			if data['seat3']:
				asiento = Asiento.objects.get(idSala=funcion1.sala,
											 numero=generatePosSeats(data['seat3']))
				Reserva.objects.create(idUsuario_asiste=customer_user,
									   idUsuario_asigna=request.user,
									   idFuncion=funcion1,
									   idAsiento=asiento)
			messages.success(request, u'Compra realizada de forma exitosa!')	
			return redirect('/')
	else:
		form = ReservationForm(request.user)

	pelicula_nombre = funcion1.idPelicula.nombre
	reserved_seats = Asiento.objects.filter(reserva__idFuncion=funcion1).values_list('numero')
	sala = funcion1.sala.idSala
	return render(request, 'seat.html',{'seats':generateSeatsPos(reserved_seats),
										'form':form,
										'pelicula':pelicula_nombre,
										'sala':sala,
										'hora_inicio':funcion1.hora_inicio},
				   content_type="text/html")
Exemplo n.º 6
0
def reservation(request, restaurant_id=None):
    template_name = 'reservation.html'
    context = RequestContext(request)
    dict = {}
    if restaurant_id:
        dict['restaurant'] = Restaurant.objects.get(pk=restaurant_id)
    if request.POST:
        if request.POST.get('cancel'):
            return HttpResponseRedirect(reverse('index'))
        form = ReservationForm(request.POST)
        if form.is_valid():
            reservation = form.save(commit=False)
            if request.user:
                reservation.user = request.user
            restaurant = reservation.restaurant
            restaurant.num_reservations += 1
            restaurant.lat = str(reservation.restaurant.lat)
            restaurant.lon = str(reservation.restaurant.lon)
            if restaurant.capacity - reservation.num_people < 0:
                form._errors['num_people'] = ErrorList([u"Unfortunately this restaurant doesn't like you and can't accomodate you.  Actually, they are just busy.  Try another time..."])
                dict['form'] = form
                if dict.get('restaurant'):
                    dict['form'].fields['restaurant'].widget = forms.HiddenInput()
                return render_to_response( template_name, dict, context, )
            else:
                restaurant.capacity -= reservation.num_people 
            restaurant.save()
            reservation.save()
            dict['msg'] = 'Thank you for your reservation.'
        else:
            dict['form'] = form
            if dict.get('restaurant'):
                dict['form'].fields['restaurant'].widget = forms.HiddenInput()
    else:
        if dict.get('restaurant'):
            dict['form'] = ReservationForm(initial={'restaurant':dict['restaurant']})
            dict['form'].fields['restaurant'].widget = forms.HiddenInput()
        else:
            dict['form'] = ReservationForm()
    return render_to_response(
        template_name,
        dict,
        context,
    )
Exemplo n.º 7
0
def res():
	form = ReservationForm(request.form)

	if request.method == 'POST' and form.validate():
		reservation = Reservation()
		save_res(reservation, form, new=True)
		flash('Reservation created successfully!')
		return redirect('/res')

	qry = db_session.query(Reservation)
	reservations = qry.all()

	reservationsTable = ReservationsTable(reversed(reservations))
	reservationsTable.border = True

	return render_template('res.html', 
						   form=form, 
						   reservations=reservations,
						   reservationsTable=reservationsTable)
Exemplo n.º 8
0
def reservation(request):
	args = {}
	args.update(csrf(request))	
	args['valgt_utstyr'] = request.session.get('test')
	args['lokasjon'] = args['valgt_utstyr'].lokasjon
	args['beskrivelse'] = args['valgt_utstyr'].beskrivelse
	args['siste_res'] = reversed(Reservasjon.objects.filter(utstyr__exact=args['valgt_utstyr']))
	
	if request.method == 'POST':
		form = ReservationForm(request.POST)
		if form.is_valid():
			form.save()
			return redirect('/lru/')
		else:
			args['form'] = form
			return render(request, 'lru/reservation.html', args)	
	else:
		form = ReservationForm(initial={'reservert_av': request.user,'utstyr': args['valgt_utstyr']})
		args['form'] = form	
		return render(request, 'lru/reservation.html', args)
Exemplo n.º 9
0
def edit_res(id):
	qry = db_session.query(Reservation).filter(Reservation.id==id)
	reservation = qry.first()

	if reservation:
		form = ReservationForm(formdata=request.form,obj=reservation)
		if request.method == 'POST':
			save_res(reservation, form)
			flash('Reservation updated successfully!')
			return redirect('/res')
		return render_template('edit_res.html', form=form)

	else:
		return 'Error loaging #{id}'.format(id=id)
Exemplo n.º 10
0
def get_reservation(request):
    if request.method == 'POST':
        form = ReservationForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'booking.html')
    else:
        form = ReservationForm()

    args = {'form': form}
    args.update(csrf(request))

    return render(request, 'reservation.html', args)
Exemplo n.º 11
0
def reservation(request, id, employee_id):
    service = get_object_or_404(Service, id=id)
    #Klemen: dobi zaposlenega za to storitev, ce je bil dolocen


    if employee_id > 0:
        service_provider_employee_obj = get_object_or_404(ServiceProviderEmployee, id=employee_id)
    else:
        service_provider_employee_obj = None

    if not service.is_active():
        raise Http404



    minTime, maxTime = getMinMaxTime(service.service_provider)



    if request.method != 'POST':
        # ce je zaposleni dolocen, ga daj kot initial
        if service_provider_employee_obj:
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj, initial={"service_provider_employee":service_provider_employee_obj})
        else:
            #ce se ni bil izbran
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj)
        service_provider = service.service_provider
        data = {'service_provider_id': service.service_provider_id} # 'service_provider_employee_id': service_provider_employee_obj.id }
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    # POST
    step = request.POST.get('step', '1')

    try:
        data = pickle.loads(base64.b64decode(request.POST.get('data')))  # Serializes an object from request
    except:
        raise Http404

    if service_provider_employee_obj:
        workingHours = WorkingHours.objects.filter(service_provider_id=service.service_provider_id)
    else:
        workingHours = EmployeeWorkingHours.objects.filter(service=service, service_provider_employee=service_provider_employee_obj)




    formNonRegisteredUser = NonRegisteredUserForm()

    if step == '1':
        # Service, date, time
        # form = ReservationForm(request.POST, workingHours='gergerre')
        #service_provider_employee_choice = request.POST.get['service_provider_employee']
        #print service_provider_employee_choice
        form = ReservationForm(request, request.POST, workingHours=workingHours, service=service, serviceProviderEmployee=service_provider_employee_obj)

        if form.is_valid():
            data['date'] = form.cleaned_data['date']
            data['time'] = form.cleaned_data['time']
            data['number'] = form.cleaned_data['number']
            service_provider_employee_obj = form.cleaned_data['service_provider_employee']
            # ce je bil izbran zaposleni, shrani njegov id in ga prenesi v naslednje step-e

            if service_provider_employee_obj:
                data['service_provider_employee'] = form.cleaned_data['service_provider_employee'].id

            if request.user.is_authenticated():
                data['user_id'] = request.user.id
                data['name'] = request.user.get_full_name()
                data['phone'] = request.user.phone
                data['email'] = request.user.email
                data['service_notifications'] = request.user.service_notifications
                return render_to_response('reservations/confirmation.html', locals(), context_instance=RequestContext(request))

            return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))
        if service_provider_employee_obj:
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj, initial={"service_provider_employee":service_provider_employee_obj})
        else:
            #ce se ni bil izbran
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj)
        service_provider = service.service_provider
        data = {'service_provider_id': service.service_provider_id} # 'service_provider_employee_id': service_provider_employee_obj.id }

        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    if step == '2':
        # User info
        if data.get('date') is None or data.get('time') is None:
            raise Http404
        formNonRegisteredUser = NonRegisteredUserForm(request.POST)
        if formNonRegisteredUser.is_valid():
            data['name'] = formNonRegisteredUser.cleaned_data['name']
            data['phone'] = formNonRegisteredUser.cleaned_data['phone']
            data['email'] = formNonRegisteredUser.cleaned_data['email']
            data['service_notifications'] = formNonRegisteredUser.cleaned_data['service_notifications']
            return render_to_response('reservations/confirmation.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

    if step == '3':
        # Confirmation

        #inicializiraj objekt zaposlenega glede na to, kateri je bil prej izbran
        if data.get('service_provider_employee'):
            service_provider_employee_obj = get_object_or_404(ServiceProviderEmployee, id=data.get('service_provider_employee'))
        else:
            service_provider_employee_obj = None
        if data.get('date') is None or data.get('time') is None:  # or data.get('user_id') is None:
            raise Http404
        if data.get('user_id') is not None:
            ruser = get_object_or_404(User, id=data.get('user_id'))
        else:
            ruser = None

        sync(service.service_provider)

        # Checking again if form for reservation is valid
        form = ReservationForm(request, {'date': data.get('date'), 'time': data.get('time')}, workingHours=workingHours, service=service, serviceProviderEmployee=service_provider_employee_obj)
        #form.fields['service_provider_employee']=service_provider_employee_obj

        if form.is_valid():
            # Add a customer
            user_mail = None
            if ruser is None:
            # If an unregistered customer performs reservation
                customer_name = data.get('name').split()
                customer = Customer(name=customer_name[0], last_name=customer_name[len(customer_name)-1], phone=data.get('phone'), email=data.get('email'), full_name=data.get('name'))
                user_mail = data.get('email')
            else:
                # If a registered customer performs reservation
                customer = Customer(name=ruser.first_name, last_name=ruser.last_name, phone=ruser.phone, email=ruser.email, full_name=ruser.first_name+' '+ruser.last_name)
                user_mail = ruser.email
            try:
                Customer.objects.get(email=data.get('email'))

            except:
                # Save a customer if they are not already in
                customer.save()
            # Save a reservation
            customer = Customer.objects.get(email=user_mail)
            customer.last_reservation=datetime.datetime.today()
            customer.save(update_fields=['last_reservation'])
            reserve = Reservation(user=ruser, service=service, date=data['date'], time=data['time'], customer=customer, service_notifications=data['service_notifications'])
            # Add backup fields
            reserve.user_fullname = data.get('name')
            reserve.user_phone = data.get('phone')
            reserve.user_email = data.get('email')
            reserve.service_provider = service.service_provider
            reserve.service_name = service.name
            reserve.service_duration = service.duration
            reserve.service_price = service.discounted_price()
            reserve.service_provider_employee = service_provider_employee_obj
            # Save
            reserve.save()

            #Creating scheduler reminder
            if data.get('service_notifications'):
                datetime_reminder = datetime.datetime.combine(reserve.date, reserve.time) - datetime.timedelta(hours=4)
                if service.service_provider.send_sms_reminder:
                    send_reminder_sms.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)
                if service.service_provider.send_email_reminder:
                    send_reminder_email.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)

            elif request.user.send_reminders:
                datetime_reminder = datetime.datetime.combine(reserve.date, reserve.time) - datetime.timedelta(hours=4)
                if service.service_provider.send_sms_reminder:
                    send_reminder_sms.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)
                if service.service_provider.send_email_reminder:
                    send_reminder_email.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)

            # saving coupon is_valid
            coupons = Coupon.objects.filter(service=service.id)
            for coup in coupons:
                if(data['number'] == coup.number):
                    coup.is_used = True
                    coup.save()
                    # Validation checking in form

            email_to1 = data.get('email')
            email_to2 = service.service_provider.user.email
            if(service.service_provider.reservation_confirmation_needed == False):
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html', {'reservation': reserve})
                renderedToProvider = render_to_string('emails/reservation_provider.html', {'reservation': reserve})
                message1 = (subject, renderedToCustomer, None, [email_to1])
                message2 = (subject, renderedToProvider, None, [email_to2])
                send_mass_mail((message1, message2), fail_silently=True)
            else:
                subject = _('Confirmation of service reservation')
                renderedToProvider = render_to_string('emails/reservation_provider.html', {'reservation': reserve})
                send_mail(subject, renderedToProvider, None, [email_to2], fail_silently=False)

            start = datetime.datetime.combine(reserve.date, reserve.time)
            gcal_params = urllib.urlencode({
                'action': 'TEMPLATE',
                'text': reserve.service_name.encode('utf8'),
                'dates': '%s/%s' % (datetime_to_url_format(start), datetime_to_url_format(start + datetime.timedelta(minutes=reserve.service_duration))),
                'details': reserve.service.description.encode('utf8'),
                'location': reserve.service_provider.full_address().encode('utf8'),
                'trp': 'true',
                'sprop': 'E-Narocanje',
                'sprop': 'name:%s' % settings.BASE_URL,
            })
            if service_provider_employee_obj <> None:
                url_service = settings.BASE_URL + reverse('service', args=(service.id,service_provider_employee_obj.id,))
            else:
                url_service = settings.BASE_URL + reverse('service2', args=(service.id,))

            sync(service.service_provider)

            return render_to_response('reservations/done.html', locals(), context_instance=RequestContext(request))

        # Someone else has made a reservation in the meantime
        return render_to_response('reservations/alreadyreserved.html', locals(), context_instance=RequestContext(request))
    raise Http404
Exemplo n.º 12
0
def reservation(request, id, employee_id):
    service = get_object_or_404(Service, id=id)
    #Klemen: dobi zaposlenega za to storitev, ce je bil dolocen


    if employee_id > 0:
        service_provider_employee_obj = get_object_or_404(ServiceProviderEmployee, id=employee_id)
    else:
        service_provider_employee_obj = None

    if not service.is_active():
        raise Http404
    if service_provider_employee_obj:
        workingHoursEmployee = EmployeeWorkingHours.objects.get(service=service, service_provider_employee=service_provider_employee_obj)
        minTime = workingHoursEmployee.time_from
        maxTime = workingHoursEmployee.time_to
    else:
        minTime, maxTime = getMinMaxTime(service.service_provider)


    if request.POST.get('action', None) == 'employeechanged':
        workingHoursEmployee = EmployeeWorkingHours.objects.get(service=service, service_provider_employee_id=request.POST.get('service_provider_employee', None))
        minTime = workingHoursEmployee.time_from
        maxTime = workingHoursEmployee.time_to
        form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj, initial={"service_provider_employee": request.POST.get('service_provider_employee', None),})
        service_provider_employee_obj = ServiceProviderEmployee.objects.get(pk=request.POST.get('service_provider_employee', None))
        data = {'service_provider_id': service.service_provider_id} # 'service_provider_employee_id': service_provider_employee_obj.id }
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))


    if request.method != 'POST':
        # ce je zaposleni dolocen, ga daj kot initial
        if service_provider_employee_obj:
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj, initial={"service_provider_employee":service_provider_employee_obj})
        else:
            #ce se ni bil izbran
            form = ReservationForm(request, workingHours=None, service=service, serviceProviderEmployee=service_provider_employee_obj)

        data = {'service_provider_id': service.service_provider_id} # 'service_provider_employee_id': service_provider_employee_obj.id }
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    # POST
    step = request.POST.get('step', '1')

    try:
        data = pickle.loads(base64.b64decode(request.POST.get('data')))  # Serializes an object from request
    except:
        raise Http404

    if service_provider_employee_obj:
        workingHours = WorkingHours.objects.filter(service_provider_id=service.service_provider_id)
    else:
        workingHours = EmployeeWorkingHours.objects.filter(service=service, service_provider_employee=service_provider_employee_obj)




    formNonRegisteredUser = NonRegisteredUserForm()

    if step == '1':
        # Service, date, time
        # form = ReservationForm(request.POST, workingHours='gergerre')
        #service_provider_employee_choice = request.POST.get['service_provider_employee']
        #print service_provider_employee_choice
        form = ReservationForm(request, request.POST, workingHours=workingHours, service=service, serviceProviderEmployee=service_provider_employee_obj)

        if form.is_valid():
            data['date'] = form.cleaned_data['date']
            data['time'] = form.cleaned_data['time']
            data['number'] = form.cleaned_data['number']
            service_provider_employee_obj = form.cleaned_data['service_provider_employee']
            # ce je bil izbran zaposleni, shrani njegov id in ga prenesi v naslednje step-e

            if service_provider_employee_obj:
                data['service_provider_employee'] = form.cleaned_data['service_provider_employee'].id

            if request.user.is_authenticated():
                data['user_id'] = request.user.id
                data['name'] = request.user.get_full_name()
                data['phone'] = request.user.phone
                data['email'] = request.user.email
                data['service_notifications'] = request.user.service_notifications
                return render_to_response('reservations/confirmation.html', locals(), context_instance=RequestContext(request))

            return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    if step == '2':
        # User info
        if data.get('date') is None or data.get('time') is None:
            raise Http404
        formNonRegisteredUser = NonRegisteredUserForm(request.POST)
        if formNonRegisteredUser.is_valid():
            data['name'] = formNonRegisteredUser.cleaned_data['name']
            data['phone'] = formNonRegisteredUser.cleaned_data['phone']
            data['email'] = formNonRegisteredUser.cleaned_data['email']
            data['service_notifications'] = formNonRegisteredUser.cleaned_data['service_notifications']
            return render_to_response('reservations/confirmation.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

    if step == '3':
        # Confirmation

        #inicializiraj objekt zaposlenega glede na to, kateri je bil prej izbran
        if data.get('service_provider_employee'):
            service_provider_employee_obj = get_object_or_404(ServiceProviderEmployee, id=data.get('service_provider_employee'))
        else:
            service_provider_employee_obj = None
        if data.get('date') is None or data.get('time') is None:  # or data.get('user_id') is None:
            raise Http404
        if data.get('user_id') is not None:
            ruser = get_object_or_404(User, id=data.get('user_id'))
        else:
            ruser = None

        sync(service.service_provider)

        # Checking again if form for reservation is valid
        form = ReservationForm(request, {'date': data.get('date'), 'time': data.get('time')}, workingHours=workingHours, service=service, serviceProviderEmployee=service_provider_employee_obj)
        #form.fields['service_provider_employee']=service_provider_employee_obj

        if form.is_valid():
            # Add a customer
            user_mail = None
            if ruser is None:
            # If an unregistered customer performs reservation
                customer_name = data.get('name').split()
                customer = Customer(name=customer_name[0], last_name=customer_name[len(customer_name)-1], phone=data.get('phone'), email=data.get('email'), full_name=data.get('name'))
                user_mail = data.get('email')
            else:
                # If a registered customer performs reservation
                customer = Customer(name=ruser.first_name, last_name=ruser.last_name, phone=ruser.phone, email=ruser.email, full_name=ruser.first_name+' '+ruser.last_name)
                user_mail = ruser.email
            try:
                Customer.objects.get(email=data.get('email'))

            except:
                # Save a customer if they are not already in
                customer.save()
            # Save a reservation
            customer = Customer.objects.get(email=user_mail)
            customer.last_reservation=datetime.datetime.today()
            customer.save(update_fields=['last_reservation'])
            reserve = Reservation(user=ruser, service=service, date=data['date'], time=data['time'], customer=customer, service_notifications=data['service_notifications'])
            # Add backup fields
            reserve.user_fullname = data.get('name')
            reserve.user_phone = data.get('phone')
            reserve.user_email = data.get('email')
            reserve.service_provider = service.service_provider
            reserve.service_name = service.name
            reserve.service_duration = service.duration
            reserve.service_price = service.discounted_price()
            reserve.service_provider_employee = service_provider_employee_obj
            # Save
            reserve.save()

            #Creating scheduler reminder
            if data.get('service_notifications'):
                datetime_reminder = datetime.datetime.combine(reserve.date, reserve.time) - datetime.timedelta(hours=4)
                if service.service_provider.send_sms_reminder:
                    send_reminder_sms.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)
                if service.service_provider.send_email_reminder:
                    send_reminder_email.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)

            elif request.user.send_reminders:
                datetime_reminder = datetime.datetime.combine(reserve.date, reserve.time) - datetime.timedelta(hours=4)
                if service.service_provider.send_sms_reminder:
                    send_reminder_sms.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)
                if service.service_provider.send_email_reminder:
                    send_reminder_email.apply_async((data.get('time'), service.service_provider.name, service.name), eta=datetime_reminder)

            # saving coupon is_valid
            coupons = Coupon.objects.filter(service=service.id)
            for coup in coupons:
                if(data['number'] == coup.number):
                    coup.is_used = True
                    coup.save()
                    # Validation checking in form

            email_to1 = data.get('email')
            email_to2 = service.service_provider.user.email
            if(service.service_provider.reservation_confirmation_needed == False):
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html', {'reservation': reserve})
                renderedToProvider = render_to_string('emails/reservation_provider.html', {'reservation': reserve})
                message1 = (subject, renderedToCustomer, None, [email_to1])
                message2 = (subject, renderedToProvider, None, [email_to2])
                send_mass_mail((message1, message2), fail_silently=True)
            else:
                subject = _('Confirmation of service reservation')
                renderedToProvider = render_to_string('emails/reservation_provider.html', {'reservation': reserve})
                send_mail(subject, renderedToProvider, None, [email_to2], fail_silently=False)

            start = datetime.datetime.combine(reserve.date, reserve.time)
            gcal_params = urllib.urlencode({
                'action': 'TEMPLATE',
                'text': reserve.service_name.encode('utf8'),
                'dates': '%s/%s' % (datetime_to_url_format(start), datetime_to_url_format(start + datetime.timedelta(minutes=reserve.service_duration))),
                'details': reserve.service.description.encode('utf8'),
                'location': reserve.service_provider.full_address().encode('utf8'),
                'trp': 'true',
                'sprop': 'E-Narocanje',
                'sprop': 'name:%s' % settings.BASE_URL,
            })
            if service_provider_employee_obj <> None:
                url_service = settings.BASE_URL + reverse('service', args=(service.id,service_provider_employee_obj.id,))
            else:
                url_service = settings.BASE_URL + reverse('service2', args=(service.id,))

            sync(service.service_provider)

            return render_to_response('reservations/done.html', locals(), context_instance=RequestContext(request))

        # Someone else has made a reservation in the meantime
        return render_to_response('reservations/alreadyreserved.html', locals(), context_instance=RequestContext(request))
    raise Http404
Exemplo n.º 13
0
Arquivo: views.py Projeto: mfrlin/TPO
def reservation(request, id):
    service = get_object_or_404(Service, id=id)

    chosen_employee = None
    emp_size = 0
    if not service.is_active():
        raise Http404
    minTime, maxTime = getMinMaxTime(service.service_provider)

    #step2 = request.session['_step'] if '_step' in request.session
    step2 = request.GET.get('step', None)

    # POST
    step = request.POST.get('step', None)

    data = None
    if step:
        try:
            data = pickle.loads(base64.b64decode(request.POST.get('data')))  # Serializes an object from request
        except:
            raise Http404
    elif step2:
        step = step2
        if 'reservation_data' in request.session:
            data = request.session['reservation_data']
        else:
            step = None

    if (request.method != 'POST' and data is None) or step is None:
        #form = ReservationForm(request, workingHours=None, service=None)
        form = ReservationForm(request, workingHours=None, service=service)
        data = {'service_provider_id': service.service_provider_id, 'service_id': service.id}
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    workingHours = WorkingHours.objects.filter(service_provider_id=service.service_provider_id)

    #formNonRegisteredUser = NonRegisteredUserForm(prefix='nonRegBtn')
    formNonRegisteredUser = NonRegisteredUserForm(provider=service.service_provider)
    loginForm = LoginForm(prefix='loginBtn')
    signupForm = SignupForm(prefix='signupBtn')

    if step == '1':
        # Service, date, time
        # form = ReservationForm(request.POST, workingHours='gergerre')
        form = ReservationForm(request, request.POST, workingHours=workingHours, service=service)
        if form.is_valid():
            chosen_employee = form.cleaned_data['employees']
            data['date'] = form.cleaned_data['date']
            data['time'] = form.cleaned_data['time']
            data['number'] = form.cleaned_data['number']
            data['employees'] = form.cleaned_data['employees']

            if request.user.is_authenticated():
                data['user_id'] = request.user.id
                data['name'] = request.user.get_full_name()
                data['phone'] = request.user.phone
                data['email'] = request.user.email
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

            return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    if step == '2':
        if data.get('date') is None or data.get('time') is None:
            raise Http404

        if 'signupBtn' in request.POST:
            signupForm = SignupForm(request.POST, prefix='signupBtn')

            if signupForm.is_valid():
                userr = signupForm.save(request)

                data['user_id'] = userr.id
                data['name'] = userr.get_full_name()
                data['phone'] = userr.phone
                data['email'] = userr.email

                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

        if 'loginBtn' in request.POST:
            loginForm = LoginForm(request.POST, prefix='loginBtn')

            if loginForm.is_valid():
                data['user_id'] = loginForm.user.id
                data['name'] = loginForm.user.get_full_name()
                data['phone'] = loginForm.user.phone
                data['email'] = loginForm.user.email

                request.session['reservation_data'] = data
                return loginForm.login(request, redirect_url=reverse('reservation', args=[service.id]) + "?step=2a")

        if 'nonRegBtn' in request.POST:

            formNonRegisteredUser = NonRegisteredUserForm(request.POST, provider=service.service_provider)
            if formNonRegisteredUser.is_valid():
                data['name'] = formNonRegisteredUser.cleaned_data['name']
                data['phone'] = formNonRegisteredUser.cleaned_data['phone']
                data['email'] = formNonRegisteredUser.cleaned_data['email']
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))
        return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

    if step == '2a':
        if request.user.is_authenticated():
            return render_to_response('reservations/confirmation.html', locals(),
                                      context_instance=RequestContext(request))

    if step == '3':
        # Confirmation
        if data.get('date') is None or data.get('time') is None:  # or data.get('user_id') is None:
            raise Http404
        if data.get('user_id') is not None:
            ruser = get_object_or_404(User, id=data.get('user_id'))
        else:
            ruser = None

        sync(service.service_provider)

        # Checking again if form for reservation is valid
        chosen_employee = data.get('employees')
        emp_id = None
        if chosen_employee is not None and chosen_employee != '':
            emp_id = chosen_employee.id

        form = ReservationForm(request,
                               {'date': data.get('date'), 'time': data.get('time'), 'employees': emp_id},
                               workingHours=workingHours, service=service)

        if form.is_valid():
            form_emp = None
            if chosen_employee != '':
                form_emp = chosen_employee
            reserve = Reservation(user=ruser, service=service, date=data['date'], time=data['time'],
                                  employee=form_emp)
            # Add backup fields
            reserve.user_fullname = data.get('name')
            reserve.user_phone = data.get('phone')
            reserve.user_email = data.get('email')
            reserve.service_provider = service.service_provider
            reserve.service_name = service.name
            reserve.service_duration = service.duration
            reserve.service_price = service.discounted_price()
            reserve.show_up = False
            if chosen_employee is not None and chosen_employee != '':
                reserve.employee = chosen_employee
            else:
                # if employees assigned to service, randomly choose one who is free
                if service.employees.all().__len__() > 0:
                    today_r = Reservation.objects.filter(employee__in=service.employees.all(), date=reserve.date)
                    # find free employees
                    reserveDt = datetime.datetime.combine(reserve.date, reserve.time)
                    free_emp = list(service.employees.all())
                    free_emp_editable = list(service.employees.all())
                    for emp in free_emp:
                        emp_time = EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                       reserve.date.weekday())
                        if not EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                   reserve.date.weekday()):
                            free_emp_editable.remove(emp)
                        if reserve.time < emp_time.time_from or reserveDt + datetime.timedelta(
                                minutes=reserve.service_duration) > datetime.datetime.combine(reserve.date,
                                                                                              emp_time.time_to):
                            free_emp_editable.remove(emp)
                    for r in today_r:
                        rDt = datetime.datetime.combine(r.date, r.time)
                        if r.active_during(reserveDt):
                            if r.employee in free_emp:
                                free_emp_editable.remove(r.employee)
                                # choose random employee
                    if free_emp_editable:
                        random_employee = free_emp_editable[random.randint(0, len(free_emp_editable) - 1)]
                        reserve.employee = random_employee

            # Save
            reserve.user.notification_type = 'email'
            reserve.save()
            # saving coupon is_valid
            coupons = Coupon.objects.filter(service=service.id)
            coupon_is_used = False
            for coup in coupons:
                if data['number'] == coup.number:
                    coup.is_used = True
                    coup.save()
                    coupon_is_used = True
                    # Validation checking in form

            user_page_link = '%s/u/%s' % (settings.BASE_URL, reserve.service_provider.userpage_link)
            email_to1 = data.get('email')
            email_to2 = service.service_provider.user.email
            if service.service_provider.reservation_confirmation_needed:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                renderedToProvider = render_to_string('emails/reservation_provider.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                message1 = (subject, renderedToCustomer, None, [email_to1])
                message2 = (subject, renderedToProvider, None, [email_to2])
                send_mass_mail((message1, message2), fail_silently=True)
            else:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                send_mail(subject, renderedToCustomer, email_to2, [email_to1],
                          fail_silently=False)

            start = datetime.datetime.combine(reserve.date, reserve.time)
            gcal_params = urllib.urlencode({
                'action': 'TEMPLATE',
                'text': reserve.service_name.encode('utf8'),
                'dates': '%s/%s' % (datetime_to_url_format(start),
                                    datetime_to_url_format(
                                        start + datetime.timedelta(minutes=reserve.service_duration))),
                'details': reserve.service.description.encode('utf8'),
                'location': reserve.service_provider.full_address().encode('utf8'),
                'trp': 'true',
                'sprop': 'E-Narocanje',
                'sprop': 'name:%s' % settings.BASE_URL,
            })
            url_service = settings.BASE_URL + reverse('service', args=(service.id,))

            sync(service.service_provider)

            return render_to_response('reservations/done.html', locals(), context_instance=RequestContext(request))

        # Someone else has made a reservation in the meantime
        return render_to_response('reservations/alreadyreserved.html', locals(),
                                  context_instance=RequestContext(request))
    raise Http404
Exemplo n.º 14
0
def make_reservation(train_id=None):
    form = ReservationForm()
    date = request.args.get('date', type=str)
    train_id = request.args.get('train_id', type=int)
    departure_station = request.args.get('departure_station', type=str)
    departure_time = request.args.get('departure_time', type=str)
    arrival_station = request.args.get('arrival_station', type=str)
    arrival_time = request.args.get('arrival_time', type=str)
    seats_available = request.args.get('seats_available', type=str)
    price = request.args.get('price', type=str)
    num_adult = request.args.get('num_adult', type=int)
    num_child = request.args.get('num_child', type=int)
    num_senior = request.args.get('num_senior', type=int)
    num_military = request.args.get('num_military', type=int)
    num_pets = request.args.get('num_pets', type=int)

    if request.method == 'GET':
        return render_template('makereservation.html',
                               form=form,
                               date=date,
                               train_id=train_id,
                               departure_station=departure_station,
                               departure_time=departure_time,
                               arrival_station=arrival_station,
                               arrival_time=arrival_time,
                               seats_available=seats_available,
                               price=price,
                               passengers=[
                                   num_adult, num_child, num_senior,
                                   num_military, num_pets
                               ])
    elif request.method == 'POST':
        if form.validate():
            booker = {
                'first_name': form.first_name.data,
                'last_name': form.last_name.data,
                'email': form.email.data
            }

            passengers = [
                int(form.num_adult.data),
                int(form.num_child.data),
                int(form.num_senior.data),
                int(form.num_military.data),
                int(form.num_pets.data)
            ]
            print('PASSENGERS FROM FORM: {}'.format(passengers))
            create_reservation_and_trips(train_id, departure_station,
                                         departure_time, arrival_station,
                                         passengers, booker, date)

            message = 'The reservation has been made successfully!'
            return render_template('success.html', message=message)
        else:
            return render_template('makereservation.html',
                                   form=form,
                                   date=date,
                                   train_id=train_id,
                                   departure_station=departure_station,
                                   departure_time=departure_time,
                                   arrival_station=arrival_station,
                                   arrival_time=arrival_time,
                                   seats_available=seats_available,
                                   price=price,
                                   passengers=[
                                       num_adult, num_child, num_senior,
                                       num_military, num_pets
                                   ])
    def render(self, context, instance, placeholder):
        request = context['request']
        context.update({
            'name':instance.name,
            })
            
        #Form was sent in
        if request.method == "POST":
            form = ReservationForm(request.POST)
            
            #Form is valid: save and send informative mails
            if form.is_valid():
                reservation = form.save(commit=False)
                reservation.reservation_list = instance
                reservation.save()

                #Send mail to responsible for the reservation
                send_mail(_('New reservation for %s') % instance.name,
                            _('A new reservation was made for %(name)s.\n') % {'name': instance.name,} + \
                            _('Contact information:\n') % {'contact_name': reservation.contact_name,} +\
                            _('- Name: %(contact_name)s\n') % {'contact_name': reservation.contact_name,} +\
                            _('- Email: %(contact_mail)s\n') % {'contact_mail': reservation.contact_mail,} +\
                            _('- Phone number: %(contact_phone)s\n') % {'contact_phone': reservation.contact_phone,},
                            '*****@*****.**', #TODO: add mail to settings
                            [instance.inform_mail], fail_silently=True)

                #Send confirmation mail to the one who just reserved
                send_mail(_('New reservation for %s') % instance.name,
                            _('You have just made a reservation for %(name)s. Your reservation will now be reviewed.\n') % {'name': instance.name,} +\
                            _('If you have further questions, please contact us at %(mail)s.\n') % {'mail': "*****@*****.**",},

                            '*****@*****.**', #TODO: add mail to settings
                            [instance.inform_mail], fail_silently=True)

                messages.success(request, _('Your reservation was successful, and is now pending. You will have received an email confirming this.'))

                form = ReservationForm()
                
            #Form is invalid: display errors (so leave the form be)
            else:
                pass
                
        #No form data sent in
        else:
            #process administration controls
            self.administration(request)
            #Create new form
            form = ReservationForm()

        if all(key in request.GET for key in ("month","year")):
            month = date(int(request.GET['year']), int(request.GET['month']),1)
        else:
            month = date.today()

        if month.month % 12 is 0:
            next_month = date(month.year+1, 1, 1)
        else:
            next_month = date(month.year, month.month+1, 1)

        if month.month is 1:
            prev_month = date(month.year-1, 12, 1)
        else:
            prev_month = date(month.year, month.month-1, 1)

        if month.month == date.today().month and month.year == date.today().year:
            prev_month = None

        context.update({
            'calendar':self.get_calendar_context(month),
            'form':form,
            'month': month,
            'prev_month': prev_month,
            'next_month': next_month,
        })
        
        return context
Exemplo n.º 16
0
    def render(self, context, instance, placeholder):
        request = context['request']
        context.update({
            'name':instance.name,
            })
            
        #Form was sent in
        if request.method == "POST":
            form = ReservationForm(request.POST)
            
            #Form is valid: save and send informative mails
            if form.is_valid():
                reservation = form.save(commit=False)
                reservation.reservation_list = instance
                reservation.save()

                #Send mail to responsible for the reservation
                send_mail(_('New reservation for %s') % instance.name,
                            _('A new reservation was made for %(name)s.\n') % {'name': instance.name,} + \
                            _('Contact information:\n') % {'contact_name': reservation.contact_name,} +\
                            _('- Name: %(contact_name)s\n') % {'contact_name': reservation.contact_name,} +\
                            _('- Email: %(contact_mail)s\n') % {'contact_mail': reservation.contact_mail,} +\
                            _('- Phone number: %(contact_phone)s\n') % {'contact_phone': reservation.contact_phone,} +\
                            _('- Datum van reservatie: %(date)s\n') % {'date': reservation.date,},
                            '*****@*****.**', #TODO: add mail to settings
                            [instance.inform_mail], fail_silently=True)

                #Send confirmation mail to the one who just reserved
                send_mail(_('New reservation for %s') % instance.name,
                          _('U heeft zopas een reservatie gemaakt voor gebruik van de hakselaar.')  +\
                          _('Uw reservatie zal nu worden nagekeken en in de komende dagen wordt contact opgenomen voor verdere afspraken.\n') +\
                          _('Bij verdere vragen of dringendheid kan je ook zelf contact opnemen met Steven Van Hyfte 0479 257670.\n') +\
                          _('Alvast bedankt.'),
                            '*****@*****.**', #TODO: add mail to settings
                            [reservation.contact_mail], fail_silently=True)

                messages.success(request, _('Your reservation was successful, and is now pending. You will have received an email confirming this.'))

                form = ReservationForm()
                
            #Form is invalid: display errors (so leave the form be)
            else:
                pass
                
        #No form data sent in
        else:
            #process administration controls
            self.administration(request)
            #Create new form
            form = ReservationForm()

        if all(key in request.GET for key in ("month","year")):
            month = date(int(request.GET['year']), int(request.GET['month']),1)
        else:
            month = date.today()

        if month.month % 12 is 0:
            next_month = date(month.year+1, 1, 1)
        else:
            next_month = date(month.year, month.month+1, 1)

        if month.month is 1:
            prev_month = date(month.year-1, 12, 1)
        else:
            prev_month = date(month.year, month.month-1, 1)

        context.update({
            'calendar':self.get_calendar_context(month),
            'form':form,
            'month': month,
            'prev_month': prev_month,
            'next_month': next_month,
        })
        
        return context