Exemplo n.º 1
0
def create(request):
    """
    parameters:
        redirect: opcional, incluir en la URL de la petición si se quiere redirigir a la página del empleado creado
    returns:
        form: formulario con los datos necesarios para el registro del empleado
        success: opcional, si se ha tenido éxito al crear un empleado
        errors: opcional, array de mensajes de error si ha habido algún error

    errores: (todos empiezan por employeeCreation_)
        passwordsDontMatch: las contraseñas no coinciden
        usernameNotUnique: el nombre de usuario ya existe
        imageNotValid: la imagen no es válida por formato y/o tamaño
        formNotValid: el formulario contiene errores
        priceNotValid: el precio debe ser mayor que 0
        emailNotUnique:si el correo no es úinco

    template:
        employee_register.html
    """

    # Check that the user is logged in and it's an administrator
    admin = get_admin_executive_or_403(request)

    # If it's a GET request, return an empty form
    if request.method == "GET":
        return render(request, 'employee/employee_register.html',
                      {'form': EmployeeRegisterForm()})

    elif request.method == "POST":
        # We are serving a POST request
        form = EmployeeRegisterForm(request.POST, request.FILES)

        if form.is_valid():

            errors = []

            # Check that the passwords match
            if not check_passwords(form):
                errors.append('employeeCreation_passwordsDontMatch')

            #Check password validation
            if not validate_pass(form.cleaned_data["password1"]):
                errors.append('newPasswordInvalid')

            # Check that the username is unique
            if not is_username_unique(form.cleaned_data["username"]):
                errors.append('employeeCreation_usernameNotUnique')

            # Check that the email is unique
            if not is_email_unique(form.cleaned_data["email"]):
                errors.append('employeeCreation_emailNotUnique')

            # Check that the image is OK
            if not check_image(form, 'photo'):
                errors.append('employeeCreation_imageNotValid')

            # Check that the price is OK
            if form.cleaned_data['price_per_hour'] <= 0:
                errors.append('employeeCreation_priceNotValid')

            if not errors:
                # Everything is OK, create the employee
                employee_user = create_employee_user(form)
                employee = create_employee(employee_user, admin, form)
                EmployeeLog.objects.create(
                    employee_id=employee,
                    event="A",
                    price_per_hour=employee.price_per_hour)
                send_register_email(form.cleaned_data["email"],
                                    form.cleaned_data["first_name"])

                return HttpResponseRedirect('/employee/view/' +
                                            form.cleaned_data["username"] +
                                            '/')

            else:
                # There are errors
                return render(request, 'employee/employee_register.html', {
                    'form': form,
                    'errors': errors
                })

        # Form is not valid
        else:
            return render(request, 'employee/employee_register.html', {
                'form': form,
                'errors': ['employeeCreation_formNotValid']
            })
    else:
        # Another request method
        raise PermissionDenied
Exemplo n.º 2
0
def edit(request, username):
    """
    url = employee/edit/<username>

    parameters/returns:
        form: formulario de edicion de datos de empleado

    errors:
        'employeeCreation_formNotValid': si el formulario no es válido

    template: employee_edit.html
    """

    # Check that the user is logged in and it's an administrator
    admin = get_admin_executive_or_403(request)
    employee = get_object_or_404(Employee, user__username=username)

    # Check that the admin has permission to view that employee
    same_company_or_403(admin, employee)

    if request.method == "GET":
        # Return a form filled with the employee's data
        form = EmployeeEditForm(
            initial={
                'first_name': employee.user.first_name,
                'last_name': employee.user.last_name,
                'email': employee.user.email,
                'identifier': employee.identifier,
                'phone': employee.phone,
                'price_per_hour': employee.price_per_hour
            })

        return render(
            request, 'employee/employee_edit.html', {
                'form': form,
                'picture': employee.picture,
                'username': username,
                'pass_form': EmployeePasswordForm(),
                'active': employee.user.is_active
            })

    elif request.method == "POST":
        # Process the received form

        form = EmployeeEditForm(request.POST, request.FILES)
        if form.is_valid():
            errors = []
            # Check that the price is OK
            if form.cleaned_data['price_per_hour'] <= 0:
                errors.append('employeeCreation_priceNotValid')

            # Check that the image is OK
            if not check_image(form, 'photo'):
                errors.append('employeeCreation_imageNotValid')

            # Check that the email is unique
            if not is_email_unique(
                    form.cleaned_data["email"]
            ) and employee.user.email != form.cleaned_data["email"]:
                errors.append('employeeCreation_emailNotUnique')

            if not errors:
                # Update employee data
                employee.identifier = form.cleaned_data["identifier"]
                employee.phone = form.cleaned_data["phone"]
                # New log if the salary has changed
                new_log = employee.price_per_hour != form.cleaned_data[
                    "price_per_hour"]

                employee.price_per_hour = form.cleaned_data["price_per_hour"]
                if form.cleaned_data["photo"]:
                    employee.picture = form.cleaned_data["photo"]

                # Update user data
                user = employee.user
                user.first_name = form.cleaned_data["first_name"]
                user.last_name = form.cleaned_data["last_name"]
                user.email = form.cleaned_data["email"]

                user.save()
                employee.save()

                # New log if the salary has changed
                if new_log:
                    EmployeeLog.objects.create(
                        employee_id=employee,
                        event="C",
                        price_per_hour=form.cleaned_data["price_per_hour"])
                return HttpResponseRedirect('/employee/view/' + username + '/')
            else:
                # There are errors
                return render(
                    request, 'employee/employee_edit.html', {
                        'form': form,
                        'errors': errors,
                        'picture': employee.picture,
                        'username': username,
                        'pass_form': EmployeePasswordForm(),
                        'active': employee.user.is_active
                    })

        else:
            # Form is not valid
            return render(
                request, 'employee/employee_edit.html', {
                    'form': form,
                    'picture': employee.picture,
                    'errors': ['employeeCreation_formNotValid'],
                    'username': username,
                    'pass_form': EmployeePasswordForm(),
                    'active': employee.user.is_active
                })
    else:
        raise PermissionDenied
Exemplo n.º 3
0
def create(request,
           email_template_name='company/company_register_email.html',
           html_email_template_name='company/company_register_email.html'):
    """
    parameters/returns:
    form: el formulario con los datos de la compañía y el administrador de la compañía

    template:
    company_form.html
    """
    # If it's a GET request, return an empty form
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = RegistrationForm(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            errors = []

            # Check that the passwords match
            if not check_passwords(form):
                errors.append('passwordsDontMatch')

            # Check that the username is unique
            if not is_username_unique(form.cleaned_data["username"]):
                errors.append('companyRegister_usernameNotUnique')

            #Check password validation
            if not validate_pass(form.cleaned_data["password"]):
                errors.append('newPasswordInvalid')

            # Check that the admin email is unique
            if Company.objects.filter(
                    email=form.cleaned_data["company_email"]).exists():
                errors.append('companyRegister_companyEmailNotUnique')

            # Check that the admin email is unique
            if not is_email_unique(form.cleaned_data["admin_email"]):
                errors.append('companyRegister_adminEmailNotUnique')

            # Check that the CIF is unique
            if not is_cif_unique(form.cleaned_data["cif"]):
                errors.append('companyRegister_cifNotUnique')

            # Check that the short name is unique
            if get_or_none(Company,
                           short_name=form.cleaned_data["short_name"]):
                errors.append('company_short_name_duplicate')

            # Check that the image is OK
            if not check_image(form, 'logo'):
                errors.append('company_imageNotValid')

            if not form.cleaned_data["terms_agree"]:
                errors.append("agree_terms_error")

            if not errors:
                # process the data in form.cleaned_data as required
                # ...
                # redirect to a new URL:
                company = create_company(form)
                administrator = register_administrator(form, company)

                # This sends an information email to the company and to the admin

                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain

                use_https = True
                context = {
                    'domain': domain,
                    'site_name': site_name,
                    'admin': administrator,
                    'company': company.short_name,
                    'protocol': 'https' if use_https else 'http',
                    'html': True
                }

                send_mail('Metronus Info.', email_template_name,
                          [company.email, administrator.user.email],
                          html_email_template_name, context)

                # Login the administrator and send him to the dashboard
                logged_user = authenticate(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password'])
                login(request, logged_user)
                return HttpResponseRedirect("/dashboard/view")
            else:
                return render(request, 'company/company_register.html', {
                    'form': form,
                    'errors': errors
                })

    # if a GET (or any other method) we'll create a blank form
    else:
        form = RegistrationForm()
    return render(request, 'company/company_register.html', {'form': form})
Exemplo n.º 4
0
def edit(request):
    """
    url = administrator/edit/

    parameters/returns:
    form: formulario de edicion de datos de administrador

    template: administrator_edit.html
    """
    errors = []
    administrator = get_current_admin_or_403(request)

    if request.method == "GET":
        # Return a form filled with the administrator's data
        form = AdministratorForm(
            initial={
                'first_name': administrator.user.first_name,
                'last_name': administrator.user.last_name,
                'admin_email': administrator.user.email,
                'identifier': administrator.identifier,
                'phone': administrator.phone
            })
    elif request.method == "POST":
        # Process the received form
        form = AdministratorForm(request.POST, request.FILES)
        if form.is_valid():
            if not check_image(form, 'photo'):
                errors.append('company_imageNotValid')
            if not email_in_use_logged(form.cleaned_data['admin_email'],
                                       administrator):
                errors.append('companyRegister_adminEmailNotUnique')
            if not errors:
                # Update employee data
                administrator.identifier = form.cleaned_data["identifier"]
                administrator.phone = form.cleaned_data["phone"]

                if form.cleaned_data["photo"]:
                    administrator.picture = form.cleaned_data["photo"]

                # Update user data
                user = administrator.user
                user.first_name = form.cleaned_data["first_name"]
                user.last_name = form.cleaned_data["last_name"]
                user.email = form.cleaned_data["admin_email"]

                user.save()
                administrator.save()

                return HttpResponseRedirect('/company/view/')
            else:
                return render(
                    request, 'company/administrator_edit.html', {
                        'form': form,
                        'errors': errors,
                        'pass_form': EmployeePasswordForm(),
                        'picture': administrator.picture
                    })
        else:
            return render(
                request, 'company/administrator_edit.html', {
                    'form': form,
                    'errors': ['formNotValid'],
                    'pass_form': EmployeePasswordForm(),
                    'picture': administrator.picture
                })
    else:
        raise PermissionDenied

    return render(
        request, 'company/administrator_edit.html', {
            'form': form,
            'pass_form': EmployeePasswordForm(),
            'picture': administrator.picture
        })
Exemplo n.º 5
0
def edit(request):
    """
    Se escoge la comoañía correspondiente al administrador que la edita

    url = company/edit

    parameters/returns:
    form: formulario de edicion de datos de la compañía

    template: company_edit.html
    """

    # Check that the user is logged in and it's an administrator
    admin = get_current_admin_or_403(request)
    company = admin.company_id

    if request.method == "GET":
        # Return a form filled with the employee's data
        form = CompanyForm(
            initial={
                'visible_short_name': company.visible_short_name,
                'company_email': company.email,
                'company_phone': company.phone,
            })
    elif request.method == "POST":
        # Process the received form

        form = CompanyForm(request.POST, request.FILES)
        if form.is_valid():
            errors = []

            # Check that the image is OK
            if not check_image(form, 'logo'):
                errors.append('company_imageNotValid')
            # Check that the company email is unique
            if Company.objects.filter(
                    email=form.cleaned_data["company_email"]).exists(
                    ) and company.email != form.cleaned_data["company_email"]:
                errors.append('companyRegister_companyEmailNotUnique')

            if not errors:
                # Company data
                company.visible_short_name = form.cleaned_data[
                    "visible_short_name"]
                company.email = form.cleaned_data["company_email"]
                company.phone = form.cleaned_data["company_phone"]

                if form.cleaned_data["logo"]:
                    # Don't overwrite the current logo with an empty one
                    # if the administrator hasn't uploaded one in the form
                    company.logo = form.cleaned_data["logo"]

                company.save()

                return HttpResponseRedirect('/company/view/')
            else:
                return render(request, 'company/company_edit.html', {
                    'form': form,
                    'errors': errors,
                    'logo': company.logo
                })

    else:
        raise PermissionDenied

    return render(request, 'company/company_edit.html', {
        'form': form,
        'logo': company.logo
    })