Example #1
0
        public async Task UpdateEmployee(EmployeeModel employee, CancellationToken token)
        {
            if (string.IsNullOrWhiteSpace(employee?.CompanyName))
            {
                throw new ArgumentException("Employee company name is required", nameof(employee));
            }
            if (employee.EmployeeId < 1)
            {
                throw new ArgumentException($"Invalid employee ID: {employee.EmployeeId}", nameof(employee));
            }

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

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

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

            var dbEmployee = await EmployeeRepository.GetEmployeeByEmployeeId(company.Id, employee.EmployeeId, token)
                             .ConfigureAwait(false);

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

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

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

            dbEmployee.FirstName         = employee.FirstName;
            dbEmployee.LastName          = employee.LastName;
            dbEmployee.SocialSecurity    = employee.SocialSecurity;
            dbEmployee.ManagerEmployeeId = employee.ManagerEmployeeId;
            dbEmployee.HireDate          = employee.HireDate;
            // Id, EmployeeId, and CompanyId are immutable after creation

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

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