Beispiel #1
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
                var porposalSectionList = new List <DocumentSection>();
                foreach (var item in opportunity.Content.ProposalDocument.Content.ProposalSectionList)
                {
                    if (!String.IsNullOrEmpty(item.DisplayName))
                    {
                        porposalSectionList.Add(item);
                    }
                }
                opportunity.Content.ProposalDocument.Content.ProposalSectionList = porposalSectionList;


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


                // Get Group id
                var opportunityName = opportunity.DisplayName.Replace("'", "");

                // Update status for team members & add them to team
                var isLoanOfficerSelected = false;                 //if true, relationship manager status should be completed
                var updatedTeamlist       = new List <TeamMember>();
                foreach (var item in opportunity.Content.TeamMembers)
                {
                    //var groupID = group;
                    var userId = item.Id;
                    var oItem  = item;

                    if (item.AssignedRole.DisplayName == "RelationshipManager")
                    {
                        oItem.Status = ActionStatus.InProgress;
                    }
                    else if (item.AssignedRole.DisplayName == "LoanOfficer")
                    {
                        if (!String.IsNullOrEmpty(item.Id))
                        {
                            isLoanOfficerSelected = true;
                        }

                        // Enable the code below if team will be created before the opportunity
                        //try
                        //{
                        //	Guard.Against.NullOrEmpty(userId, "CreateWorkflowAsync_LoanOffier_Ups Null or empty", requestId);
                        //	var responseJson = await _graphUserAppService.AddGroupOwnerAsync(userId, groupID);
                        //}
                        //catch (Exception ex)
                        //{
                        //	_logger.LogError($"RequestId: {requestId} - userId: {userId} - AddGroupOwnerAsync error in CreateWorkflowAsync: {ex}");
                        //}
                    }
                    else
                    {
                        // Nothing for other members
                    }

                    updatedTeamlist.Add(oItem);
                }

                opportunity.Content.TeamMembers = updatedTeamlist;

                // Update relationship manager status if loan officer has been selected
                if (isLoanOfficerSelected)
                {
                    updatedTeamlist = new List <TeamMember>();
                    foreach (var item in opportunity.Content.TeamMembers)
                    {
                        var prevItem = item;
                        if (item.AssignedRole.DisplayName == "RelationshipManager")
                        {
                            prevItem.Status = ActionStatus.Completed;
                        }
                        updatedTeamlist.Add(prevItem);
                    }

                    opportunity.Content.TeamMembers = updatedTeamlist;
                }

                // Update note created by (if one) and set it to relationship manager
                if (opportunity.Content.Notes != null)
                {
                    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");
                        }
                    }
                }

                // Send notification
                // Define Sent To user profile
                var loanOfficer = opportunity.Content.TeamMembers.ToList().Find(x => x.AssignedRole.DisplayName == "LoanOfficer");

                if (loanOfficer != null)
                {
                    try
                    {
                        _logger.LogInformation($"RequestId: {requestId} - CreateWorkflowAsync sendNotificationCardAsync new opportunity notification.");
                        var sendAccount = UserProfile.Empty;
                        sendAccount.Id          = loanOfficer.Id;
                        sendAccount.DisplayName = loanOfficer.DisplayName;
                        sendAccount.Fields.UserPrincipalName = loanOfficer.Fields.UserPrincipalName;
                        var sendNotificationCard = 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}");
                    }
                }


                // wave 1 notifination
                if (loanOfficer != null)
                {
                    var sendTo = loanOfficer.Fields.Mail ?? loanOfficer.Fields.UserPrincipalName;

                    var relManager = opportunity.Content.TeamMembers.ToList().Find(x => x.AssignedRole.DisplayName == "RelationshipManager");

                    if (relManager != null)
                    {
                        var notification = new Notification
                        {
                            Id     = String.Empty,
                            Title  = "New opportunity '" + opportunity.DisplayName + "' has been assigned to you.",
                            Fields = new NotificationFields
                            {
                                Message  = "Please go to your dashboard or teams to view the new opportunity.",
                                SentFrom = relManager.Fields.Mail ?? relManager.Fields.UserPrincipalName,
                                SentTo   = sendTo
                            }
                        };

                        // ensure opportunity creation does not fail due to an error in creating and sending te notification
                        try
                        {
                            var respCreateNotification = await _notificationRepository.CreateItemAsync(notification, requestId);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"RequestId: {requestId} - CreateWorkflowAsync CreateNotification 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}");
            }
        }
Beispiel #2
0
        public async Task <Opportunity> UpdateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            try
            {
                if (opportunity.Content.Template != null)
                {
                    if (opportunity.Content.Template.ProcessList != null)
                    {
                        if (opportunity.Content.Template.ProcessList.Count() > 1)
                        {
                            if (!opportunity.TemplateLoaded)
                            {
                                opportunity = await _teamChannelService.CreateWorkflowAsync(opportunity, requestId);

                                opportunity.Metadata.OpportunityState = OpportunityState.InProgress;
                            }
                            opportunity = await _memberService.CreateWorkflowAsync(opportunity, requestId);
                        }

                        bool checklistPass = false;
                        foreach (var item in opportunity.Content.Template.ProcessList)
                        {
                            if (item.ProcessType.ToLower() == "checklisttab" && checklistPass == false)
                            {
                                opportunity = await _checkListProcessService.UpdateWorkflowAsync(opportunity, requestId);

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


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

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

                var initialState = opportunity.Metadata.OpportunityState;
                _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}");
                    }
                }

                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}");
            }
        }