Beispiel #1
0
        public async Task <EmployeeModel> CreateEmployee(EmployeeModel newEmployee, CancellationToken token)
        {
            if (string.IsNullOrWhiteSpace(newEmployee?.CompanyName))
            {
                throw new ArgumentException("Employee company name is required", nameof(newEmployee));
            }

            Logger.LogInformation("Create new employee for company: {Company}", newEmployee.CompanyName);

            var company = await CompanyRepository.GetCompanyByName(newEmployee.CompanyName, token).ConfigureAwait(false);

            if (company == null)
            {
                // throw some kind of 'NotFound' exception to controller
                Logger.LogInformation("Company not found: {Company}", newEmployee.CompanyName);
                throw new Exception();
            }

            // if we had any logic here around preventing duplicates, like maybe two employees
            // can't have same SSN or same first or last name, we'd validate that here
            //var existing = await EmployeeRepository.GetEmployeesBySomeField(company.Id, field, token).ConfigureAwait(false);

            if (newEmployee.ManagerEmployeeId.HasValue)
            {
                // manager may not have been assigned yet, or maybe this is the CEO
                var manager = await EmployeeRepository
                              .GetEmployeeByManagerId(company.Id, newEmployee.ManagerEmployeeId.Value, token)
                              .ConfigureAwait(false);

                if (manager == null)
                {
                    // throw some kind of 'NotFound' exception to controller
                    Logger.LogInformation("Invalid manager employee ID: {ManagerEmployeeID}", newEmployee.ManagerEmployeeId.Value);
                    throw new Exception();
                }
            }

            int newEmployeeId = await GetNewEmployeeIdForCompany(company.Id, token).ConfigureAwait(false);

            var dbEmployee = new EmployeeInformation
            {
                CompanyId         = company.Id,
                EmployeeId        = newEmployeeId,
                FirstName         = newEmployee.FirstName,
                LastName          = newEmployee.LastName,
                SocialSecurity    = newEmployee.SocialSecurity,
                HireDate          = newEmployee.HireDate,
                ManagerEmployeeId = newEmployee.ManagerEmployeeId
            };

            await EmployeeRepository.CreateEmployee(dbEmployee, token).ConfigureAwait(false);

            Logger.LogInformation("New employee created for '{Company}'. ID: {EmployeeID}", company.CompanyName, newEmployee.EmployeeId);

            newEmployee.EmployeeId = newEmployeeId;
            return(newEmployee);
        }