Ejemplo n.º 1
0
        public async Task <String> GetAppId(string name, string requestId = "")
        {
            _logger.LogInformation($"RequestId: {requestId} - SetupService_GetAppId called.");

            //get groupID
            bool    check     = true;
            dynamic jsonDyn   = null;
            var     groupName = WebUtility.UrlEncode(name);
            var     options   = new List <QueryParam>();

            options.Add(new QueryParam("filter", $"startswith(displayName,'{groupName}')"));
            while (check)
            {
                var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "");

                jsonDyn = groupIdJson;
                JArray jsonArray = JArray.Parse(jsonDyn["value"].ToString());
                if (jsonArray.Count() > 0)
                {
                    if (!String.IsNullOrEmpty(jsonDyn.value[0].id.ToString()))
                    {
                        check = false;
                    }
                }
            }
            var groupID = String.Empty;

            groupID = jsonDyn.value[0].id.ToString();
            var respose = await _graphTeamsAppService.GetAppIdAsync(groupID);

            return(respose);
        }
Ejemplo n.º 2
0
        public async Task CreateProposalManagerTeamAsync(string name, string requestId = "")
        {
            _logger.LogInformation($"RequestId: {requestId} - SetupService_CreateProposalManagerTeamAsync called.");

            try
            {
                await _graphTeamsAppService.CreateTeamAsync(name, name + "team");

                //get groupID
                bool    check           = true;
                dynamic jsonDyn         = null;
                var     opportunityName = WebUtility.UrlEncode(name);
                var     options         = new List <QueryParam>();
                options.Add(new QueryParam("filter", $"startswith(displayName,'{opportunityName}')"));
                while (check)
                {
                    var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                    jsonDyn = groupIdJson;
                    JArray jsonArray = JArray.Parse(jsonDyn["value"].ToString());
                    if (jsonArray.Count() > 0)
                    {
                        if (!String.IsNullOrEmpty(jsonDyn.value[0].id.ToString()))
                        {
                            check = false;
                        }
                    }
                }
                var groupID = String.Empty;
                groupID = jsonDyn.value[0].id.ToString();

                //get user Id
                string objectId = _userContext.User.FindFirst(AzureAdConstants.ObjectIdClaimType).Value;
                await _graphUserAppService.AddGroupMemberAsync(objectId, groupID, requestId);

                //Create channels
                await _graphTeamsAppService.CreateChannelAsync(groupID, "Configuration", "Configuration Channel");

                await _graphTeamsAppService.CreateChannelAsync(groupID, "Administration", "Administration Channel");
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - SetupService_CreateProposalManagerTeamAsync error: {ex}");
                throw;
            }
        }
Ejemplo n.º 3
0
        private async Task <bool> checkADGroupNameinAADAsync(string adGroupName, string requestId = "")
        {
            bool flag = false;

            try
            {
                //bug fix
                if ("aud" == adGroupName.Substring(0, 3).ToLower())
                {
                    flag = true;
                }
                else
                {
                    var options = new List <QueryParam>();
                    //Granular Permission Change :  Start
                    options.Add(new QueryParam("filter", $"startswith(displayName,'{adGroupName}')"));
                    var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                    dynamic jsonDyn = groupIdJson;
                    if (jsonDyn.value.HasValues)
                    {
                        var id = "";
                        id = jsonDyn.value[0].id.ToString();
                        if (!string.IsNullOrEmpty(id))
                        {
                            flag = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - RoleMappingRepo_CreateItemAsync error: {ex}");
            }

            return(flag);
        }
        private async Task <List <UserProfile> > GetUsersListAsync(string requestId = "")
        {
            try
            {
                if (_usersList?.Count == 0)
                {
                    var roles = await _roleRepository.GetAllAsync(requestId);

                    foreach (var role in roles)
                    {
                        var userRole = Role.Empty;
                        userRole.Id              = role.Id;
                        userRole.DisplayName     = role.DisplayName;
                        userRole.AdGroupName     = role.AdGroupName;
                        userRole.TeamsMembership = role.TeamsMembership;
                        userRole.Permissions     = (
                            from permission in role.Permissions
                            select new Permission {
                            Name = permission.Name, Id = permission.Id
                        }
                            ).ToList();

                        var options = new List <QueryParam>
                        {
                            new QueryParam("filter", $"startswith(displayName,'{role.AdGroupName}')"),
                            new QueryParam("$expand", "members")
                        };

                        dynamic jsonDyn = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                        if (jsonDyn.value.HasValues)
                        {
                            userRole.Id = jsonDyn.value[0].id.ToString();

                            foreach (var member in jsonDyn.value[0]["members"])
                            {
                                var user = UserProfile.Empty;
                                user = _usersList.Find(x => x.Id == member["id"].ToString());

                                if (user != null)
                                {
                                    _usersList.Remove(user);
                                }
                                else
                                {
                                    user    = UserProfile.Empty;
                                    user.Id = member["id"].ToString();
                                }

                                user.DisplayName = member["displayName"].ToString();
                                if (user.Fields == null)
                                {
                                    user.Fields = UserProfileFields.Empty;
                                }
                                user.Fields.Mail = member["mail"].ToString();
                                user.Fields.UserPrincipalName = member["userPrincipalName"].ToString();
                                user.Fields.Title             = member["jobTitle"].ToString() ?? String.Empty;

                                // Check if user already has the role
                                var existingRole = user.Fields.UserRoles.Find(x => x.Id == userRole.Id);
                                if (existingRole == null)
                                {
                                    user.Fields.UserRoles.Add(userRole);
                                }

                                _usersList.Add(user);
                            }
                        }
                    }
                }

                return(_usersList);
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - GetUsersListAsync Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - GetUsersListAsync Service Exception: {ex}");
            }
        }
        private async Task <List <UserProfile> > GetUsersListAsync(string requestId = "")
        {
            try
            {
                if (_usersList?.Count == 0)
                {
                    var roleMappings = await _roleMappingRepository.GetAllAsync(requestId);

                    foreach (var role in roleMappings)
                    {
                        var userRole = Role.Empty;
                        userRole.DisplayName = role.RoleName;
                        userRole.AdGroupName = role.AdGroupName;

                        var options = new List <QueryParam>();
                        options.Add(new QueryParam("filter", $"startswith(displayName,'{userRole.AdGroupName}')"));
                        var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                        dynamic jsonDyn = groupIdJson;
                        if (jsonDyn.value.HasValues)
                        {
                            userRole.Id = jsonDyn.value[0].id.ToString();

                            var groupMembersJson = await _graphUserAppService.GetGroupMembersAsync(userRole.Id, requestId);

                            JArray membersJsonArray = JArray.Parse(groupMembersJson["value"].ToString());

                            foreach (var member in membersJsonArray)
                            {
                                var user = UserProfile.Empty;
                                user = _usersList.Find(x => x.Id == member["id"].ToString());

                                if (user != null)
                                {
                                    _usersList.Remove(user);
                                }
                                else
                                {
                                    user    = UserProfile.Empty;
                                    user.Id = member["id"].ToString();
                                }

                                user.DisplayName = member["displayName"].ToString();
                                if (user.Fields == null)
                                {
                                    user.Fields = UserProfileFields.Empty;
                                }
                                user.Fields.Mail = member["mail"].ToString();
                                user.Fields.UserPrincipalName = member["userPrincipalName"].ToString();
                                user.Fields.Title             = member["jobTitle"].ToString() ?? String.Empty;

                                // Check if user already has the role
                                var existingRole = user.Fields.UserRoles.Find(x => x.Id == userRole.Id);
                                if (existingRole == null)
                                {
                                    user.Fields.UserRoles.Add(userRole);
                                }

                                _usersList.Add(user);
                            }
                        }
                    }
                }

                return(_usersList);
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - GetUsersListAsync Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - GetUsersListAsync Service Exception: {ex}");
            }
        }
Ejemplo n.º 6
0
        public async Task <Opportunity> UpdateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            try
            {
                var initialState = opportunity.Metadata.OpportunityState;

                if (opportunity.Metadata.OpportunityState != OpportunityState.Creating)
                {
                    if (opportunity.Content.CustomerDecision.Approved)
                    {
                        opportunity.Metadata.OpportunityState = OpportunityState.Accepted;
                    }

                    try
                    {
                        opportunity = await MoveTempFileToTeamAsync(opportunity, requestId);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - UpdateWorkflowAsync_MoveTempFileToTeam Service Exception: {ex}");
                    }

                    // Add / update members
                    // Get Group id
                    //var opportunityName = opportunity.DisplayName.Replace(" ", "");
                    var opportunityName = WebUtility.UrlEncode(opportunity.DisplayName);
                    var options         = new List <QueryParam>();

                    options.Add(new QueryParam("filter", $"startswith(displayName,'{opportunityName}')"));

                    var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                    dynamic jsonDyn = groupIdJson;

                    var group = String.Empty;
                    if (groupIdJson.HasValues)
                    {
                        group = jsonDyn.value[0].id.ToString();
                    }

                    // add to team group
                    var teamMembersComplete   = 0;
                    var isLoanOfficerSelected = false;
                    foreach (var item in opportunity.Content.TeamMembers)
                    {
                        var groupID = group;
                        var userId  = item.Id;
                        var oItem   = item;

                        if (item.AssignedRole.DisplayName == "RelationshipManager")
                        {
                            // In case an admin or background workflow will trigger this update after team/channels are created, relationship manager should also be added as owner
                            try
                            {
                                Guard.Against.NullOrEmpty(item.Id, $"UpdateWorkflowAsync_{item.AssignedRole.DisplayName} Id NullOrEmpty", requestId);
                                var responseJson = await _graphUserAppService.AddGroupOwnerAsync(userId, groupID, requestId);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError($"RequestId: {requestId} - userId: {userId} - UpdateWorkflowAsync_AddGroupOwnerAsync_{item.AssignedRole.DisplayName} error in CreateWorkflowAsync: {ex}");
                            }
                        }
                        else if (item.AssignedRole.DisplayName == "LoanOfficer")
                        {
                            if (!String.IsNullOrEmpty(item.Id))
                            {
                                isLoanOfficerSelected = true;                                 //Reltionship manager should be set to complete if loan officer is selected
                            }
                            try
                            {
                                Guard.Against.NullOrEmpty(item.Id, $"UpdateWorkflowAsync_{item.AssignedRole.DisplayName} Id NullOrEmpty", requestId);
                                var responseJson = await _graphUserAppService.AddGroupOwnerAsync(userId, groupID, requestId);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError($"RequestId: {requestId} - userId: {userId} - UpdateWorkflowAsync_AddGroupOwnerAsync_{item.AssignedRole.DisplayName} error in CreateWorkflowAsync: {ex}");
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(item.Fields.UserPrincipalName))
                            {
                                teamMembersComplete = teamMembersComplete + 1;
                                try
                                {
                                    Guard.Against.NullOrEmpty(item.Id, $"UpdateWorkflowAsync_{item.AssignedRole.DisplayName} Id NullOrEmpty", requestId);
                                    var responseJson = await _graphUserAppService.AddGroupMemberAsync(userId, groupID, requestId);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"RequestId: {requestId} - userId: {userId} - UpdateWorkflowAsync_AddGroupMemberAsync_{item.AssignedRole.DisplayName} error in CreateWorkflowAsync: {ex}");
                                }
                            }
                        }
                    }

                    //Update status of team members
                    var oppCheckLists = opportunity.Content.Checklists.ToList();
                    var roleMappings  = (await _roleMappingRepository.GetAllAsync(requestId)).ToList();

                    //TODO: LinQ
                    var updatedTeamlist = new List <TeamMember>();
                    foreach (var item in opportunity.Content.TeamMembers)
                    {
                        var oItem = item;
                        oItem.Status = ActionStatus.NotStarted;

                        if (opportunity.Content.CustomerDecision.Approved)
                        {
                            oItem.Status = ActionStatus.Completed;
                        }
                        else
                        {
                            var roleMap = roleMappings.Find(x => x.RoleName == item.AssignedRole.DisplayName);

                            if (item.AssignedRole.DisplayName != "LoanOfficer" && item.AssignedRole.DisplayName != "RelationshipManager")
                            {
                                if (roleMap != null)
                                {
                                    _logger.LogInformation($"RequestId: {requestId} - UpdateOpportunityAsync teamMember status sync with checklist status RoleName: {roleMap.RoleName}");

                                    var checklistItm = oppCheckLists.Find(x => x.ChecklistChannel == roleMap.Channel);
                                    if (checklistItm != null)
                                    {
                                        _logger.LogInformation($"RequestId: {requestId} - UpdateOpportunityAsync teamMember status sync with checklist status: {checklistItm.ChecklistStatus.Name}");
                                        oItem.Status = checklistItm.ChecklistStatus;
                                    }
                                }
                            }
                            else if (item.AssignedRole.DisplayName == "RelationshipManager")
                            {
                                var exisitngLoanOfficers = ((opportunity.Content.TeamMembers).ToList()).Find(x => x.AssignedRole.DisplayName == "LoanOfficer");
                                if (exisitngLoanOfficers == null)
                                {
                                    oItem.Status = ActionStatus.InProgress;
                                }
                                else
                                {
                                    oItem.Status = ActionStatus.Completed;
                                }
                            }
                            else if (item.AssignedRole.DisplayName == "LoanOfficer")
                            {
                                var teamList = ((opportunity.Content.TeamMembers).ToList()).FindAll(x => x.AssignedRole.DisplayName != "LoanOfficer" && x.AssignedRole.DisplayName != "RelationshipManager");
                                if (teamList != null)
                                {
                                    var expectedTeam = roleMappings.FindAll(x => x.RoleName != "LoanOfficer" && x.RoleName != "RelationshipManager" && x.RoleName != "Administrator");
                                    if (expectedTeam != null)
                                    {
                                        if (teamList.Count != 0)
                                        {
                                            oItem.Status = ActionStatus.InProgress;
                                        }
                                        if (teamList.Count >= expectedTeam.Count)
                                        {
                                            oItem.Status = ActionStatus.Completed;
                                        }
                                    }
                                }
                            }
                        }

                        updatedTeamlist.Add(oItem);
                    }

                    opportunity.Content.TeamMembers = updatedTeamlist;
                }

                // Send notification
                _logger.LogInformation($"RequestId: {requestId} - UpdateWorkflowAsync initialState: {initialState.Name} - {opportunity.Metadata.OpportunityState.Name}");
                if (initialState.Value != opportunity.Metadata.OpportunityState.Value)
                {
                    try
                    {
                        _logger.LogInformation($"RequestId: {requestId} - CreateWorkflowAsync sendNotificationCardAsync opportunity state change notification.");
                        var sendTo = UserProfile.Empty;
                        var sendNotificationCard = await _cardNotificationService.sendNotificationCardAsync(opportunity, sendTo, $"Opportunity state for {opportunity.DisplayName} has been changed to {opportunity.Metadata.OpportunityState.Name}", requestId);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - CreateWorkflowAsync sendNotificationCardAsync OpportunityState error: {ex}");
                    }
                }

                // Delete empty ChecklistItems
                //opportunity.Content.Checklists = await RemoveEmptyFromChecklist(opportunity.Content.Checklists, requestId);

                return(opportunity);
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - UpdateWorkflowAsync Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - UpdateWorkflowAsync Service Exception: {ex}");
            }
        }
Ejemplo n.º 7
0
        public async Task <Opportunity> CreateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            try
            {
                // Set initial opportunity state
                opportunity.Metadata.OpportunityState = OpportunityState.Creating;

                // Remove empty sections from proposal document
                opportunity.Content.ProposalDocument.Content.ProposalSectionList = opportunity.Content.ProposalDocument.Content.ProposalSectionList.Where(x => !string.IsNullOrWhiteSpace(x.DisplayName)).ToList();

                // Delete empty ChecklistItems
                opportunity.Content.Checklists = opportunity.Content.Checklists.Where(x => x.ChecklistTaskList.Any(y => !string.IsNullOrWhiteSpace(y.Id) && !string.IsNullOrWhiteSpace(y.ChecklistItem))).ToList();

                //Granular Access : Start
                _logger.LogError($"RequestId: {requestId} - Opportunityfactory_UpdateItemAsync CheckAccess CreateItemAsync");

                // QUESTION:
                // When an opportunity is created the DealType.ProcessList is always null, then why do we have the IF below, this is done in the UpdateWorkflowAsync

                if (opportunity.Content.DealType.ProcessList != null)
                {
                    //create team and channels
                    if (await GroupIdCheckAsync(opportunity.DisplayName, requestId))
                    {
                        await CreateTeamAndChannelsAsync(opportunity, requestId);
                    }

                    if (StatusCodes.Status200OK == await _authorizationService.CheckAccessFactoryAsync(PermissionNeededTo.DealTypeWrite, requestId) ||
                        await _authorizationService.CheckAccessInOpportunityAsync(opportunity, PermissionNeededTo.Write, requestId))
                    {
                        bool checklistPass = false;
                        foreach (var item in opportunity.Content.DealType.ProcessList)
                        {
                            if (item.ProcessType.ToLower() == "checklisttab" && checklistPass == false)
                            {
                                //DashBoard Create call Start.
                                await UpdateDashBoardEntryAsync(opportunity, requestId);

                                //DashBoard Create call End.
                                opportunity = await _checkListProcessService.CreateWorkflowAsync(opportunity, requestId);

                                checklistPass = true;
                            }
                            else if (item.ProcessType.ToLower() == "customerdecisiontab")
                            {
                                opportunity = await _customerDecisionProcessService.CreateWorkflowAsync(opportunity, requestId);
                            }
                            else if (item.ProcessType.ToLower() == "proposalstatustab")
                            {
                                opportunity = await _proposalStatusProcessService.CreateWorkflowAsync(opportunity, requestId);
                            }
                            else if (item.ProcessStep.ToLower() == "start process")
                            {
                                opportunity = await _startProcessService.CreateWorkflowAsync(opportunity, requestId);
                            }
                            else if (item.ProcessStep.ToLower() == "new opportunity")
                            {
                                opportunity = await _newOpportunityProcessService.CreateWorkflowAsync(opportunity, requestId);
                            }
                        }
                    }
                    else
                    {
                        if (opportunity.Content.DealType != null)
                        {
                            _logger.LogError($"RequestId: {requestId} - CreateWorkflowAsync Service Exception");
                            throw new AccessDeniedException($"RequestId: {requestId} - CreateWorkflowAsync Service Exception");
                        }
                    }
                }

                // Update note created by (if one) and set it to relationship manager
                if (opportunity.Content.Notes?.Count > 0)
                {
                    var currentUser = (_userContext.User.Claims).ToList().Find(x => x.Type == "preferred_username")?.Value;
                    var callerUser  = await _userProfileRepository.GetItemByUpnAsync(currentUser, requestId);

                    if (callerUser != null)
                    {
                        opportunity.Content.Notes[0].CreatedBy       = callerUser;
                        opportunity.Content.Notes[0].CreatedDateTime = DateTimeOffset.Now;
                    }
                    else
                    {
                        _logger.LogWarning($"RequestId: {requestId} - CreateWorkflowAsync can't find {currentUser} to set note created by");
                    }
                }

                //Adding RelationShipManager and LoanOfficer into ProposalManager Team
                dynamic jsonDyn = null;
                foreach (var item in opportunity.Content.TeamMembers.Where(item => item.AssignedRole.DisplayName.Equals("LoanOfficer", StringComparison.OrdinalIgnoreCase) ||
                                                                           item.AssignedRole.DisplayName.Equals("RelationshipManager", StringComparison.OrdinalIgnoreCase)))
                {
                    try
                    {
                        if (jsonDyn == null)
                        {
                            var options = new List <QueryParam>()
                            {
                                new QueryParam("filter", $"startswith(displayName,'{_appOptions.GeneralProposalManagementTeam}')")
                            };
                            jsonDyn = await _graphUserAppService.GetGroupAsync(options, "", requestId);
                        }

                        if (!string.IsNullOrEmpty(jsonDyn.value[0].id.ToString()) && !string.IsNullOrEmpty(item.Fields.UserPrincipalName))
                        {
                            try
                            {
                                var groupID = jsonDyn.value[0].id.ToString();
                                Guard.Against.NullOrEmpty(item.Id, $"OpportunityFactorty_{item.AssignedRole.DisplayName} Id NullOrEmpty", requestId);
                                await _graphUserAppService.AddGroupMemberAsync(item.Id, groupID, requestId);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError($"RequestId: {requestId} - userId: {item.Id} - OpportunityFactorty_AddGroupMemberAsync_{item.AssignedRole.DisplayName} error in CreateWorkflowAsync: {ex}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - userId: {item.Id} - OpportunityFactorty_AddGroupMemberAsync_{item.AssignedRole.DisplayName} error in CreateWorkflowAsync: {ex}");
                    }

                    // Send notification
                    // Define Sent To user profile
                    if (item.AssignedRole.DisplayName.Equals("LoanOfficer", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            _logger.LogInformation($"RequestId: {requestId} - CreateWorkflowAsync sendNotificationCardAsync new opportunity notification.");
                            var sendAccount = UserProfile.Empty;
                            sendAccount.Id          = item.Id;
                            sendAccount.DisplayName = item.DisplayName;
                            sendAccount.Fields.UserPrincipalName = item.Fields.UserPrincipalName;
                            await _cardNotificationService.sendNotificationCardAsync(opportunity, sendAccount, $"New opportunity {opportunity.DisplayName} has been assigned to ", requestId);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"RequestId: {requestId} - CreateWorkflowAsync sendNotificationCardAsync Action error: {ex}");
                        }
                    }
                }

                return(opportunity);
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - CreateWorkflowAsync Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - CreateWorkflowAsync Service Exception: {ex}");
            }
        }