Exemple #1
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;
            }
        }
Exemple #2
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}");
            }
        }
        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}");
            }
        }