Example #1
0
        public void Delete_Employee_Should_Set_NotActive()
        {
            var db = InitContext();
            var employeeService = InitService(db);

            var firstEmployee = new EmployeeUser()
            {
                Id        = 1,
                FirstName = "First Employee",
                IsActive  = true
            };

            var secondEmployee = new EmployeeUser()
            {
                Id        = 2,
                FirstName = "Second Employee",
                IsActive  = true
            };

            var thirdEmployee = new EmployeeUser()
            {
                Id        = 3,
                FirstName = "Third Employee",
                IsActive  = true
            };

            db.AddRange(firstEmployee, secondEmployee, thirdEmployee);
            db.SaveChanges();

            employeeService.Delete(1);

            db.EmployeeUsers.Should().ContainSingle(e => !e.IsActive);
        }
Example #2
0
        public static List <EmployeeUser> ToEmployeeModel(DbDataReader readers)
        {
            if (readers == null)
            {
                return(null);
            }
            var models = new List <EmployeeUser>();

            while (readers.Read())
            {
                var model = new EmployeeUser
                {
                    Id             = Convert.ToInt32(readers["Id"]),
                    UserName       = Convert.IsDBNull(readers["UserName"]) ? string.Empty : Convert.ToString(readers["UserName"]),
                    Designation    = Convert.IsDBNull(readers["Designation"]) ? string.Empty : Convert.ToString(readers["Designation"]),
                    CompanyId      = Convert.ToInt32(readers["CompanyId"]),
                    DepartmentId   = Convert.ToInt32(readers["DepartmentId"]),
                    PhoneNumber    = Convert.IsDBNull(readers["PhoneNumber"]) ? string.Empty : Convert.ToString(readers["PhoneNumber"]),
                    ImageFileName  = Convert.IsDBNull(readers["ImageFileName"]) ? string.Empty : Convert.ToString(readers["ImageFileName"]),
                    ImageFileId    = Convert.IsDBNull(readers["ImageFileId"]) ? string.Empty : Convert.ToString(readers["ImageFileId"]),
                    UserId         = Convert.IsDBNull(readers["UserId"]) ? string.Empty : Convert.ToString(readers["UserId"]),
                    DepartmentName = Convert.IsDBNull(readers["DepartmentName"]) ? string.Empty : Convert.ToString(readers["DepartmentName"]),
                    IsActive       = Convert.IsDBNull(readers["IsActive"]) ? (bool?)null : Convert.ToBoolean(readers["IsActive"]),
                };
                models.Add(model);
            }
            return(models);
        }
        public static void SeedUsers(UserManager <EmployeeUser> userManager)
        {
            if (userManager.FindByNameAsync("admin").Result == null)
            {
                EmployeeUser user = new EmployeeUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                user.FIO      = "admin";

                IdentityResult result = userManager.CreateAsync(user, "admin").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RolesNames.Admin).Wait();
                }
            }
            if (userManager.FindByNameAsync("user").Result == null)
            {
                EmployeeUser user = new EmployeeUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                user.FIO      = "user";

                IdentityResult result = userManager.CreateAsync(user, "user").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RolesNames.Employee).Wait();
                }
            }
        }
        protected void btnadd_Click(object sender, EventArgs e)
        {
            if (txtpwd.Text == txtcpwd.Text)
            {
                EmployeeUser emp = new EmployeeUser();
                emp.firstName       = txtfName.Text.ToString();
                emp.lastName        = txtlName.Text.ToString();
                emp.email           = txtemail.Text.ToString();
                emp.contactNum      = txtphn.Text.ToString();
                emp.address         = txtaddress.Text.ToString();
                emp.userId          = txtuser.Text.ToString();
                emp.password        = txtpwd.Text.ToString();
                emp.confirmPassword = txtcpwd.Text.ToString();
                emp.dob             = txtdate.Text.ToString();
                emp.role            = drpRole.SelectedValue;
                emp.hours           = statusRadio.SelectedValue;
                emp.status          = statusRadio.SelectedItem.ToString();

                if (insertEmployee(emp) > 0)
                {
                    lblErrorMsg.Text = "Employee Added Successfully!";
                }
            }
            else
            {
                lblErrorMsg.Text = "Passwords do not match!";
            }
        }
Example #5
0
        public JsonResult EmployeeUserGetInfo(int id)
        {
            EmployeeUser eu  = EmployeeUser.GetInfoById(id);
            object       obj = new { id = eu.Id, name = eu.Name, pid = eu.PId, did = eu.DId, spid = eu.SPId, uid = eu.UId, loginname = eu.LoginName, userlevel = eu.UserLevel };

            return(Json(obj, JsonRequestBehavior.AllowGet));
        }
Example #6
0
        public async Task <IdentityResult> SignUpCompanyAsync(CompanyRegistrationViewModel model, IUrlHelper Url, HttpContext httpContext)
        {
            Company company = new Company();

            company.CompanyName = model.CompanyName;
            _context.Companies.Add(company);
            await _context.SaveChangesAsync();

            var user = new EmployeeUser {
                UserName = model.Email, Email = model.Email, CompanyID = company.ID, PrimaryContact = true
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                company.Team.Employees.Add(user);
                await _context.SaveChangesAsync();

                await _userManager.AddToRoleAsync(user, AppRole.SHIPPER);

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: httpContext.Request.Scheme);
                await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                                                  $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            }
            return(result);
        }
Example #7
0
        public EmployeeUser Map(EmployeeUserDto dto)
        {
            EmployeeUser user = _context.Users.FirstOrDefault(x => x.Id == dto.Id);

            if (user == null)
            {
                user = new EmployeeUser();
                //user.Id = Guid.NewGuid().ToString();
            }

            user.FIO                  = dto.FIO;
            user.Email                = dto.Mail;
            user.AdditionalInfo       = dto.AdditionalInfo;
            user.PositionId           = dto.PositionId;
            user.Address              = dto.Address;
            user.BirthDate            = dto.BirthDate;
            user.Education            = dto.Education;
            user.PassportGiven        = dto.PassportGiven;
            user.PassportSeriesNumber = dto.PassportSeriesNumber;
            user.Salary               = dto.Salary;
            user.Level                = (Level)dto.Level;
            user.Experience           = dto.Experience;

            return(user);
        }
Example #8
0
        public async Task <IdentityResult> CreateEmployeeUserAsync(EmployeeCreateView model, Company company)
        {
            string          DEFAULT_NEW_EMPLOYEE_PASSWORD = company.CompanyName.ToUpper() + "123";;
            ApplicationUser employee = new ApplicationUser {
                Email = model.Email, CompanyID = company.ID, UserName = model.Email
            };
            var user = new EmployeeUser {
                UserName = model.Email, Email = model.Email, CompanyID = company.ID, PrimaryContact = false
            };
            var result = await _userManager.CreateAsync(user, DEFAULT_NEW_EMPLOYEE_PASSWORD);

            if (result.Succeeded)
            {
                company.Team.Employees.Add(user);
                await _context.SaveChangesAsync();

                await _userManager.AddToRoleAsync(user, AppRole.SHIPPER);

                //confirm email for the user
                await ConfirmUserEmail(user);

                await _emailSender.SendEmailAsync(model.Email, "You have been created an accout",
                                                  $"Please log into the system with the default password " + DEFAULT_NEW_EMPLOYEE_PASSWORD + " , please dont forget to change it ");
            }
            return(result);
        }
Example #9
0
        public async Task <IActionResult> RegisterAPI([FromBody] RegisterRequestViewModel model)
        {
            //var aVal = 0; var blowUp = 1 / aVal;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new EmployeeUser {
                UserName = model.Email, Email = model.Email, Name = model.Name, Position = model.Position
            };

            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(JwtClaimTypes.Email, user.Email));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(JwtClaimTypes.Name, user.Name));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("position", user.Position));

            //await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("role", Roles.Consumer));

            return(Ok("Registration successful!"));
        }
Example #10
0
        private bool TaskMatch(long taskId, EstimateDataDto dto)
        {
            TaskModel task = _context.TaskModels
                             .Include(x => x.TaskUsers)
                             .Where(x => x.Id == taskId).FirstOrDefault();

            foreach (var taskUser in task.TaskUsers)
            {
                EmployeeUser user = _context.Users.FirstOrDefault(x => x.Id == taskUser.UserId);
                if (UserMatch(user, dto))
                {
                    return(true);
                }
            }

            foreach (var child in _context.TaskModels.Where(x => x.ParentId == task.Id))
            {
                if (TaskMatch(child.Id, dto))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #11
0
        public EmployeeUser ValidateCredential(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(null);
            }
            var result = db.ValidateEmpUserCredentials(userName, password);

            if (result == null)
            {
                return(null);
            }
            var row  = result.FirstOrDefault();
            var user = new EmployeeUser
            {
                Email      = row.Email,
                EmployeeId = (int)row.EmployeeId,
                Id         = (int)row.Id,
                Password   = row.Password,
                Role       = (Role)row.RoleId,
                Status     = (Status)row.StatusId,
                UserName   = row.UserName
            };

            return(user);
        }
Example #12
0
        public TaskModelDto Add(TaskModelDto dto, EmployeeUser currentUser)
        {
            TaskModel TaskModel = Map(dto);

            TaskModel.CreatedDate = DateTime.Now;
            var saved = _context.TaskModels.Add(TaskModel);

            _context.TaskUsers.Add(new TaskUser()
            {
                TaskModelId = TaskModel.Id,
                UserId      = currentUser.Id
            });
            _context.SaveChanges();

            var estHist = new EstimateHistory()
            {
                Reason      = "Создание задачи",
                NewValue    = dto.EstimatedTime,
                OldValue    = 0,
                TaskModelId = saved.Entity.Id,
                UserId      = currentUser.Id,
                Date        = DateTime.Now,
            };

            _context.EstimateHistories.Add(estHist);
            _context.SaveChanges();
            return(Map(TaskModel));
        }
        public async Task <IActionResult> Update(string id)
        {
            EmployeeUser user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                //If the user wasn't found, return to index
                return(RedirectToAction("Index"));
            }

            EmployeeEditViewModel model = new EmployeeEditViewModel()
            {
                Id           = user.Id,
                FirstName    = user.FirstName,
                MiddleName   = user.MiddleName,
                LastName     = user.LastName,
                Email        = user.Email,
                PhoneNumber  = user.PhoneNumber,
                EGN          = user.EGN,
                Hired        = user.Hired,
                IsActive     = user.IsActive,
                Fired        = user.Fired,
                Reservations = user.Reservations
            };

            return(View(model));
        }
        public async Task <IActionResult> Fire(string id)
        {
            EmployeeUser employeeUser = _userManager.Users.FirstOrDefault(item => item.Id == id);

            if (employeeUser == null)
            {
                return(NotFound());
            }

            //If a "Fired" role does not exist, create it
            if (!await _roleManager.RoleExistsAsync(WebConstants.FiredRole))
            {
                await _roleManager.CreateAsync(new IdentityRole(WebConstants.FiredRole));
            }

            bool isAdmin = await _userManager.IsInRoleAsync(employeeUser, WebConstants.AdminRole);

            bool isFired = await _userManager.IsInRoleAsync(employeeUser, WebConstants.FiredRole);

            //We cannot fire other admins or already fired users
            if (!isAdmin && !isFired)
            {
                employeeUser.IsActive = false;
                employeeUser.Fired    = DateTime.Now;
                await _userManager.AddToRoleAsync(employeeUser, WebConstants.FiredRole);
            }


            return(RedirectToAction("Index"));
        }
 public void UploadEmployees(object sender, EventArgs e)
 {
     if (uploadCsvControl.HasFile)
     {
         string fileExt =
             System.IO.Path.GetExtension(uploadCsvControl.FileName);
         if (fileExt == ".csv" || fileExt == ".xlsx")
         {
             DataTable           dt           = new DataTable();
             List <EmployeeUser> allEmployees = new List <EmployeeUser>();
             try
             {
                 using (var reader = new StreamReader(uploadCsvControl.PostedFile.InputStream))
                     using (var csvReader = new CsvReader(reader))
                     {
                         while (csvReader.Read())
                         {
                             EmployeeUser data = csvReader.GetRecord <EmployeeUser>();
                             if (insertEmployee(data) <= 0)
                             {
                                 lblErrorMsg.Text = "Error adding employee!";
                                 break;
                             }
                         }
                     }
             }
             catch (Exception ex)
             {
                 Console.Write(ex.StackTrace);
             }
         }
     }
 }
Example #16
0
        public Payment MakePayment(EmployeeUser user, int month, int year)
        {
            var events = user.EmployeeEvent.Where(e => e.Start.Value.Month == month &&
                                                  e.Start.Value.Year == year);

            var hoursWorked = events.Where(e => e.Status == WorkStatus.Work).Select(e => e.CalculateWorkHours()).Sum();
            var paydate     = events.Min(e => e.Start) ?? new DateTime();

            if (paydate == DateTime.MinValue)
            {
                paydate = DateTime.Now;
            }

            Payment payment = new Payment
            {
                Month         = month,
                Year          = year,
                PayDate       = paydate,
                WorkHours     = hoursWorked,
                DaysWorked    = events.Where(e => e.Status == WorkStatus.Work).Count(),
                OverTimeHours = (decimal)events.Where(e => e.Status == WorkStatus.Work).Sum(e => e.Overtime),
                DaysAbsent    = events.Where(e => e.Status == WorkStatus.Absent).Count(),
                DaysHolidays  = events.Where(e => e.Status == WorkStatus.Holiday).Count(),
                Username      = user.UserName
            };

            payment.HolidayHours = payment.DaysHolidays * 8;
            payment.OverTimePay  = Math.Round(payment.OverTimeHours * user.OverTimeRate);
            payment.NormalPay    = Math.Round(payment.DaysWorked * user.PayRate, 2);
            payment.HolidayPay   = Math.Round(payment.DaysHolidays * user.PayRate, 2);
            payment.TotalPay     = Math.Round(payment.OverTimePay + payment.NormalPay + payment.HolidayPay, 2);
            payment.TaxPay       = Math.Round(payment.TotalPay * user.TaxRate / 100, 2);

            return(payment);
        }
Example #17
0
 public ActionResult EmployeeManager()
 {
     ViewData.Model        = EmployeeUser.GetList();
     ViewData["typelist"]  = EmployeeUser.GetSelector();
     ViewData["dtypelist"] = EmployeeUser.GetDSelector();
     ViewData["stypelist"] = EmployeeUser.GetSSelector();
     return(PartialView());
 }
Example #18
0
        public EmployeeUserDto Delete(string id)
        {
            EmployeeUser user = _context.Users.FirstOrDefault(x => x.Id == id);

            _context.Users.Remove(user);
            _context.SaveChanges();
            return(Map(user));
        }
Example #19
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            EmployeeUser employeeUser = await db.EmployeeUsers.FindAsync(id);

            db.EmployeeUsers.Remove(employeeUser);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
 public ActionResult Edit([Bind(Include = "Id,Name,Email,PhoneNumber,Status,State,City")] EmployeeUser emp)
 {
     if (ModelState.IsValid)
     {
         context.Edit(emp);
         return(RedirectToAction("Index"));
     }
     return(View(emp));
 }
Example #21
0
 public ActionResult Delete(int id)
 {
     using (EmployeeUserManagementModel db = new EmployeeUserManagementModel())
     {
         EmployeeUser empuser = db.EmployeeUsers.Where(x => x.userID == id).FirstOrDefault <EmployeeUser>();
         db.EmployeeUsers.Remove(empuser);
         db.SaveChanges();
         return(Json(new { success = true, message = "Employee deleted successfully" }, JsonRequestBehavior.AllowGet));
     }
 }
Example #22
0
        public static async Task <int> AddEmployeeUserAsync(eStoreDbContext db, string UserName, int EmployeeId)
        {
            //  UserName = RemoveWhiteSpace(UserName);

            EmployeeUser user = new EmployeeUser {
                EmployeeId = EmployeeId, IsWorking = true                                   /*, UserName = UserName*/
            };
            await db.EmployeeUsers.AddAsync(user);

            return(await db.SaveChangesAsync());
        }
        public ActionResult store(EmployeeUserViewModel euViewModel)
        {
            //Get Current UserName
            int id = Convert.ToInt32(User.Identity.Name);
            //Current Compamy
            company find_company = new DBContext().companies.ToList().Find(x => x.user_id == id);

            //Check Model state is valid or not
            if (ModelState.IsValid)
            {
                //Check if already exists
                if (new DBContext().employee_users.ToList().FindAll(x => x.employee_id == euViewModel.VM_EMPLOYEEUSER.employee_id).Count > 0)
                {
                    //Delete The EmployeeUser
                    EmployeeUser existingEmployeeUser = new DBContext().employee_users.ToList().Find(x => x.employee_id == euViewModel.VM_EMPLOYEEUSER.employee_id);
                    using (var contxt = new DBContext())
                    {
                        contxt.Entry(existingEmployeeUser).State = EntityState.Deleted;
                        contxt.SaveChanges();
                    }
                }
                //Add new EmployeeUser
                using (var contxt = new DBContext())
                {
                    //Set Datetime
                    //EmployeeMdl.created_at = DateTime.Now;
                    //set comapmny id
                    //euViewModel.VM_EMPLOYEE.company_id = find_company.id;
                    //Add New EmployeeUser
                    EmployeeUser employeeUser = new EmployeeUser
                    {
                        employee_id = euViewModel.VM_EMPLOYEEUSER.employee_id,
                        user_id     = euViewModel.VM_EMPLOYEEUSER.user_id
                    };
                    contxt.employee_users.Add(employeeUser);
                    contxt.SaveChanges();
                }
                //Set temp data Success registration message
                TempData["message"] = Utility.SUCCESS_MESSAGE + "Employee Assigned Successfully";

                return(RedirectToAction("index"));
            }

            else
            {
                string errors = errorstate.errors(ModelState);
                //Set temp data for wrong credentials
                TempData["message"] = Utility.FAILED_MESSAGE + "" + errors;

                String param_id = euViewModel.VM_EMPLOYEEUSER.employee_id.ToString();
                //redirect back to assign page
                return(RedirectToAction("assign", new { empID = param_id }));
            }
        }
Example #24
0
        public async Task <ActionResult> Edit([Bind(Include = "userID,fname,lname,username,email,password")] EmployeeUser employeeUser)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employeeUser).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(employeeUser));
        }
Example #25
0
        private void addServicesToEmployee(RegisterEmployeeVM _RegisterEmployee, EmployeeUser _userEmployee)
        {
            List <string> serviceList = _RegisterEmployee.listaServiciosId.Split(',').ToList();

            foreach (var serviceId in serviceList)
            {
                Guid id      = Guid.Parse(serviceId);
                var  service = _queries.GetServiceIncludeApplicationUserFirstOrDefault(id);
                _userEmployee.ServiceLst.Add(service);
            }
        }
Example #26
0
        public ActionResult Edit(int id)
        {
            ViewBag.Head = "Manage Employee";
            ViewBag.Form = "Employees Updation";

            EmployeeUser model = new EmployeeUser();

            model = _rep.Get(id);

            return(View(model));
        }
Example #27
0
 public ActionResult EmployeeUserProc(int id, string name, int pid, int did, int spid, string loginname, int userlevel)
 {
     if (id == 0)
     {
         EmployeeUser.AddInfo(new EmployeeUser(name, pid, did, spid, loginname, userlevel));
     }
     else
     {
         EmployeeUser.UpdateInfo(new EmployeeUser(id, name, pid, did, spid, loginname, userlevel));
     }
     return(RedirectToAction("EmployeeManager"));
 }
Example #28
0
        public async Task <ActionResult> Create([Bind(Include = "userID,fname,lname,username,email,password")] EmployeeUser employeeUser)
        {
            if (ModelState.IsValid)
            {
                db.EmployeeUsers.Add(employeeUser);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(employeeUser));
        }
Example #29
0
        public EmployeeUserDto Add(EmployeeUserDto dto)
        {
            EmployeeUser user = Map(dto);

            user.UserName = user.FIO;
            user.Email    = dto.Mail;
            var res = _userManager.CreateAsync(user, user.FIO).Result;

            res = _userManager.AddToRoleAsync(user, dto.Role).Result;
            _context.SaveChanges();
            return(Map(user));
        }
Example #30
0
        private EmployeeUser setEmployeesAttributes(RegisterEmployeeVM _RegisterEmployee)
        {
            var _userEmployee = new EmployeeUser();

            _userEmployee.UserName = _RegisterEmployee.email;
            _userEmployee.Email    = _RegisterEmployee.email;
            _userEmployee.Name     = _RegisterEmployee.Nombre;
            var Employer = _queries.GetApplicationUserIncludeServiceLst(_RegisterEmployee.idEmpleador);

            _userEmployee.EmployedBy = Employer;
            return(_userEmployee);
        }
 /// <summary>
 /// 验证用户名和密码。
 /// </summary>
 /// <param name="userSign">用户账号。</param>
 /// <param name="password">用户密码。</param>
 /// <param name="err">异常错误信息。</param>
 /// <returns>如果用户名和密码有效,则返回用户信息;否则返回null。</returns>
 public IUser UserAuthorizationVerification(string userSign, string password, out string err)
 {
     try
     {
         UserInfo userInfo = null;
         CallResult result = this.poxy.UserAuthorizationVerification(userSign, password, out userInfo);
         err = result.ResultMessage;
         if (result.ResultCode == 0 && userInfo != null)
         {
             EmployeeUser user = new EmployeeUser();
             user.CurrentUserID = userInfo.CurrentUserID;
             user.CurrentUserName = userInfo.CurrentUserName;
             return user;
         }
         return null;
     }
     catch (Exception e)
     {
         this.log.CreateErrorLog(err = e.Message);
         throw e;
     }
 }
 public bool UpdateEmployee(EmployeeUser user)
 {
     bool canUpdate = (_employeeRepository.GetById(user.Id) != null);
     if (canUpdate)
     {
         _employeeRepository.Upsert(user);
     }
     return canUpdate;
 }
 public EmployeeUser CreateEmployee(string login, string password, string employeeId)
 {
     var employeeUser = new EmployeeUser(login, password, employeeId);
     _employeeRepository.Upsert(employeeUser);
     return employeeUser;
 }