Example #1
0
def newEmployee(request):

    if request.method == 'POST':

        form = EmployeeForm(request.POST)

        if form.is_valid():

            username = form['username'].value()
            password = form['password'].value()
            first_name = form['first_name'].value()
            last_name = form['last_name'].value()

            new_user = User.objects.create_user(username=username,
                                                first_name=first_name,
                                                password=password,
                                                last_name=last_name)
            new_user.save()

            user = User.objects.get(username=username)
            obj = employee()
            obj.user_id = user.id
            obj.employment_date = request.POST['employment_date']
            obj.save()
            return redirect('backend:admin')

    else:
        form = EmployeeForm()
    return render(request, 'backend/add_new_employee.html', {'form': form})
Example #2
0
def create_employee_view(company_slug_to_id, **kwargs):
    corporation_id = kwargs['corporation_id']
    roles = RoleAccess(corporation_id=corporation_id,
                       company_id=company_slug_to_id). \
        roles_available_to_create_employee()

    roles_to_choose = [(i.id, i.name) for i in roles]

    form = EmployeeForm(roles_to_choose, corporation_id)

    next_page = request.args.get('next')

    if request.method == 'POST':
        if form.submit_employee.data and form.validate_on_submit():
            EmployeeAccess(company_id=company_slug_to_id,
                           first_name=form.first_name_employee.data.strip(),
                           email=form.email_employee.data.strip(),
                           role_id=form.role_employee.data.strip(),
                           corporation_id=corporation_id). \
                create_employee()
            flash('Your employee is now live!')
            if next_page:
                return redirect(next_page)
            form.first_name_employee.data = ''
            form.email_employee.data = ''
            form.role_employee.data = ''

        elif form.cancel_employee.data:
            if next_page:
                return redirect(next_page)
            form.first_name_employee.data = ''
            form.email_employee.data = ''
            form.role_employee.data = ''

    return render_template('create_employee.html', form=form)
Example #3
0
def employee_login():
    form = EmployeeForm()
    if form.validate_on_submit():
        employee_id = form.employee_id.data
        password = form.password.data
        db = get_db()
        employee = db.execute(
            ''' SELECT * FROM employees
                                WHERE employee_id = ?;''',
            (employee_id, )).fetchone()

        if employee is None:
            form.employee_id.errors.append("Unknown employee id")

        elif not check_password_hash(employee["password"], password):
            form.password.errors.append("Incorrect password!")
            eventLogger(employee_id, "got their password wrong")

        else:
            session.clear()
            session["employee_id"] = employee_id
            eventLogger(employee_id, "logged in")
            next_page = request.args.get("next")
            if not next_page:
                next_page = url_for("employee_home")
            return redirect(next_page)
    return render_template("employee_login.html", form=form)
Example #4
0
    def post(self, request, id):
        if request.user.is_superuser:
            empid = id
            form = EmployeeForm(request.POST)
            print "FORNM", request.POST
            emp = Employee.objects.get(id=empid)
            print emp
            edit_user = User.objects.filter(id=emp.usr_id)
            print "editttttttttttttt", edit_user.values('first_name')
            # form.emailedit=emp.usr_email
            if form.is_valid():

                print "valid"
                edit_user.first_name = request.POST.get('first_name'),
                edit_user.last_name = request.POST.get('last_name'),
                # edit_user.email=request.POST.get('email'),
                # edit_user.save()
                # emp.address=request.POST.get('address'),
                # emp.dob=request.POST.get('dob'),
                # emp.mobile_no=request.POST.get('mobile_no'),
                # emp.dept=request.POST.get('dept')
                # emp.save()
                form.save()

                context = {'form': form}
                return render(request, self.template_name, context)
            else:
                print "not cvalid", form.errors
                context = {'form': form}
                return render(request, self.template_name, context)
        else:
            return redirect('emp_home')
Example #5
0
def addemp():
    if 'username' in session:
        form = EmployeeForm(request.form)
        if request.method == 'POST':
            if form.validate():
                empdata = request.form
                firstname = empdata['firstname']
                midname = empdata['midname']
                lastname = empdata['lastname']
                address = empdata['address']
                email = empdata['email']
                mobile = empdata['mobile']
                gender = empdata['gender']
                designation = empdata['designation']
                name = firstname + " " + midname + " " + lastname
                sql = "INSERT INTO employees(name, email, mobile, gender, designation, address) VALUES(%s, %s, %s, %s, %s, %s);"
                conn = mysql.connect()
                cursor = conn.cursor()
                rows = cursor.execute(
                    sql, (name, email, mobile, gender, designation, address))
                conn.commit()
                if rows > 0:
                    flash('Employee Added Successfully')
                    return redirect(url_for('addemp'))
                else:
                    flash('Failed to added new employee!')
                    return redirect(url_for('addemp'))
                cursor.close()
                conn.close()
            else:
                return render_template('addemployee.html', form=form)
        elif request.method == 'GET':
            return render_template('addemployee.html', form=form)
    else:
        return redirect(url_for('login'))
Example #6
0
def employee():
    my_form = EmployeeForm()
    print("sucess")
    if my_form.validate_on_submit():
        # fetch the uploaded file
        file_csv = request.files.get('file_csv')
        print("valid")
        if file_csv:
            # get the file full path
            file_full_path = os.path.join(app.config['UPLOAD_FOLDER'], file_csv.filename)
            # save it in the server file system
            file_csv.save(file_full_path)
            # read that file in dataframe 
            df = pd.read_csv(file_full_path)
            #print(df)
            employee_list_raw = df.to_dict('records')
            #create a list for bulk insert later on
            employee_list = []
            for curr_employee in employee_list_raw:
                emp = Employee.from_dict(curr_employee)
                employee_list.append(emp)
            print("employee_list_count", len(employee_list)) 

            # save t0 DB
            db.session.bulk_save_objects(employee_list)
            db.session.commit()

            # test query
            e_list = Employee.query.limit(5).all()
            print("*******")
            print(e_list)
            print("*******")  


    return render_template('employee.html', title = 'Employee', my_form = my_form) # customize the title
def addemp():
    form = EmployeeForm(request.form)
    if request.method == 'POST':
        if form.validate():
            return 'Submitted!'
        else:
            return render_template('addemployee.html', form=form)
    elif request.method == 'GET':
        return render_template('addemployee.html', form=form)
Example #8
0
def add_employee(request):
	"""
	Add employee
	"""
	form = EmployeeForm(request, request.POST or None)
	if not form.is_valid():
		return TemplateResponse(request, 'mus/create_employee_form.html', {'employee_form': form})
	form.save()
	return HttpResponseRedirect('/employee/all/%d' %form.cleaned_data.get('company').pk)
Example #9
0
def Add_employee(request):
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            form.save()
            return msg(request,"Funcionario adicionado com Sucesso")
    else:
        form = EmployeeForm
    return render(request, 'add_employee.html', {'user':request.user,'form': form})
Example #10
0
File: views.py Project: kajun/ehsdb
def edit_employee(employee_id):

    employee = Employee.query.get(employee_id)
    form = EmployeeForm(obj=employee)
    form.populate_obj(employee)
    if form.validate_on_submit():
        db.session.commit()
        return redirect(url_for('employee_list'))
    return render_template('edit_employee.html', form=form, employee=employee)
Example #11
0
def edit_employee(request,
                  employee_id=None,
                  template="employees/employee_edit.html",
                  context=None):

    context = context or {}
    incidents = ['windscreen', 'smash and grab', 'road accident', 'vehicle']

    employee = Employee.objects.get(pk=employee_id) if employee_id else None

    vehicle_history = VehicleDriver.objects.filter(driver__id=employee_id)

    traffic_incidents = Incident.objects.filter(driver_id=employee_id,incident_type='traffic fine')\
                                 .values('id','reference_number','vehicle__registration_number','incident_date','cost','incident_type')\
                                 .order_by('incident_date')
    other_incidents = Incident.objects.filter(driver_id=employee_id,incident_type__in=incidents)\
                                 .values('id','reference_number','vehicle__registration_number','incident_date','cost','incident_type')\
                                 .order_by('incident_date')
    insurance_incidents = InsuranceClaim.objects.filter(driver=employee)\
                                                .values('id','insurance_reference_number','vehicle__registration_number','incident_date','quote_amount')\
                                                .order_by('incident_date')

    employee_form = EmployeeForm(request.POST or None, instance=employee)
    driving_licence_form = DrivingLicenceForm(request.POST or None,
                                              request.FILES or None)

    if u'save' in request.POST:
        if employee_form.is_valid():
            employee = employee_form.save(request.user)
            employee.save()

            has_errors = False
            submitted = request.POST.get('tab', '')
            if submitted == 'licence':
                has_errors = edit_driving_licence(driving_licence_form,
                                                  employee, has_errors,
                                                  request.user)

            if not has_errors:
                next = request.POST.get('next', '/')

                return HttpResponseRedirect(next)

    if u'cancel' in request.POST:
        next = request.POST.get('next', '/')
        return HttpResponseRedirect(next)

    context['employee'] = employee
    context['vehicle_history'] = vehicle_history
    context['employee_form'] = employee_form
    context['driving_licence_form'] = driving_licence_form
    context['traffic_incidents'] = traffic_incidents
    context['other_incidents'] = other_incidents
    context['insurnace_incidents'] = insurance_incidents

    return render(request, template, context)
Example #12
0
def cont4ct():
    pass
    form = EmployeeForm()
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('forms_employee.html', form=form)
    elif request.method == 'GET':
        return render_template('forms_employee.html', form=form)
    else:
        return render_template('form_data_employee.html')
Example #13
0
def edit(id):
    if 'username' in session:
        form = EmployeeForm(request.form)
        if request.method == 'POST':
            if form.validate():
                empdata = request.form
                firstname = empdata['firstname']
                midname = empdata['midname']
                lastname = empdata['lastname']
                address = empdata['address']
                email = empdata['email']
                mobile = empdata['mobile']
                gender = empdata['gender']
                designation = empdata['designation']
                name = firstname + " " + midname + " " + lastname
                sql = "UPDATE employees SET name = %s, email = %s, mobile = %s, gender = %s, designation = %s, address = %s WHERE id = %s;"
                conn = mysql.connect()
                cursor = conn.cursor()
                rows = cursor.execute(
                    sql,
                    (name, email, mobile, gender, designation, address, id))
                conn.commit()
                if rows > 0:
                    flash('Employee Updated Successfully')
                    return redirect(url_for('index'))
                else:
                    flash('Failed to update employee!')
                    return redirect(url_for('index'))
                cursor.close()
                conn.close()
            else:
                return render_template('edit.html', form=form, id=id)
        elif request.method == 'GET':
            sql = "SELECT * FROM employees WHERE id = %s;"
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sql, (id))
            data = cursor.fetchone()
            fullname = data[1].split(" ")
            ln = len(fullname)
            if ln > 2:
                form.firstname.data = fullname[0]
                form.midname.data = fullname[1]
                form.lastname.data = fullname[2]
            else:
                form.firstname.data = fullname[0]
                form.lastname.data = fullname[1]
            form.address.data = data[6]
            form.email.data = data[2]
            form.mobile.data = data[3]
            form.gender.data = data[4]
            form.designation.data = data[5]
            return render_template('edit.html', form=form, id=id)
    else:
        return redirect(url_for('login'))
Example #14
0
def employee_form(request):
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return render(request, 'finished.html')
        else:
            print form.errors
    else:
        form = EmployeeForm()
    return render(request, 'employee_form.html', {'form': form})
Example #15
0
def add_employee(request):
    """
	Add employee
	"""
    form = EmployeeForm(request, request.POST or None)
    if not form.is_valid():
        return TemplateResponse(request, 'mus/create_employee_form.html',
                                {'employee_form': form})
    form.save()
    return HttpResponseRedirect('/employee/all/%d' %
                                form.cleaned_data.get('company').pk)
Example #16
0
def edit_emp(emp_id):
    emp = Employee.query.get_or_404(emp_id)
    form = EmployeeForm(obj=emp)
    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts
    if form.validate_on_submit():
        emp.name = form.name.data
        emp.state = form.state.data
        emp.dept_code = form.dept_code.data
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template('edit-emp.html', form=form)
Example #17
0
def edit_employee(id):
    emp = Employee.query.get_or_404(id)
    form = EmployeeForm(obj=emp)
    depts = [('mktg', 'Marketing')]
    form.dept_code.choices = depts

    if form.validate_on_submit():
        emp.name = form.name.data
        emp.state = form.state.data
        emp.dept_code = form.dept_code.data
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template("edit_employee_form.html", form=form)
Example #18
0
File: views.py Project: kajun/ehsdb
def add_employee():

    form = EmployeeForm()
    if form.validate_on_submit():
        new_employee = Employee(firstname=form.firstname.data,
                                lastname=form.lastname.data,
                                department=form.department.data,
                                user_id=current_user.id)

        db.session.add(new_employee)
        db.session.commit()
        flash('New employee added successfully.')
        return redirect(url_for('employee_list'))
    return render_template('add_employee.html', form=form)
Example #19
0
def add_employee():
    form = EmployeeForm()
    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts
    if form.validate_on_submit():
        name = form.name.data
        state = form.state.data
        dept_code = form.dept_code.data
        emp = Employee(name=name, state=state, dept_code=dept_code)
        db.session.add(emp)
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template('add_employee_form.html', form=form)
Example #20
0
def employee():
    my_form = EmployeeForm()
    # convert to list

    if my_form.validate_on_submit():  # my_form.submitted()
        # file we are importing
        file_csv = request.files.get('file_csv')

        if file_csv:
            file_full_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                          file_csv.filename)
            # print("file_full_path", file_full_path)

            # save to upload folder
            file_csv.save(file_full_path)

            # load the data in the table using pandas
            df = pd.read_csv(file_full_path)

            # print("raw_data", df.iloc[0])

            # print("shape", df.shape)
            employee_list_raw = df.to_dict('records')

            # print("dictionary", employee_list_raw)

            employee_list = []
            for curr_emp in employee_list_raw:
                emp = Employee.from_dict(curr_emp)
                employee_list.append(emp)
                # db.session.add(emp)
                # db.session.commit()

            print("employee_list_count", len(employee_list))

            # save t0 DB
            db.session.bulk_save_objects(employee_list)
            db.session.commit()

            # test query
            e_list = Employee.query.limit(5).all()
            print("*******")
            print(e_list)
            print("*******")

        # send us to the display page
        # return redirect("/employee/" + str(my_data.id))

    return render_template('employee.html', my_form=my_form)
Example #21
0
    def get(self, request, id):
        if request.user.is_superuser:
            empid = id

            emp_obj = Employee.objects.get(pk=id)

            choices = [
                (dept.id, str(dept.name))
                for dept in Department.objects.filter(name=emp_obj.dept.name)
            ]
            print choices
            form = EmployeeForm(
                initial={
                    'first_name': emp_obj.usr.first_name,
                    'last_name': emp_obj.usr.last_name,
                    'address': emp_obj.address,
                    'dob': emp_obj.dob,
                    'mobile_no': emp_obj.mobile_no,
                    'dept': emp_obj.dept.id,
                    # 'username':emp_obj.usr.username,
                    # 'password':emp_obj.usr.password,
                    # 'gender':emp_obj.gender,
                    # 'email':emp_obj.usr.email,
                    # 'edit':True,
                })
            context = {'form': form}
            return render(request, self.template_name, context)
        else:
            return redirect('login')
Example #22
0
def edit_user(user_id):
    employee = Employee.query.get_or_404(user_id)
    # obj=employee prepopulates fields automatically based on employee data
    form = EmployeeForm(obj=employee)

    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts

    if form.validate_on_submit():
        employee.name = form.name.data
        employee.state = form.state.data
        employee.dept_code = form.dept_code.data

        db.session.commit()
        return redirect('/phones')
    else:
        return render_template('edit_employee_form.html', form=form)
Example #23
0
def create_employee(request):
    context = {}
    if request.method == 'POST':
        data = request.POST.get('form_data').split('&')
        data_dict = {}
        for d in data:
            data_dict[d.split("=")[0]] = urllib.unquote_plus(d.split("=")[1])
        form = EmployeeForm(data=data_dict)
        if form.is_valid():
            print "Data being sucessfully saved"
            form.save()
            return JsonResponse({'status': 'success'})
        else:
            error_dict = form.errors
            message = "Entered data is incorrect"
            return JsonResponse({
                'status': 'fail',
                'err_dict': error_dict,
                'err_message': message
            })
    else:
        form = EmployeeForm()
        context['form'] = form
        context['err_dict'] = {}
    return render(request, 'employee_form.html', context)
Example #24
0
def edit_employee(request, id):
    emp_id = id
    data = Employee.objects.get(id=emp_id)
    context = {}
    if request.method == 'POST':
        updated_data = request.POST.get('form_data').split('&')
        data_dict = {}
        for d in updated_data:
            data_dict[d.split("=")[0]] = urllib.unquote_plus(d.split("=")[1])
        print "Data coming in from form: ", data_dict
        form = EmployeeForm(data_dict, instance=data)
        if form.is_valid():
            print "Data being sucessfully updated"
            form.save()
            return JsonResponse({'status': 'success'})
        else:
            error_dict = form.errors
            message = "Entered data is incorrect"
            return JsonResponse({
                'status': 'fail',
                'err_dict': error_dict,
                'err_message': message
            })
    else:
        form = EmployeeForm(instance=data)
        context['form'] = form
        context['id'] = emp_id
    return render(request, 'update_employee.html', context)
Example #25
0
def add_employee():
    """Show a form to add new employee and handle form to add new employee"""
    # Get the appropriate form from forms.py
    form = EmployeeForm()

    # Make options for select input
    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts

    # For POST request
    if form.validate_on_submit():
        emp = Employee(name=form.name.data,
                       state=form.state.data,
                       dept_code=form.dept_code.data)
        db.session.add(emp)
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template('add_employee_form.html', form=form)
Example #26
0
def add_employee():

    form = EmployeeForm()

    # Adds a tuple to the dept_code.choices select form field ie. ('mktg', 'Marketing')
    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts
    if form.validate_on_submit():
        name = form.name.data
        state = form.state.data
        dept_code = form.dept_code.data

        new_employee = Employee(name=name, state=state, dept_code=dept_code)
        db.session.add(new_employee)
        db.session.commit()

        return redirect('/phones')
    else:
        return render_template('add_employee_form.html', form=form)
Example #27
0
def add_employee():
    form = EmployeeForm()
    depts = db.session.query(Department.dept_code, Department.dept_name)
    #pdb.set_trace()
    #depts = [('mktg','Marketing')]
    form.dept_code.choices = depts
    #raise

    if form.validate_on_submit():
        name = form.name.data
        state = form.state.data
        dept_code = form.dept_code.data

        emp = Employee(name=name, state=state, dept_code=dept_code)
        db.session.add(emp)
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template('add_employee.html', form=form)
Example #28
0
def add_interviewers(request):
    emp = employee.get_employee_by_user(userid=request.user.id)
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                interviewer = form.save()
                return render(
                    request,
                    'interviewer_detail.html',
                    {'interviewer': interviewer})
            except Exception as ex:
                print ex
    else:
        form = EmployeeForm()
    return render(
        request,
        'add_interviewer.html',
        {'form': form, 'cid': emp.company.id})
Example #29
0
def edit_employee(id):
    """Show form to edit employee and handle form to update existing employee"""
    # Get employee based on input id
    emp = Employee.query.get_or_404(id)

    # Get the appropriate form from forms.py and re-pupolate the fields on HTML
    form = EmployeeForm(obj=emp)

    # Make options for select input
    depts = db.session.query(Department.dept_code, Department.dept_name)
    form.dept_code.choices = depts

    # For POST request
    if form.validate_on_submit():
        # Update employee, get data from the form
        emp.name = form.name.data
        emp.state = form.state.data
        emp.dept_code = form.dept_code.data
        db.session.commit()
        return redirect('/phones')
    else:
        return render_template("edit_employee_form.html", form=form, emp=emp)
Example #30
0
def employee():
    form = EmployeeForm()
    pageTitle = "Employee Form"
    if request.method == 'POST':
        if form.validate() == False:
            flash('All fields are required.')
            return render_template('employee.html',
                                   form=form,
                                   pageTitle=pageTitle)
        else:
            print('Doing employeeadd')
            result = employeeAdd(request.form)
            if result['error'] == 1:
                return render_template('employee.html',
                                       form=form,
                                       pageTitle=pageTitle,
                                       processMessage=result['message'])
            else:
                return redirect(url_for('employeelist'))

            return render_template('employeeadd.html', formData=request.form)
    elif request.method == 'GET':
        return render_template('employee.html', form=form, pageTitle=pageTitle)
def update1(request):
	if request.POST:
		form = EmployeeForm(request.POST,request.FILES)
		print "hello1"
		if form.is_valid():
			form.save()
			print "hello"
			return HttpResponseRedirect('/employee/update')

	else:
		form = EmployeeForm()

	args = {}
	args.update(csrf(request))
	args['form'] = form
	return render_to_response('update.html', args)
Example #32
0
def create_employee(request, company_id):
    """
	View for creating employee in company
	"""
    company = Company.objects.get(pk=company_id)
    current_employee = Employee.objects.get(user__pk=request.user.pk)
    if not current_employee.isEnsoUser(
    ) and current_employee.company.pk != company.pk:
        logUnauthorizedAccess("User tried to create_employee", request)
        raise PermissionDenied()
    form = EmployeeForm(request, initial=dict(company=company))
    form.fields['manager'].queryset = Employee.objects.filter(is_manager=True,
                                                              company=company)
    form.fields[
        'development_plan_type'].queryset = DevelopmentPlanType.objects.filter(
            Q(company=company) | Q(company__isnull=True))
    return TemplateResponse(request, 'mus/create_employee_form.html', {
        'employee_form': form,
        'company': company
    })
Example #33
0
def employeelist():
    form = EmployeeForm()
    pageTitle = "Employee List"

    if request.method == 'GET':
        # Open database connection
        db = pymysql.connect("localhost", "localCentosUser", "Pa55word",
                             "employees")

        # prepare a cursor object using cursor() method
        cursor = db.cursor()

        # execute SQL query using execute() method.
        cursor.execute("SELECT VERSION()")

        # Fetch a single row using fetchone() method.
        data = cursor.fetchone()
        print("Database version : %s " % data)

        #now lets fetch records
        cursor.execute(
            "INSERT INTO employee (employee_name,username,user_password,email,gender,salary,active) SELECT * FROM (SELECT 'Darshan Patel','dpxx56','123123','*****@*****.**','M',565656,0) AS tmp WHERE NOT EXISTS (SELECT 1 FROM employee WHERE employee_name = 'Darshan Patel') LIMIT 1;"
        )
        db.commit()
        cursor.execute("SELECT * FROM employee;")
        data = cursor.fetchall()
        print('Total records: %d' % cursor.rowcount)

        # disconnect from server
        db.close()

        columnList = ('id', 'employee_name', 'username', 'user_password',
                      'email', 'gender', 'salary', 'active')

        return render_template('employeelist.html',
                               pageTitle=pageTitle,
                               data=data,
                               columnList=columnList)