Beispiel #1
0
        public Employee AddEmployee(string name, EmployeePosition position, float capacity, List <string> hobbies)
        {
            Employee employee;

            switch (position)
            {
            case EmployeePosition.DEV:
                employee = new Dev(name, capacity);
                employee.Hobbies.AddRange(hobbies);
                _employees.Add(employee);

                break;

            case EmployeePosition.Intern:
                employee = new Intern(name, capacity);
                employee.Hobbies.AddRange(hobbies);
                _employees.Add(employee);

                break;

            case EmployeePosition.QA:
            default:
                employee = new QA(name, capacity);
                employee.Hobbies.AddRange(hobbies);
                _employees.Add(employee);
                break;
            }
            return(employee);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            EmployeePosition employeePosition = _employeePositionService.GetById(id);

            _employeePositionService.Delete(employeePosition.ID);
            return(RedirectToAction("Index"));
        }
Beispiel #3
0
        public Employee(string id, string name, string employeePosition)
        {
            Id   = id;
            Name = name;

            switch (employeePosition)
            {
            case "Bartender":
                Position = EmployeePosition.Bartender;
                break;

            case "Waiter":
                Position = EmployeePosition.Waiter;
                break;

            case "Chef":
                Position = EmployeePosition.Chef;
                break;

            case "Manager":
                Position = EmployeePosition.Manager;
                break;

            default:
                throw new Exception("Wrong string input for employee position");
            }
        }
Beispiel #4
0
        public IHttpActionResult PutEmployeePosition(int id, EmployeePosition employeePosition)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != employeePosition.Id)
            {
                return(BadRequest());
            }

            employeePositionRepository.Update(employeePosition);

            try
            {
                employeePositionRepository.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!employeePositionRepository.Exists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(employeePositionRepository));
        }
 public EmployeePosition GetEmployeePositionInvalid()
 {
     Employees = new List <Employee>();
     Employees.Add(GetEmployeeFake());
     _employeePosition = new EmployeePosition(EP_DESCRIPTION_INVALID, EP_SALARY, EP_NUM_REFERENCE, Employees);
     return(_employeePosition);
 }
        public async Task <ActionResult> Delete(int?id)  //GET: /EmployeePositions/Delete/5
        {
            if (id == null)
            {
                return(BadRequestTextResult());
            }
            EmployeePosition employeePosition = await FindAsyncEmployeePosition(id.Value);

            if (employeePosition == null || employeePosition.AppDefault)
            {
                return(NotFoundTextResult());
            }

            DataContext.EmployeePositions.Remove(employeePosition);
            try
            {
                await DataContext.SaveChangesAsync(this);
            }
            catch (Exception ex)
            {
                var sb = new StringBuilder();
                sb.Append(MessageStrings.CanNotDelete);
                sb.Append(employeePosition.Position);
                sb.Append("<br/>");
                AppendExceptionMsg(ex, sb);

                return(StatusCodeTextResult(sb, HttpStatusCode.InternalServerError));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
        public EmployeePosition GetById(int id)
        {
            try
            {
                OpenConnection();
                string queryString = "select * from EmployeePosition where idEmployeePosition = " + id;

                MySqlCommand command = new MySqlCommand(queryString, conn);
                command.ExecuteNonQuery();
                MySqlDataAdapter adapter = new MySqlDataAdapter(command);

                DataTable dt = new DataTable();
                adapter.Fill(dt);

                EmployeePosition position = new EmployeePosition(int.Parse(dt.Rows[0].ItemArray[0].ToString()),
                                                                 dt.Rows[0].ItemArray[1].ToString(), long.Parse(dt.Rows[0].ItemArray[2].ToString()),
                                                                 long.Parse(dt.Rows[0].ItemArray[3].ToString()), long.Parse(dt.Rows[0].ItemArray[4].ToString()),
                                                                 int.Parse(dt.Rows[0].ItemArray[5].ToString()));
                return(position);
            }
            catch
            {
                return(new EmployeePosition());
            }
            finally
            {
                CloseConnection();
            }
        }
        public List <EmployeePosition> GetList()
        {
            try
            {
                OpenConnection();

                string          queryStr   = "select * from EmployeePosition where isDeleted = 0";
                MySqlCommand    cmd        = new MySqlCommand(queryStr, conn);
                MySqlDataReader dataReader = cmd.ExecuteReader();
                DataTable       dt         = new DataTable();
                dt.Load(dataReader);

                List <EmployeePosition> positionList = new List <EmployeePosition>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    EmployeePosition position = new EmployeePosition(int.Parse(dt.Rows[i].ItemArray[0].ToString()),
                                                                     dt.Rows[i].ItemArray[1].ToString(), long.Parse(dt.Rows[i].ItemArray[2].ToString()),
                                                                     long.Parse(dt.Rows[i].ItemArray[3].ToString()), long.Parse(dt.Rows[i].ItemArray[4].ToString()),
                                                                     int.Parse(dt.Rows[i].ItemArray[5].ToString()));

                    positionList.Add(position);
                }
                return(positionList);
            }
            catch
            {
                return(new List <EmployeePosition>());
            }
            finally
            {
                CloseConnection();
            }
        }
        public async Task <ActionResult> Create(EmployeePosition employeePosition, bool?modal)
        {
            if (ModelState.IsValid)
            {
                OnCreateSaving(employeePosition);

                DataContext.EmployeePositions.Add(employeePosition);
                await DataContext.SaveChangesAsync(this);

                OnCreateSaved(employeePosition);
                if (modal ?? false)
                {
                    return(Json(new { saved = true }));
                }
                return(RedirectToAction("Index"));
            }

            SetSelectLists(employeePosition);
            if (modal ?? false)
            {
                ViewBag.Modal = true;
                return(PartialView("_Create", employeePosition));
            }
            return(View(employeePosition));
        }
Beispiel #10
0
        public async Task <IActionResult> CreateAsync([FromBody] EmployeePosition employeePosition)
        {
            if (employeePosition == null)
            {
                var ex = new ArgumentException($"{nameof(employeePosition)} can't be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(employeePosition).IsValid)
            {
                var ex = new ArgumentException($"{nameof(employeePosition)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _employeePositionRepository.Add(employeePosition);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(employeePosition));
            }
            catch
            {
                var ex = new Exception($"Error while adding employee nameof{nameof(employeePosition)}");
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public override Employee OnModelCreate(EmployeeViewModel employeeViewModel)
        {
            Organization currentOrganization = employeeViewModel.GetOrganization(context);
            Division     division            = employeeViewModel.GetDivision(currentOrganization);
            Position     primaryPosition     = employeeViewModel.GetPrimaryPosition(division);

            Employee employee = new Employee()
            {
                FirstName         = employeeViewModel.FirstName,
                LastName          = employeeViewModel.LastName,
                MiddleName        = employeeViewModel.MiddleName,
                PrimaryPositionId = primaryPosition.Id,
                DivisionId        = division.Id,
                UserId            = Guid.Parse(employeeViewModel.UserId)
            };

            EmployeePosition employeePosition = new EmployeePosition()
            {
                Employee   = employee,
                EmployeeId = employee.Id,
                Position   = primaryPosition,
                PositionId = primaryPosition.Id
            };

            context.Entry(employeePosition).State = EntityState.Added;
            employee.EmployeePositions.Add(employeePosition);
            return(employee);
        }
Beispiel #12
0
 public Hourly(int employeeID, EmployeePosition employeePosition, EmployeeType type, double premium, double Rate)
     : base(employeePosition, type, employeeID, _employeePremium)
 {
     this.Rate = Rate;
     type      = employeeType;
     salary    = SalaryCalc();
 }
        public RepositoryActionsResult SetPositionToEmployee(int positionId, int employeeId)
        {
            var position = _mainContext.Positions.AsNoTracking().FirstOrDefault(pos => pos.PositionId == positionId);
            var employee = _mainContext.Employees.AsNoTracking().FirstOrDefault(emp => emp.EmployeeId == employeeId);

            var employeePositionInDb = _mainContext.EmployeePositions
                                       .FirstOrDefault(emp => emp.EmployeeId == employeeId && emp.PositionId == positionId);

            if (position == default || employee == default || employeePositionInDb != default)
            {
                return(RepositoryActionsResult.BadRequest);
            }
            else
            {
                var employeePosition = new EmployeePosition
                {
                    EmployeeId = employeeId,
                    PositionId = positionId
                };

                _mainContext.EmployeePositions.Add(employeePosition);
                _mainContext.SaveChanges();

                return(RepositoryActionsResult.Success);
            }
        }
        public static List <EmployeePosition> GetPosition()
        {
            var dbUtil    = new DatabaseManager();
            var positions = new List <EmployeePosition>();

            using (var conn = new SqlConnection(dbUtil.getSQLConnectionString("MainDB")))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandText    = "spMasGetEmployeePosition";
                    cmd.CommandTimeout = 180;

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var position = new EmployeePosition
                            {
                                PositionID  = ReferenceEquals(reader["intPositionID"], DBNull.Value) ? 0 : Convert.ToInt32(reader["intPositionID"]),
                                Description = ReferenceEquals(reader["strDescription"], DBNull.Value) ? String.Empty : Convert.ToString(reader["strDescription"])
                                ,
                                blnRequireIntIDMasBranchZone = object.ReferenceEquals(reader["blnRequireIntIDMasBranchZone"], DBNull.Value) ? false : Convert.ToBoolean(reader["blnRequireIntIDMasBranchZone"])
                            };

                            positions.Add(position);
                        }

                        return(positions);
                    }
                }
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("EmployeePositionId,Name")] EmployeePosition employeePosition)
        {
            if (id != employeePosition.EmployeePositionId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(employeePosition);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeePositionExists(employeePosition.EmployeePositionId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(employeePosition));
        }
Beispiel #16
0
 public virtual void Info()
 {
     Console.WriteLine("Сотрудник: ");
     Console.WriteLine("    Код сотрудника: {0}\n       Фамилия: {1}\n    Имя: {2}\n    Отчество: "
                       + "{3}\n    ИНН: {4}\n    Стаж работы: {5}",
                       ID_Employee, Surname, Name, Patronymic, INN, Experience);
     EmployeePosition.Info();
 }
 public ActionResult Edit(EmployeePosition employeePosition)
 {
     if (ModelState.IsValid)
     {
         _employeePositionService.Update(employeePosition);
         return(RedirectToAction("Index"));
     }
     return(View(employeePosition));
 }
Beispiel #18
0
 public Employee(int id, string name, string city, string email, string phone, EmployeePosition position)
 {
     this.id       = id;
     this.name     = name;
     this.city     = city;
     this.email    = email;
     this.phone    = phone;
     this.position = position;
 }
Beispiel #19
0
 public IActionResult Create([Bind("PositionId,PositionName,Salary")] EmployeePosition employeePosition)
 {
     if (ModelState.IsValid)
     {
         _repository.Create(employeePosition);
         return(RedirectToAction(nameof(Index)));
     }
     return(View(employeePosition));
 }
Beispiel #20
0
 /// <summary>
 /// Метод проверяет необходимость в блокировке сотрудника, находящихся на заданной должности(требуется при удалении или смене подразделения)
 /// И в случае необходимости лочит его, стирая PrimaryPositionId на сотруднике
 /// </summary>
 /// <param name="position"></param>
 private void CheckEmployeeForLock(EmployeePosition employeePosition, Position position)
 {
     if (employeePosition.Employee.PrimaryPositionId == position.Id)
     {
         employeePosition.Employee.PrimaryPositionId = null;
         employeePosition.Employee.Lock();
         new AccountRepository(context, resManager).CheckAccountsForLock(employeePosition.Employee);
         context.Employees.Update(employeePosition.Employee);
     }
 }
Beispiel #21
0
 public Employee(int id, string name, string surname, EmployeeStatus status, EmployeePosition position, string username, UserType type)
 {
     this.id       = id;
     this.name     = name;
     this.surname  = surname;
     this.status   = status;
     this.position = position;
     this.username = username;
     this.type     = type;
 }
 public bool Delete(EmployeePosition position)
 {
     if (position.Id < 0)
     {
         return(false);
     }
     SQLConnectionHandler.GetInstance()
     .Execute(SQLCommand.DeleteEmployeesPositions(position), true);
     return(true);
 }
Beispiel #23
0
        public int add(string fName, string lName,
            string address, string country, string phone, string email, // ICollection<MLogInfo> logInfos,
            int sId, EmployeePosition position)
        {
            // TODO: station id from StationCtr

            // cannot be empty list at Employee creation, because it requires Person ID
            // ICollection<MLogInfo> lis = new List<MLogInfo>();
            return dbEmployee.addNewRecord(fName, lName, address, country, phone, email, sId, position);
        }
        public async Task <IActionResult> Create([Bind("EmployeePositionId,Name")] EmployeePosition employeePosition)
        {
            if (ModelState.IsValid)
            {
                _context.Add(employeePosition);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(employeePosition));
        }
Beispiel #25
0
        /// <summary>
        /// Проверка на удаление основной должности
        /// </summary>
        /// <param name="positionViewModel"></param>
        private void CheckPrimaryPosition(Guid id)
        {
            EmployeePosition employeePosition = context.EmployeePositions
                                                .Include(emp => emp.Employee)
                                                .FirstOrDefault(i => i.Id == id);

            if (employeePosition.Employee.PrimaryPositionId == employeePosition.PositionId)
            {
                errors.Add("PrimaryPositionIsReadonly", resManager.GetString("PrimaryPositionIsReadonly"));
            }
        }
Beispiel #26
0
 public CreateEmployee(Guid id, string firstName, string secondName, string surname,
                       DateTime birthday, EmployeeStatus employeeStatus, EmployeePosition employeePosition)
 {
     Id               = id;
     FirstName        = firstName;
     SecondName       = secondName;
     Surname          = surname;
     Birthday         = birthday;
     EmployeeStatus   = employeeStatus;
     EmployeePosition = employeePosition;
 }
Beispiel #27
0
        public IHttpActionResult GetEmployeePosition(int id)
        {
            EmployeePosition employeePosition = employeePositionRepository.GetById(id);

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

            return(Ok(employeePosition));
        }
Beispiel #28
0
        public async Task <IActionResult> AddPositionToEmployee(AddPositionToEmployeeViewModel model)
        {
            ViewBag.EmpId    = model.EmployeeId;
            ViewBag.Position = context.Positions.Select(c => new SelectListItem
            {
                Text  = c.Name,
                Value = c.Name
            });

            if (ModelState.IsValid)
            {
                var emp = await context.Employees
                          .Where(c => c.Id == Convert.ToInt32(model.EmployeeId))
                          .FirstOrDefaultAsync();

                var position = await context.Positions.Where(c => c.Name == model.PositionValue).FirstOrDefaultAsync();

                if (position != null)
                {
                    var emplPosition = new EmployeePosition()
                    {
                        Position = position,
                        Employee = emp
                    };

                    await context.EmployeePositions.AddAsync(emplPosition);

                    int changesCount = await context.SaveChangesAsync();

                    if (changesCount > 0)
                    {
                        var appLogType = await context.AppLogTypes.Where(c => c.TypeName == "PositionToEmployeeAdded").FirstOrDefaultAsync();

                        var appLog = new AppLog()
                        {
                            Created    = DateTime.Now,
                            AppLogType = appLogType,
                            Message    = $"Для пользователя {emplPosition.Employee.Id} добавлена должность. ID: {emplPosition.PositionId}, наименование: {emplPosition.Position.Name}"
                        };

                        await context.AppLogs.AddAsync(appLog);

                        await context.SaveChangesAsync();
                    }
                    return(RedirectToAction("EmployeeDetails", "Employee", new { id = emplPosition.EmployeeId }));
                }
                else
                {
                    ModelState.AddModelError("", "Выберите должность");
                }
            }
            return(View());
        }
Beispiel #29
0
        public IHttpActionResult PostEmployeePosition(EmployeePosition employeePosition)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            employeePositionRepository.Insert(employeePosition);
            employeePositionRepository.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = employeePosition.Id }, employeePosition));
        }
Beispiel #30
0
 public int addNewRecord(string fName, string lName, string address, string country, string phone, string email, int sId, EmployeePosition position)
 {
     using (TransactionScope transaction = new TransactionScope((TransactionScopeOption.Required)))
     {
         try
         {
             int newId = -1;
             using (ElectricCarEntities context = new ElectricCarEntities())
             {
                 try
                 {
                     int max;
                     try {
                         max = context.People.Max(emp => emp.Id);
                     } catch {
                         max = 0;
                     }
                     newId = max + 1;
                     context.People.Add(new Employee()
                     {
                         Id = newId,
                         fName = fName,
                         lname = lName,
                         address = address,
                         country = country,
                         phone = phone,
                         email = email,
                         // together and after employee creation add logInfo and include returned
                         // person Id in there
                         // LoginInfoes = DLogInfo.buildLogInfos(logInfos),
                         pType = PType.Employee.ToString(),
                         sId = sId,
                         position = position.ToString(),
                     });
                     context.SaveChanges();
                 }
                 catch (Exception e)
                 {
                     throw new SystemException("Cannot add new Employee record " +
                          " with an error " + e.Message);
                 }
             }
             transaction.Complete();
             return newId;
         }
         catch (TransactionAbortedException e)
         {
             throw new SystemException("Cannot finish transaction for adding an Employee " +
                 " with an error " + e.Message);
         }
     }
 }
 private List <EmployeeViewModel> GetEmployeeFromDbWithWhereClause(EmployeePosition employeePosition, string keyword)
 {
     return((from a in _db.Employees
             where a.PositionEnum == employeePosition &&
             a.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase)
             select new EmployeeViewModel
     {
         Id = a.Id,
         Name = a.Name,
         Position = a.Position,
         PositionEnum = a.PositionEnum,
     }).ToList());
 }
Beispiel #32
0
        public void AddEmployee(
            string firstName,
            string lastName,
            string phone,
            string privatePhone,
            string email,
            EmployeePosition position,
            Address address)
        {
            var employee = Employee.Create(firstName, lastName, phone, privatePhone, email, position, address, this.Id);

            this.Employees.Add(employee);
        }
Beispiel #33
0
 public void update(int id,string fName, string lName,
     string address, string country, string phone, string email, ICollection<MLogInfo> logInfos,
     int sId,  EmployeePosition position)
 {
     dbEmployee.updateRecord(id, fName, lName, address, country, phone, email, logInfos, sId, position);
 }
Beispiel #34
0
 public void updateRecord(int id, string fName, string lName, string address, string country, string phone, string email, ICollection<MLogInfo> logInfos, int sId, EmployeePosition position)
 {
     using (TransactionScope transaction = new TransactionScope((TransactionScopeOption.Required)))
     {
         try
         {
             using (ElectricCarEntities context = new ElectricCarEntities())
             {
                 try
                 {
                     Employee emp = (Employee) context.People.Find(id);
                     emp.fName = fName;
                     emp.lname = lName;
                     emp.address = address;
                     emp.country = country;
                     emp.phone = phone;
                     emp.email = email;
                     // to be or not to be, cos LoginInfoes is 'virtual' in Customer EF model
                     emp.LoginInfoes = DLogInfo.buildLogInfos(logInfos, emp.LoginInfoes);
                     foreach (LoginInfo logInfo in emp.LoginInfoes)
                     {
                         logInfo.pId = emp.Id;
                         logInfo.Person = emp;
                     }
                     emp.position = position.ToString();
                     emp.sId = sId;
                     context.SaveChanges();
                 }
                 catch (Exception e)
                 {
                     throw new SystemException("Cannot update Employee record " + id
                         + " with message " + e.Message);
                 }
             }
             transaction.Complete();
         }
         catch (TransactionAbortedException e)
         {
             throw new SystemException("Cannot finish transaction for updating Employee no. " + id +
                 " with an error " + e.Message);
         }
     }
 }
        public void EmployeePositionTestByHybrid()
        {
            var company = Repository<Company>.FindFirst();
            company.Should().Not.Be.Null();

            var employeePosition = new EmployeePosition(company, "POS_0001");
            employeePosition.AddLocale(new CultureInfo("en"), new EmployeeCodeLocale {Name = "과장"});
            employeePosition.AddLocale(new CultureInfo("ko"), new EmployeeCodeLocale {Name = "Manager"});

            new PersistenceSpecification<EmployeePosition>(UnitOfWork.CurrentSession)
                .VerifyTheMappings(employeePosition);
        }