public async Task Execute(ReassignEmployeeOperationRequest request) { if (request.EmployeeId == request.ManagerId) { throw new ApplicationException("An employee can't manage himself."); } bool isAuthorizedToReassign = await _authorizationContext.IsAuthorizedForEmployee(request.EmployeeId) && await _authorizationContext.IsAuthorizedForEmployee(request.ManagerId); if (!isAuthorizedToReassign) { throw new ApplicationException($"Not authorized to reassign employee {request.EmployeeId}"); } var employeeToAssign = await _employeeRepository.GetByIdAsync(request.EmployeeId); var myTeamTree = await _authorizationContext.GetTeamTree(); var reassignedEmployeeTeamTree = myTeamTree .FindAnyOrDefault( team => team.Employees.Select(employee => employee.ManagedTeam), team => team.Manager.Id == employeeToAssign.Id); var subordinates = reassignedEmployeeTeamTree?.GetAllEmployees() ?? new List <Domain.Entity.LearningCalendar.Employee>(); bool isNewManagerASubordinate = subordinates.Any(subordinate => subordinate.Id == request.ManagerId); if (isNewManagerASubordinate) { throw new ApplicationException("Can't reassign an employee to his subordinate"); } var ensureNewManagerHasTeamRequest = new EnsureManagerHasTeamRequest { ManagerId = request.ManagerId }; await _ensureManagerHasTeamOperation.Execute(ensureNewManagerHasTeamRequest); var newManager = await _employeeRepository.GetByIdAsync(request.ManagerId); employeeToAssign.Team = newManager.ManagedTeam; await _employeeRepository.UpdateAsync(employeeToAssign); }
private async Task <CreateEmployeeOperationResponse> CreateEmployee(IdentityUser identityUser, CreateEmployeeOperationRequest request) { var roleTask = _roleRepository .QuerySingleOrDefaultAsync(role => role.Title == request.Role); var managerId = (await _employeeRepository.GetByEmailAsync(request.ManagerEmail)).Id; var getTeamResponse = await _ensureManagerHasTeamOperation.Execute(new EnsureManagerHasTeamRequest { ManagerId = managerId }); Role role = await roleTask; var employee = new Domain.Entity.LearningCalendar.Employee { Identity = identityUser, Team = new Domain.Entity.LearningCalendar.Team { Id = getTeamResponse.TeamId }, FirstName = request.FirstName, LastName = request.LastName, Image = new Image { Value = request.ImageData }, Role = role ?? new Role { Title = request.Role } }; var limit = await _limitRepository.GetGlobalAsync(); limit.Employees.Add(employee); try { await _limitRepository.UpdateAsync(limit); } catch (DbUpdateException) { throw new EmailAlreadyUseException(); } return(new CreateEmployeeOperationResponse()); }