Ejemplo n.º 1
0
        /// <summary>
        /// Преобразование DTO сотрудника в бизнес модель
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static BaseEmployee ToBaseEmployee(this Employee e)
        {
            var          position = e.Positions;
            BaseEmployee employee = default;

            switch (position)
            {
            case Positions.None:
                break;

            case Positions.Director:
                employee = new DirectorEmployee(e.Id, e.NamePerson, e.SurnamePerson, e.Department, e.BaseSalary);
                break;

            case Positions.Developer:
                employee = new StaffEmployee(e.Id, e.NamePerson, e.SurnamePerson, e.Department, e.BaseSalary);
                break;

            case Positions.Freelance:
                employee = new FreeLancerEmployee(e.Id, e.NamePerson, e.SurnamePerson, e.Department, e.BaseSalary);
                break;

            default:
                break;
            }
            return(employee);
        }
        public void Login_InvokeTwiceForOneLogin_ShouldReturnTrue(string login, string password)
        {
            //arrange
            var expectedEmployee = new StaffEmployee(login, 50000)
            {
                PasswordHash = password
            };

            var employeeRepositoryMock = new Mock <IEmployeeRepository>();

            employeeRepositoryMock.Setup(x =>
                                         x.GetEmployeeByLoginPassword(It.Is <string>(y => y == login),
                                                                      It.Is <string>(z => z == password)))
            .Returns(() => expectedEmployee);

            var service = new AuthService(employeeRepositoryMock.Object);

            //act
            var result = service.Login(login, password);

            result = service.Login(login, password);

            //assert
            Assert.IsNotEmpty(UserSession.Sessions);
            Assert.IsNotNull(UserSession.Sessions);
            Assert.IsTrue(UserSession.Sessions.Contains(expectedEmployee));
            Assert.IsTrue(result);
        }
Ejemplo n.º 3
0
        public int Create(string Number, int?ContractorID, int?ToStructureObjectID, int?FromStructureObjectID,
                          DateTime?Date, decimal DocumentSum, decimal PaySum, int DocumentTypeID, int?LinkedDocumentID, string Description,
                          int CurrencyID, string Address, int EnterpriseID)
        {
            int result = 1;

            int          userId = Compas.Logic.Security.CurrentSecurityContext.Identity.ID;
            WareDocument sr     = WareDocument.CreateWareDocument(1, DocumentSum, PaySum, DocumentTypeID, userId, DateTime.Now, CurrencyID, true);

            sr.Number                = Number;
            sr.ContractorID          = ContractorID;
            sr.ToStructureObjectD    = ToStructureObjectID;
            sr.FromStructureObjectID = FromStructureObjectID;
            sr.Date             = Date;
            sr.LinkedDocumentID = LinkedDocumentID;
            sr.Description      = Description;
            sr.Address          = Address;
            sr.EnterpriseID     = EnterpriseID;

            Logic.Staff.StaffEmployeeLogic staffLogic = new Staff.StaffEmployeeLogic(manager);
            StaffEmployee employee = staffLogic.GetByUserID(userId);

            if (employee != null)
            {
                sr.CreatedEmployeeID = employee.ID;
            }

            context.AddToWareDocuments(sr);
            return(result);
        }
Ejemplo n.º 4
0
        private void FillInfo()
        {
            if (DataGV.SelectedRows.Count > 0)
            {
                StaffEmployeePositionsLogic employeePositionsLogic = new StaffEmployeePositionsLogic(manager);
                StaffEmployeeLogic          employeeLogic          = new StaffEmployeeLogic(manager);
                SecurityUserRolesLogic      userRoles = new SecurityUserRolesLogic(manager);
                int employeeId = Convert.ToInt32(DataGV.SelectedRows[0].Cells["ID"].Value);
                PositionsLB.DataSource = employeePositionsLogic.GetPositionsByEmployeeID(employeeId).ToList();

                PositionsLB.DisplayMember = "Name";
                PositionsLB.ValueMember   = "ID";
                PositionsLB.Update();

                StaffEmployee employee = employeeLogic.Get(employeeId);
                if (employee.UserID != null)
                {
                    int userId = Convert.ToInt32(employee.UserID);
                    RolesLB.DataSource    = userRoles.GetAll(userId).Select(a => a.SecurityRole).ToList();
                    RolesLB.DisplayMember = "Name";
                    RolesLB.ValueMember   = "ID";
                    RolesLB.Update();
                }
            }
        }
Ejemplo n.º 5
0
        public void TrackTime_StaffEmployeeAdditionNotHimself_ShouldReturnFalse()
        {
            //arrange
            int     workingHourse = 8;
            string  login         = "******";
            decimal salary        = 40_000m;

            var employee = new StaffEmployee(login, salary);
            var timeLog  = new TimeLog
            {
                Date          = DateTime.Now.AddDays(1),
                WorkingHours  = workingHourse,
                EmployeeLogin = "******",
                Comment       = ""
            };

            UserSession.Sessions.Add(employee);

            _employeeRepositoryMock.Setup(x =>
                                          x.GetEmployee(It.Is <string>(y => y == login)))
            .Returns(new StaffEmployee(login, salary));

            //act
            var result = _service.TrackTime(timeLog, login);

            //assert
            _timeLogRepositoryMock.Verify(x => x.Add(timeLog), Times.Never);
            Assert.IsFalse(result);
        }
Ejemplo n.º 6
0
        private void Fill()
        {
            StaffEmployeeSalariesLogic salariesLogic = new StaffEmployeeSalariesLogic(manager);

            DataGV.AutoGenerateColumns = false;
            if (employeeId != null)
            {
                DataGV.DataSource = salariesLogic.GetViewByEmployeeID(Convert.ToInt32(employeeId));
            }
            else
            {
                DataGV.DataSource = salariesLogic.GetView();
            }
            StaffEmployeeLogic employees = new StaffEmployeeLogic(manager);

            if (employeeId != null)
            {
                StaffEmployee employee = employees.Get(Convert.ToInt32(employeeId));
                EmployeeL.Text = employee.LastName + " " + employee.FirstName + " " + employee.MiddleName;
            }
            else
            {
                EmployeeL.Text = "Всі працівники";
            }

            DataGV.Update();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Заполнение словаря параметров resolveContext значениями идентификаторов группы, пользователя, роли
        /// </summary>
        public void FillResolveContext(SessionContext sessionContext, BaseResolveContext resolveContext, Options options)
        {
            // Для повышения быстродействия значения идентификаторов можно закэшировать
            var           userId        = sessionContext.UserInfo.EmployeeId;
            var           unit          = sessionContext.UserInfo.Employee.Unit;
            var           unitId        = sessionContext.ObjectContext.GetObjectRef <StaffUnit>(unit).Id;
            StaffEmployee staffEmployee = sessionContext.ObjectContext.GetObject <StaffEmployee>(userId);
            IStaffService staffService  = sessionContext.ObjectContext.GetService <IStaffService>();
            StringBuilder roleIdList    = new StringBuilder();
            StringBuilder groupIdList   = new StringBuilder();

            foreach (StaffGroup group in staffService.FindEmployeeGroups(staffEmployee))
            {
                var groupId = sessionContext.ObjectContext.GetObjectRef <StaffGroup>(group).Id;
                groupIdList.Append(string.Concat(groupId, ";"));
            }
            foreach (StaffRole role in staffService.FindEmployeeRoles(staffEmployee))
            {
                var roleId = sessionContext.ObjectContext.GetObjectRef <StaffRole>(role).Id;
                roleIdList.Append(string.Concat(roleId, ";"));
            }

            resolveContext.Parameters.Add(Constants.ConditionTypes.UnitConditionType, unitId.ToString());
            resolveContext.Parameters.Add(Constants.ConditionTypes.RolesConditionType, roleIdList.ToString());
            resolveContext.Parameters.Add(Constants.ConditionTypes.GroupsConditionType, groupIdList.ToString());
        }
Ejemplo n.º 8
0
        private void FillData()
        {
            StaffEmployeeLogic employees = new StaffEmployeeLogic(manager);

            StaffEmployee employee = employees.Get(Convert.ToInt32(id));



            LastNameTB.Text   = employee.LastName;
            FirstNameTB.Text  = employee.FirstName;
            MiddleNameTB.Text = employee.MiddleName;

            CityTB.Text     = employee.City;
            StreetTB.Text   = employee.Street;
            BuildingTB.Text = employee.Building;
            FlatTB.Text     = employee.Flat;

            PhoneTB.Text    = employee.Phone;
            MobPhoneTB.Text = employee.MobPhone;

            HireDateDTP.Value = Convert.ToDateTime(employee.HireDate);

            if (employee.ReleaseDate != null)
            {
                ReleasedCB.Checked   = true;
                ReleaseDateDTP.Value = Convert.ToDateTime(employee.ReleaseDate);
            }
        }
Ejemplo n.º 9
0
        public UserRolesForm(int EmployeeID)
        {
            InitializeComponent();
            employeeId = EmployeeID;
            manager    = new ContextManager();
            StaffEmployeeLogic employeeLogic = new StaffEmployeeLogic(manager);
            StaffEmployee      employee      = employeeLogic.Get(EmployeeID);

            if (employee != null)
            {
                if (employee.UserID != null)
                {
                    userId = Convert.ToInt32(employee.UserID);
                    SecurityUsersLogic usersLogic = new SecurityUsersLogic(manager);
                    SecurityUser       user       = usersLogic.Get(Convert.ToInt32(userId));
                    LoginL.Text = user.Login;
                }
                else
                {
                    MessageBox.Show("Логін користувача відсутній");
                }
            }

            LFML.Text = employee.LastName + " " + employee.FirstName + " " + employee.MiddleName;


            FillRoles();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Возвращает сотрудника по группе или его заместителя.
        /// </summary>
        /// <param name="Context"></param>
        /// <param name="GroupName">Название группы.</param>
        /// <param name="GetDeputy">Возвращать заместителя при неактивности сотрудника в необходимой должности.</param>
        /// <returns></returns>
        public StaffEmployee GetEmployeeByGroup(ObjectContext Context, String GroupName, Boolean GetDeputy = true)
        {
            Staff      staff = Context.GetObject <Staff>(RefStaff.ID);
            StaffGroup Group = staff.Groups.FirstOrDefault <StaffGroup>(r => r.Name == GroupName);

            if (!Group.IsNull())
            {
                List <StaffEmployee> FindedEmployees = Group.Employees.ToList(); //Context.FindObjects<StaffEmployee>(new QueryObject(RefStaff.Employees.Position, Context.GetObjectRef<StaffPosition>(Position).Id)).ToList();
                if (FindedEmployees.Any())
                {
                    List <StaffEmployee> Employees = FindedEmployees.Where(emp => emp.Status != StaffEmployeeStatus.Discharged && emp.Status != StaffEmployeeStatus.Transfered && emp.Status != StaffEmployeeStatus.DischargedNoRestoration).ToList();
                    if (Employees.Any())
                    {
                        StaffEmployee Employee = Employees.FirstOrDefault(emp => emp.Status == StaffEmployeeStatus.Active);
                        if (!Employee.IsNull())
                        {
                            return(Employee);
                        }
                        else if (GetDeputy)
                        {
                            return(Employees.Select(emp => emp.GetDeputy()).FirstOrDefault(emp => !emp.IsNull()));
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 11
0
        public StaffEmployee GetEmployee(string lastName)
        {
            var           data          = File.ReadAllText(_path);
            var           dataRows      = data.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            StaffEmployee staffEmployee = null;

            foreach (var dataRow in dataRows)
            {
                if (dataRow.Contains(lastName))
                {
                    var dataMembers = dataRow.Split(_delimeter);

                    staffEmployee = new StaffEmployee
                    {
                        LastName = dataMembers[0],
                        Salary   = decimal.TryParse(dataMembers[1], out decimal salary) ? salary : 0
                    };

                    break;
                }
            }

            return(staffEmployee);
        }
    }
Ejemplo n.º 12
0
        public void TrackTime_ShouldReturnFalse(int workingHourse, string login)
        {
            //arrange
            decimal salary   = 70_000m;
            var     employee = new StaffEmployee(login, salary);
            var     timeLog  = new TimeLog
            {
                Date          = DateTime.Now,
                WorkingHours  = workingHourse,
                EmployeeLogin = employee.Login,
                Comment       = ""
            };

            UserSession.Sessions.Add(employee);

            _employeeRepositoryMock.Setup(x =>
                                          x.GetEmployee(It.Is <string>(y => y == login)))
            .Returns(new StaffEmployee(login, salary));


            //act
            var result = _service.TrackTime(timeLog, "Ivanov");

            //assert
            _timeLogRepositoryMock.Verify(x => x.Add(timeLog), Times.Never());
            Assert.IsFalse(result);
        }
        /// <summary>
        /// Получить асинхронно список всех сотрудников
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <BaseEmployee> > GetEmployeesListAsync()
        {
            //Создаем новый список сотрудников
            List <BaseEmployee> result = new List <BaseEmployee>();

            //Считываем все строки из файла в текстовый массив
            string[] dataLines = await base.ReadAsync();

            foreach (var line in dataLines)
            {
                //Получаем модель сотрудника в виде текстового массива
                string[] model = line.Split(DataSearator);
                //Преобразуем данные массива
                Guid.TryParse(model[0], out Guid id);
                string name          = model[1];
                string surnamePerson = model[2];
                var    department    = (Departments)Enum.Parse(typeof(Departments), model[3]);
                var    position      = (Positions)Enum.Parse(typeof(Positions), model[4]);
                decimal.TryParse(model[5], out decimal salary);

                //Создаем нового сотрудника и в зависимости от позиции создаем тип сотрудника
                BaseEmployee employee = null;
                switch (position)
                {
                case Positions.None:
                    employee = new StaffEmployee(id, name, surnamePerson, department, position, salary);
                    break;

                case Positions.Developer:
                    employee = new StaffEmployee(id, name, surnamePerson, department, salary);
                    break;

                case Positions.Director:
                    employee = new DirectorEmployee(id, name, surnamePerson, department, salary);
                    break;

                case Positions.Freelance:
                    employee = new FreeLancerEmployee(id, name, surnamePerson, department, salary);
                    break;

                default:
                    break;
                }

                //Если сотрудник создан, добавляем его в результирующий список
                if (employee != null)
                {
                    result.Add(employee);
                }
            }
            //Если результирующий список пустой, возвращаем null
            if (result.Count == 0)
            {
                return(null);
            }

            return(result);
        }
Ejemplo n.º 14
0
        public bool AddStaffEmployee(StaffEmployee employee)
        {
            bool isValid = !string.IsNullOrEmpty(employee.Login) && employee.Salary > 0;

            if (isValid)
            {
                _employeeRepository.AddStaff(employee);
            }

            return(isValid);
        }
Ejemplo n.º 15
0
        public bool AddEmployee(StaffEmployee staffEmployee)
        {
            bool isValid = !string.IsNullOrEmpty(staffEmployee.LastName) && staffEmployee.Salary > 0;

            if (isValid)
            {
                _employeeRepository.AddEmployee(staffEmployee);
            }

            return(isValid);
        }
        private void sendApproval(String role, StaffEmployee Performer, int performingType)
        {
            KindsCardKind kind = Context.GetObject <KindsCardKind>(new Guid("F841AEE1-6018-44C6-A6A6-D3BAE4A3439F"));    // Задание на согласование фин.документов

            DocsVision.BackOffice.ObjectModel.Task task = TaskService.CreateTask(kind);
            task.MainInfo.Name = "Согласование бухгалтерских документов " + Document.MainInfo.Name;
            task.Description   = "Согласование бухгалтерских документов " + Document.MainInfo.Name;
            string content = "Вы назначены " + role + " при согласовании бухгалтерских документов.";

            content = content + " Пожалуйста, отметьте свое решение кнопками Согласован или Не согласован и напишите соответствующий комментарий";
            task.MainInfo.Content   = content;
            task.MainInfo.Author    = this.StaffService.GetCurrentEmployee();
            task.MainInfo.StartDate = DateTime.Now;
            task.MainInfo.Priority  = TaskPriority.Normal;
            task.Preset.AllowDelegateToAnyEmployee = true;
            TaskService.AddSelectedPerformer(task.MainInfo, Performer);
            BaseCardSectionRow taskRow = (BaseCardSectionRow)task.GetSection(new System.Guid("20D21193-9F7F-4B62-8D69-272E78E1D6A8"))[0];

            taskRow["PerformanceType"] = performingType;
            addTaskRows(task);
            //добавляем ссылку на родительскую карточку
            TaskService.AddLinkOnParentCard(task, TaskService.GetKindSettings(kind), this.Document);
            //добавляем ссылку на задание в карточку
            TaskListService.AddTask(this.Document.MainInfo.Tasks, task, this.Document);
            //создаем и сохраняем новый список заданий
            TaskList newTaskList = TaskListService.CreateTaskList();

            Context.SaveObject <DocsVision.BackOffice.ObjectModel.TaskList>(newTaskList);
            //записываем в задание
            task.MainInfo.ChildTaskList = newTaskList;
            Context.SaveObject <DocsVision.BackOffice.ObjectModel.Task>(task);
            string oErrMessageForStart;
            bool   CanStart = TaskService.ValidateForBegin(task, out oErrMessageForStart);

            if (CanStart)
            {
                TaskService.StartTask(task);
                StatesState oStartedState = StateService.GetStates(kind).FirstOrDefault(br => br.DefaultName == "Started");
                task.SystemInfo.State = oStartedState;

                UIService.ShowMessage("Документ успешно отправлен пользователю " + Performer.DisplayString, "Отправка задания");
            }

            else
            {
                UIService.ShowMessage(oErrMessageForStart, "Ошибка отправки задания");
            }

            Context.SaveObject <DocsVision.BackOffice.ObjectModel.Task>(task);
        }
        public void GetStaffEmployeeReport_ShouldReturnReportWithOvertimeBill()
        {
            //arrange
            var timesheetRepositoryMock = new Mock <ITimeLogRepository>();
            var employeeRepositoryMock  = new Mock <IEmployeeRepository>();

            var totalBill  = 43_750; //  ((8/160 * 70_000) + (1 / 160 * 70000 * 2)) * 10
            var totalHours = 90;     // 9 * 10
            var salary     = 70_000m;
            var employee   = new StaffEmployee("Иванов", salary);

            timesheetRepositoryMock.Setup(x =>
                                          x.GetTimeLogs(It.Is <string>(l => l == employee.Login)))
            .Returns(() =>
            {
                var timelogs = new TimeLog[10];

                for (int i = 0; i < timelogs.Length; i++)
                {
                    timelogs[i] = new TimeLog
                    {
                        WorkingHours  = 9,
                        Date          = new DateTime(2021, 1, 1).AddDays(i),
                        EmployeeLogin = employee.Login,
                        Comment       = "Abstract comment"
                    };
                }

                return(timelogs);
            });

            employeeRepositoryMock.Setup(x
                                         => x.GetEmployee(It.Is <string>(l => l == employee.Login)))
            .Returns(() => employee);

            var service = new ReportService(timesheetRepositoryMock.Object, employeeRepositoryMock.Object);

            //act
            var result = service.GetEmployeeReport(employee.Login);

            //assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.TimeLogs);
            Assert.IsNotEmpty(result.TimeLogs);

            Assert.AreEqual(employee.Login, result.Employee.Login);
            Assert.AreEqual(totalHours, result.TotalHours);
            Assert.AreEqual(totalBill, result.Bill);
        }
Ejemplo n.º 18
0
        public void Add_ShouldReturnFalse(string lastName, int salary)
        {
            //arrange
            var staffEmployee = new StaffEmployee(lastName, salary);

            var employeeRepository = new Mock <IEmployeeRepository>();

            var service = new EmployeeService(employeeRepository.Object);

            //act
            var result = service.AddEmployee(staffEmployee);

            //assert
            employeeRepository.Verify(x => x.AddEmployee(It.IsAny <StaffEmployee>()), Times.Never);
            Assert.IsFalse(result);
        }
Ejemplo n.º 19
0
        public bool Login(string lastName)
        {
            if (string.IsNullOrEmpty(lastName))
            {
                return(false);
            }

            StaffEmployee employee        = _employeeRepository.GetEmployee(lastName);
            bool          IsEmployeeExist = (employee != null);

            if (IsEmployeeExist)
            {
                UserSession.Sessions.Add(lastName);
            }

            return(IsEmployeeExist);
        }
Ejemplo n.º 20
0
        public void Add_ShouldReturnTrue(string lastName, int salary)
        {
            //arrange
            var staffEmployee = new StaffEmployee(lastName, salary);

            var employeeRepository = new Mock <IEmployeeRepository>();

            employeeRepository.Setup(x => x.AddEmployee(staffEmployee)).Verifiable();

            var service = new EmployeeService(employeeRepository.Object);

            //act
            var result = service.AddEmployee(staffEmployee);

            //assert
            employeeRepository.Verify(x => x.AddEmployee(staffEmployee), Times.Once);
            Assert.IsTrue(result);
        }
Ejemplo n.º 21
0
        private void Fill()
        {
            StaffEmployeePositionsLogic positions = new StaffEmployeePositionsLogic(manager);

            DataGV.AutoGenerateColumns = false;
            DataGV.DataSource          = positions.GetByEmployeeID(employeeId).Select(a => new
            {
                a.ID,
                Name = a.StaffPosition.Name,
                a.StartDate,
                a.EndDate,
                a.Active
            }).ToList();
            StaffEmployeeLogic employees = new StaffEmployeeLogic(manager);
            StaffEmployee      employee  = employees.Get(employeeId);

            EmployeeL.Text = employee.LastName + " " + employee.FirstName + " " + employee.MiddleName;
            DataGV.Update();
        }
Ejemplo n.º 22
0
        public void SaveDocumentWithEmployees(WareDocument Document, StaffEmployee Employee, int?TeamID, string Mode)
        {
            //перевіряємо чи даний працівник закріплений за документом
            WareDocumentStaffDetail exists = (from a in context.WareDocumentStaffDetails
                                              where a.EmployeeID == Employee.ID & a.DocumentID == Document.ID
                                              select a).FirstOrDefault();

            if (exists == null)
            {
                WareDocumentStaffDetail d = new WareDocumentStaffDetail();
                d.StaffEmployee = Employee;
                d.TeamID        = TeamID;
                Document.WareDocumentStaffDetails.Add(d);
                context.AddToWareDocumentStaffDetails(d);
            }

            //if (Mode == "new")
            //    context.AddToWareDocuments(Document);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Конструктор формы заполнения журнала условий калибровки.
        /// </summary>
        /// <param name="Session">Пользовательская сессия DV.</param>
        /// <param name="Context">Объектный контекст.</param>
        /// <param name="JournalItemType">Тип справочника.</param>
        /// <param name="CabinetNumber">Номер кабинета.</param>
        public JournalForm(UserSession Session, ObjectContext Context, BaseUniversalItemType JournalItemType, Int32 CabinetNumber)
        {
            InitializeComponent();
            this.Session = Session;
            this.Context = Context;
            IBaseUniversalService baseUniversalService = Context.GetService <IBaseUniversalService>();

            this.CabinetNumber = CabinetNumber;

            staffEmployee = Context.GetCurrentEmployee();
            BaseUniversalItem NewItem = baseUniversalService.AddNewItem(JournalItemType);

            NewItem.Name     = "Каб. №" + CabinetNumber + ". Условия на " + DateTime.Today.ToShortDateString();
            this.Text        = "Каб. №" + (CabinetNumber == 237 ? 226 : 228) + ". Условия на " + DateTime.Today.ToShortDateString();
            itemCard         = baseUniversalService.OpenOrCreateItemCard(NewItem);
            NewItem.ItemCard = itemCard;
            Context.AcceptChanges();
            this.Date.DateTime = DateTime.Today;
            this.Employee.Text = staffEmployee.DisplayString;
        }
Ejemplo n.º 24
0
        public Employee GetEmployee(string lastName)
        {
            var      data     = File.ReadAllText(_path);
            var      dataRows = data.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            Employee employee = null;

            foreach (var dataRow in dataRows)
            {
                if (dataRow.Contains(lastName))
                {
                    var     dataMembers = dataRow.Split(_delimeter);
                    decimal salary      = 0;
                    decimal.TryParse(dataMembers[1], out salary);
                    var position = dataMembers[2];
                    switch (position)
                    {
                    case "Руководитель":
                        decimal bonus = 0;
                        decimal.TryParse(dataMembers[1], out bonus);
                        employee = new ChiefEmployee(lastName, salary, bonus);
                        break;

                    case "Штатный сотрудник":
                        employee = new StaffEmployee(lastName, salary);
                        break;

                    case "Фрилансер":
                        employee = new FreelancerEmployee(lastName, salary);
                        break;

                    default:
                        break;     // Выбрасывать исключение?
                    }


                    break;
                }
            }

            return(employee);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Конструктор формы заполнения журнала условий калибровки.
        /// </summary>
        /// <param name="Session">Пользовательская сессия DV.</param>
        /// <param name="Context">Объектный контекст.</param>
        /// <param name="JournalItemType">Тип справочника.</param>
        /// <param name="CurrentItem">Текущая строка справочника.</param>
        /// <param name="CabinetNumber">Номер кабинета.</param>
        public JournalForm(UserSession Session, ObjectContext Context, BaseUniversalItemType JournalItemType, BaseUniversalItem CurrentItem, Int32 CabinetNumber)
        {
            InitializeComponent();
            this.Session = Session;
            this.Context = Context;
            IBaseUniversalService baseUniversalService = Context.GetService <IBaseUniversalService>();

            staffEmployee = Context.GetCurrentEmployee();
            itemCard      = baseUniversalService.OpenOrCreateItemCard(CurrentItem);
            CardData    itemCardData = Session.CardManager.GetCardData(Context.GetObjectRef <BaseUniversalItemCard>(itemCard).Id);
            SectionData CalibrationConditionsSection = itemCardData.Sections[itemCardData.Type.Sections["CalibrationConditions"].Id];
            RowData     CalibrationConditionsRow     = CalibrationConditionsSection.FirstRow;

            this.Text          = "Каб. №" + (CabinetNumber == 237 ? 226 : 228) + ". Условия на " + DateTime.Today.ToShortDateString();
            this.Date.DateTime = (DateTime?)CalibrationConditionsRow.GetDateTime("Date") ?? DateTime.Today;
            this.Employee.Text = CalibrationConditionsRow.GetString("Employee") != null?Context.GetEmployeeDisplay(new Guid(CalibrationConditionsRow.GetString("Employee"))) : staffEmployee.DisplayString;

            this.Temperature.Value = (decimal?)CalibrationConditionsRow.GetDecimal("Temperature") ?? 0;
            this.Humidity.Value    = (decimal?)CalibrationConditionsRow.GetDecimal("Humidity") ?? 0;
            this.Pressure.Value    = (decimal?)CalibrationConditionsRow.GetDecimal("Pressure") ?? 0;
        }
Ejemplo n.º 26
0
        public void AddStaffEmployee_ShouldReturnFalse(string login, decimal salary)
        {
            //arrange
            StaffEmployee employee = new StaffEmployee(login, salary);

            var employeeRepositoryMock = new Mock <IEmployeeRepository>();

            employeeRepositoryMock.Setup(x =>
                                         x.AddStaff(It.Is <StaffEmployee>(y =>
                                                                          y == employee)));

            var service = new EmployeeService(employeeRepositoryMock.Object);
            //act
            var result = service.AddStaffEmployee(employee);

            //assert
            employeeRepositoryMock.Verify(x
                                          => x.AddStaff(employee), Times.Never);

            Assert.IsFalse(result);
        }
Ejemplo n.º 27
0
        public int Create(int DocumentID, int StateID, DateTime StartDate)
        {
            int result           = 1;
            WareDocumentState sr = new WareDocumentState();

            sr.DocumentID = DocumentID;
            sr.Active     = true;
            sr.StateID    = StateID;
            sr.StartDate  = StartDate;
            int userId = Compas.Logic.Security.CurrentSecurityContext.Identity.ID;

            Logic.Staff.StaffEmployeeLogic staffLogic = new Staff.StaffEmployeeLogic(manager);
            StaffEmployee employee = staffLogic.GetByUserID(userId);

            if (employee != null)
            {
                sr.EmployeeID = employee.ID;
            }
            context.WareDocumentStates.AddObject(sr);
            return(result);
        }
Ejemplo n.º 28
0
        public int Create(string Login, string Hash, bool Active, int?EmployeeID)
        {
            int          result = 1;
            SecurityUser sr     = SecurityUser.CreateSecurityUser(1, true);

            sr.Login  = Login;
            sr.Hash   = Hash;
            sr.Active = Active;
            if (EmployeeID != null)
            {
                int           employeeId = Convert.ToInt32(EmployeeID);
                StaffEmployee e          = (from a in context.StaffEmployees
                                            where a.ID == employeeId
                                            select a).FirstOrDefault();

                e.SecurityUser = sr;
            }
            context.AddToSecurityUsers(sr);

            result = sr.ID;
            return(result);
        }
Ejemplo n.º 29
0
        public StaffEmployee GetEmployee(string lastName)
        {
            var data = File.ReadAllText(PATH);

            StaffEmployee empoloyee = null;

            foreach (var dataRow in data.Split('\n'))
            {
                if (dataRow.Contains(lastName))
                {
                    var dataMembers = dataRow.Split(DELIMETER);

                    empoloyee = new StaffEmployee()
                    {
                        LastName = lastName,
                        Salary   = decimal.TryParse(dataMembers[1], out decimal Salary) ? Salary : 0m
                    };
                }
            }
            return(empoloyee);
        }
    }
        public void Login_NotValidArgument_ShouldReturnFalse(string login, string password)
        {
            //arrange
            var expectedEmployee = new StaffEmployee(login, 50000)
            {
                PasswordHash = password
            };

            var employeeRepositoryMock = new Mock <IEmployeeRepository>();

            employeeRepositoryMock.Setup(x =>
                                         x.GetEmployeeByLoginPassword(It.Is <string>(y => y == login),
                                                                      It.Is <string>(z => z == password)))
            .Returns(() => expectedEmployee);

            var service = new AuthService(employeeRepositoryMock.Object);

            //act
            var result = service.Login(login, password);

            //assert
            Assert.IsFalse(result);
        }