Example #1
0
        private async Task <DialogTurnResult> GoServicenowStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rpaService     = new RPAService();
            var processDetails = (ProcessDetails)stepContext.Options;

            processDetails.Action = string.Empty;
            var option       = stepContext.Result.ToString();
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "mainMenu" && promptOption.Id != "incident" && promptOption.Id != "asset")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                option = promptOption.Value;
            }

            if (option.ToLower() == "main menu" || option.ToLower() == "m")
            {
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
            }
            else
            {
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
        }
Example #2
0
		protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
		{
			foreach (var member in membersAdded)
			{
				// Greet anyone that was not the target (recipient) of this message.
				// To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for morBe details.
				if (member.Id != turnContext.Activity.Recipient.Id)
				{
					var user = new List<User>();
					var rpaService = new RPAService();
					var result = rpaService.GetUser(turnContext.Activity.Conversation.Id);
					if (result.IsSuccess)
						user = JsonConvert.DeserializeObject<List<User>>(result.Content);

					//var _user = user.GetUser();
					var msg = string.Empty;
					if (user.Count > 0)
					{
						if (!string.IsNullOrWhiteSpace(user[0].u_user))
						{
							msg = "Hello " + user[0].Name + ", welcome to Bayview ChatBot!";
						}
					}
					else
					{
						msg = "Welcome to Bayview ChatBot!";
					}
					await turnContext.SendActivityAsync(MessageFactory.Text(msg + Environment.NewLine + "What can I help you with today? You could type "+'"'+ "Menu" + '"' + " for available options."), cancellationToken);
				}

			}
		}
        private string GetApiPath()
        {
            var rpaService = new RPAService();
            var instance   = rpaService.GetInstanceName();
            var apiPath    = "https://" + instance + ".service-now.com/api/baam/bam_chat_bot/";

            return(apiPath);
        }
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var text           = string.Empty;
            var rpaService     = new RPAService();
            var response       = rpaService.GetConversationFlow(stepContext.Context.Activity.Conversation.Id);
            var result         = JsonConvert.DeserializeObject <List <ConversationFlow> >(response.Content);

            if (result.Count > 0)
            {
                processDetails.CurrentQuestion = result[0];
                if (processDetails.CurrentQuestion.u_last_question_index == 0 && processDetails.AttemptCount == 0)
                {
                    text = "Process " + processDetails.ProcessSelected.Name + " needs input parameters, please start entering them below.";
                }
                else if (processDetails.AttemptCount != 0 && processDetails.CurrentQuestion.u_last_question_index == 0)
                {
                    text = "Input parameters entered are incorrect, please re-enter them below.";
                }

                //delete record from SN
                rpaService.DeactivatedConversationFlow(processDetails.CurrentQuestion.sys_id, stepContext.Context.Activity.Conversation.Id);
                if (processDetails.CurrentQuestion.u_type.Contains("Bool"))
                {
                    var boolParamTrue = JsonConvert.SerializeObject(new PromptOption {
                        Id = "boolParam", Value = "true"
                    });
                    var boolParamFalse = JsonConvert.SerializeObject(new PromptOption {
                        Id = "boolParam", Value = "false"
                    });
                    var choices = new List <Choice> {
                        new Choice
                        {
                            Value  = "true",
                            Action = new CardAction(ActionTypes.PostBack, "true", null, "true", "true", value: boolParamTrue, null)
                        },
                        new Choice
                        {
                            Value  = "false",
                            Action = new CardAction(ActionTypes.PostBack, "false", null, "false", "false", value: boolParamFalse, null)
                        }
                    };
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, text + Environment.NewLine + "For " + processDetails.CurrentQuestion.u_param_name.UppercaseFirst() + " choose one option below.") }, cancellationToken));
                }
                else
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text(text + Environment.NewLine + "Enter " + processDetails.CurrentQuestion.u_param_name.UppercaseFirst() + ":") }, cancellationToken));
                }
            }
            else
            {
                processDetails.CurrentQuestion = new ConversationFlow();
                //get parameters entered

                return(await stepContext.NextAsync(processDetails, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> GetRunningProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var processes      = processDetails.Processes;
            var text           = "Here are your running processes.";

            if (processDetails.LoadMore)
            {
                text = string.Empty;
                processDetails.LoadMore = false;
            }
            if (processes.Count > 0)
            {
                var rpaService = new RPAService();
                //var _user = await _userAccessor.GetAsync(stepContext.Context, () => new User(), cancellationToken);
                var response = rpaService.GetUser(stepContext.Context.Activity.Conversation.Id);
                var user     = new List <User>();
                if (response.IsSuccess)
                {
                    user = JsonConvert.DeserializeObject <List <User> >(response.Content);
                }
                var result  = rpaService.GetListOfProcess(processes, Convert.ToInt32(user[0].u_last_index));
                var choices = result.Choices;
                //var rpaSupportChoice = rpaService.GetRPASupportOption();
                var menuValue = JsonConvert.SerializeObject(new PromptOption {
                    Id = "menu", Value = "menu"
                });
                var mainMenu = new Choice
                {
                    Value  = "menu",                   //[email protected]
                    Action = new CardAction(ActionTypes.PostBack, "**Main Menu**", null, "**Main Menu**", "**Main Menu**", value: menuValue, null)
                };
                //choices.Add(rpaSupportChoice);
                choices.Add(mainMenu);
                //save index
                user[0].u_last_index = result.LastIndex.ToString();
                rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                //_user.u_last_index = result.LastIndex;
                //await this._userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);

                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.HeroCard(choices, text + Environment.NewLine + "Click the process you would like to get the status for.")

                             /*Prompt = MessageFactory.Text(text + Environment.NewLine + "Click the process you would like to get the status for."),
                              * Choices = choices,
                              * Style = ListStyle.Auto*/
                }, cancellationToken));
            }
            else
            {
                processDetails.Action = "error";
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> ContinueStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rpaService     = new RPAService();
            var processDetails = this.processDetails;

            processDetails.Action = string.Empty;
            var option       = stepContext.Result.ToString();
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "Confirm" && promptOption.Id != "mainMenu" && promptOption.Id != "FinalStep" && promptOption.Id != "rpaSuport")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                option = promptOption.Value;
            }
            //if (option.ToLower() == "yes" || option.ToLower() == "y")
            //{
            //return await stepContext.ReplaceDialogAsync(InitialDialogId, processDetails, cancellationToken);

            /*var value = JsonConvert.SerializeObject(new PromptOption { Id = "rpaSuport", Value = "*****@*****.**" });
             * var choices = new List<Choice>
             * { new Choice
             *                      {
             *                              Value = "rpaSupport",
             *                              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openEmail", value: value, null)
             *                       } };
             * choices.Add(rpaService.GetMainMenuOption());
             *
             * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
             * {
             *      Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "To Contact RPA Support, click Button below")
             *
             * }, cancellationToken);*/
            //}
            if (option.ToLower() == "main menu" || option.ToLower() == "m")
            {
                return(await stepContext.ReplaceDialogAsync(InitialDialogId, null, cancellationToken));
            }
            else
            {
                return(await stepContext.ReplaceDialogAsync(InitialDialogId, processDetails, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> ShowProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var processes      = processDetails.Processes;
            var text           = "Here are your processes in progress. ";

            if (processDetails.LoadMore)
            {
                text = string.Empty;
                processDetails.LoadMore = false;
            }
            if (processes.Count > 0)
            {
                var rpaService = new RPAService();
                //var _user = await _userAccessor.GetAsync(stepContext.Context, () => new User(), cancellationToken);
                //get last index
                var response = rpaService.GetUser(stepContext.Context.Activity.Conversation.Id);
                var user     = new List <User>();
                if (response.IsSuccess)
                {
                    user = JsonConvert.DeserializeObject <List <User> >(response.Content);
                }
                var result  = rpaService.GetListOfProcess(processes, Convert.ToInt32(user[0].u_last_index));
                var choices = result.Choices;
                //add one choice for rpa support
                var rpaSupportChoice = rpaService.GetRPASupportOption();
                choices.Add(rpaSupportChoice);
                //save index
                user[0].u_last_index = result.LastIndex.ToString();
                rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                //_user.u_last_index = result.LastIndex;
                //await this._userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);

                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.HeroCard(choices, text + "Which one would you like to stop?")

                             /*Prompt = MessageFactory.Text(text+ "Which one would you like to stop?"),
                              * Choices = choices,
                              * Style = ListStyle.Auto*/
                }, cancellationToken));
            }
            else
            {
                processDetails.Action = "error";
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
        }
Example #8
0
        internal void GetUserRunningProcess(ProcessDetails processDetails)
        {
            var rpaService = new RPAService();
            var result     = rpaService.GetApiResult("getUserRunningProcess", processDetails.User.UserId);

            if (!result.IsSuccess)
            {
                processDetails.Error     = JsonConvert.DeserializeObject <ProcessModel>(result.Content).Error;
                processDetails.Processes = new List <ProcessModel>();
            }
            else
            {
                var processes = JsonConvert.DeserializeObject <List <ProcessModel> >(result.Content);
                processDetails.Processes = processes;
            }
        }
Example #9
0
        internal void GetUserProcess(ProcessDetails processDetails)
        {
            var rpaService = new RPAService();
            var result     = rpaService.GetApiResult("userProcesses", processDetails.User.UserId);

            if (!result.IsSuccess)
            {
                processDetails.Error = JsonConvert.DeserializeObject <ProcessModel>(result.Content).Error;
            }
            else
            {
                var processes = JsonConvert.DeserializeObject <List <ProcessModel> >(result.Content);
                //sort the process
                processes = processes.OrderBy(p => p.Name).ToList();
                processDetails.Processes = processes;
            }
        }
        private async Task <DialogTurnResult> ConfirmStartProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rpaService     = new RPAService();
            var processDetails = (ProcessDetails)stepContext.Options;
            var result         = stepContext.Result.ToString();

            if (result.ToLower() == "yes" || result.ToLower() == "y")
            {
                //clear data in SN table
                rpaService.DeleteConversationFlowInputs(stepContext.Context.Activity.Conversation.Id);
                //return await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken);
            }
            //else
            //{
            return(await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken));

            //}
        }
Example #11
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var snConfig       = new RPAService();
            var result         = snConfig.GetApiResult("userProcesses", "");

            if (!result.IsSuccess)
            {
                processDetails.Error = JsonConvert.DeserializeObject <ProcessModel>(result.Content).Error;
            }
            else
            {
                var processes = JsonConvert.DeserializeObject <List <ProcessModel> >(result.Content);
                processDetails.Processes = processes;
            }

            return(await stepContext.NextAsync(processDetails, cancellationToken));
        }
Example #12
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var message        = string.Empty;
            var processDetails = (ProcessDetails)stepContext.Options;

            if (processDetails.Action == "typed")
            {
                message = "Typing is not valid for this menu option." + Environment.NewLine + "Please return to the Main Menu and click on the option you want to select.";
                processDetails.Action = string.Empty;
                var rpaService = new RPAService();
                var choices    = new List <Choice>();
                choices.Add(rpaService.GetMainMenuOption());
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, message),
                }, cancellationToken));
            }

            return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
        }
 protected override async Task OnEventActivityAsync(ITurnContext <IEventActivity> turnContext, CancellationToken cancellationToken)
 {
     if (turnContext.Activity.Type == ActivityTypes.Event)
     {
         var user = new User();
         if (turnContext.Activity.Name == "urlClickedEvent")
         {
         }
         else
         {
             //get params sent from SN
             var userParam = turnContext.Activity.From.Properties["userparam"].ToString();
             user = JsonConvert.DeserializeObject <User>(userParam);
             //save user
             var rpaService = new RPAService();
             rpaService.SaveUser(new User {
                 u_user = user.UserId, u_conversation_id = turnContext.Activity.Conversation.Id
             });
         }
     }
 }
Example #14
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;

            //2nd attempt to start process
            var rpaService = new RPAService();
            var response   = rpaService.StartProcess(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
            var error      = false;

            if (string.IsNullOrEmpty(response.Content) || !response.IsSuccess)
            {
                error = true;
            }
            if (error)
            {
                var rpaSupportChoice = rpaService.GetRPASupportOption();
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(new List <Choice> {
                        rpaSupportChoice
                    }, "There was an issue running " + processDetails.ProcessSelected.Name + " process, please contact RPA Support.")

                             /*Prompt = MessageFactory.Text("There was an issue running " + processDetails.ProcessSelected.Name + " process, please contact RPA Support. "),
                              * Choices = new List<Choice> { rpaSupportChoice }*/
                }, cancellationToken));
            }
            else
            {
                var choices = rpaService.GetConfirmChoices();
                processDetails.Jobs = JsonConvert.DeserializeObject <List <Job> >(response.Content);

                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, processDetails.ProcessSelected.Name + " process has started and you will be notified when it finishes." + Environment.NewLine + "Do you want to run another process??")

                             /*Prompt = MessageFactory.Text(processDetails.ProcessSelected.Name + " process  has started, you will be notified when it finishes. Do you want to run another process?"),
                              * Choices = ChoiceFactory.ToChoices(new List<string> { "Yes", "No" })*/
                }, cancellationToken));
            }
        }
Example #15
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var value          = JsonConvert.SerializeObject(new PromptOption {
                Id = "rpaSuport", Value = "*****@*****.**"
            });
            var choices = new List <Choice>
            {
                new Choice
                {
                    Value  = "rpaSupport",//[email protected]
                    Action = new CardAction(ActionTypes.PostBack, "To Contact RPA Support click here", null, "To Contact RPA Support click here", "openEmail", value: value, null)
                }
            };
            var rpaService = new RPAService();

            choices.Add(rpaService.GetMainMenuOption());
            return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            {
                Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "You have made 3 attempts, please contact RPA Support or go back to Main Menu.")
            },
                                                 cancellationToken));
        }
Example #16
0
        private async Task <DialogTurnResult> StartProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var result         = stepContext.Result.ToString();
            var promptOption   = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) {}

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "Confirm")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                result = promptOption.Value;
            }

            if (result.ToLower() == "yes" || result.ToLower() == "y")
            {
                var rpaService = new RPAService();
                //save activity id for when process finish
                var activityId = stepContext.Context.Activity.Id;
                //check if the process can start
                if (processDetails.ProcessSelected.LastRun.State == "Faulted" || processDetails.ProcessSelected.LastRun.State == "Successful" || processDetails.ProcessSelected.LastRun.State == "Stopped" || string.IsNullOrEmpty(processDetails.ProcessSelected.LastRun.State))
                {
                    //check if has asset
                    var assetsWithValueFromChild = rpaService.HasAnyAsset(processDetails.ProcessSelected);
                    if (assetsWithValueFromChild.Count > 0)
                    {
                        var response = rpaService.MakeAssetFromChild(assetsWithValueFromChild);
                        if (response.Body != "Success")
                        {
                            var choices   = new List <Choice>();
                            var rpaOption = rpaService.GetMainMenuOption();
                            if (response.MissingAsset)
                            {
                                //create incident
                                var incident      = rpaService.CreateRPAIncident(processDetails.ProcessSelected);
                                var incidentValue = JsonConvert.SerializeObject(new PromptOption {
                                    Id = "incident", Value = "bam?id=rpa_request&table=u_robot_incident&sys_id=" + incident.Sys_Id
                                });
                                choices = new List <Choice>
                                {
                                    new Choice
                                    {
                                        Value  = "bam?id=rpa_request&table=u_robot_incident&sys_id=" + incident.Sys_Id,
                                        Action = new CardAction(ActionTypes.PostBack, incident.Number, null, incident.Number, "openUrl", value: incidentValue, null)
                                    }
                                };
                                choices.Add(rpaOption);

                                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                                {
                                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "Process " + processDetails.ProcessSelected.Name + " requires an asset associated to your user, an incident has been opened to RPA Support." + Environment.NewLine + "Click incident number below to open it")
                                }, cancellationToken));
                            }
                            else
                            {
                                var assetValue = JsonConvert.SerializeObject(new PromptOption {
                                    Id = "asset", Value = "bam?id=rpa_process_assets&process=" + processDetails.ProcessSelected.Sys_id
                                });
                                choices = new List <Choice>
                                {
                                    new Choice
                                    {
                                        Value  = "bam?id=rpa_process_assets&process=" + processDetails.ProcessSelected.Sys_id,
                                        Action = new CardAction(ActionTypes.PostBack, "Update Asset", null, "Update Asset", "openUrl", value: assetValue, null)
                                    }
                                };
                                choices.Add(rpaOption);
                                //send the user to SN UI page
                                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                                {
                                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, response.Body + Environment.NewLine + "Please enter them before running the process by pressing Update Asset button below.")
                                }, cancellationToken));
                            }
                        }
                    }
                    if (processDetails.ProcessSelected.Releases.Any(r => r.robots.Count > 1))
                    {
                        processDetails.ProcessSelected.FirstBot = true;
                        return(await stepContext.ReplaceDialogAsync(nameof(RobotsDialog), processDetails, cancellationToken));
                    }                    //check if process need params
                    else if (processDetails.ProcessSelected.Releases.Any(r => r.parameters_required == true))
                    {
                        //set all params for this conversation to false(maybe was interrupted by a notification)
                        rpaService.DeactivatedConversationFlow(string.Empty, stepContext.Context.Activity.Conversation.Id);
                        rpaService.SaveConversationFlow(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
                        return(await stepContext.ReplaceDialogAsync(nameof(ParametersProcessDialog), processDetails, cancellationToken));
                    }
                    else
                    {
                        return(await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken));
                    }
                }
                else
                {
                    processDetails.Action = "error";
                    processDetails.Error  = "Cannot start " + processDetails.ProcessSelected.Name + " because the process is already running.";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
            }
            else if (result.ToLower() == "no" || result.ToLower() == "n")            //when no is selected
            {
                processDetails.Action = string.Empty;
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
            }
            else             //when something is typed
            {
                processDetails.Action = string.Empty;
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
            }
        }
Example #17
0
        private async Task <DialogTurnResult> ExecuteActionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails  = (ProcessDetails)stepContext.Options;
            var selectedProcess = processDetails.ProcessSelected;

            selectedProcess.StartedBy = "chat_bot";
            var action = (FoundChoice)stepContext.Result;

            processDetails.ConfirmAction = action.Value;
            var config = new RPAService();

            if (action.Value == "Yes")
            {
                if (processDetails.Action == "start")
                {
                    //save activity id for when process finish
                    var activityId = stepContext.Context.Activity.Id;

                    var response = config.StartProcess(selectedProcess, string.Empty);
                    if (!string.IsNullOrEmpty(response.Content))
                    {
                        if (response.IsSuccess)
                        {
                            processDetails.Jobs = JsonConvert.DeserializeObject <List <Job> >(response.Content);
                        }
                        else
                        {
                            processDetails.Error = JsonConvert.DeserializeObject <Job>(response.Content).Error;
                        }
                        return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));

                        /*return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                         * { Prompt = MessageFactory.Text("Process " + processDetails.ProcessSelected.Name + " was started, you will be notified when it finishes. Meanwhile, is there something else can I assist you with?") },
                         * cancellationToken);*/
                    }
                    else//there was an error
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions
                        {
                            Prompt = MessageFactory.Text("To continue to run this bot, please contact RPA Support. "),
                            Choices = new List <Choice> {
                                new Choice
                                {
                                    Value = "rpaSupport",
                                    Action = new CardAction(ActionTypes.OpenUrl, "Click Here", value: "bam?id=rpa_new_request&type=incident")
                                }
                            }
                        }, cancellationToken));
                    }
                }
                else if (processDetails.Action == "check status")
                {
                    return(await stepContext.BeginDialogAsync(nameof(StatusDialog), processDetails, cancellationToken));
                }
                else
                {
                    return(await stepContext.BeginDialogAsync(nameof(StopProcessDialog), processDetails, cancellationToken));
                }
            }
            else
            {
                //start over
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
        }
Example #18
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var bot            = new Robot();

            foreach (var r in processDetails.ProcessSelected.Releases)
            {
                if (r.robots.Count > 1)
                {
                    if (r.robots.Any(b => b.Shown == false))
                    {
                        bot       = r.robots.Find(b => b.Shown == false);
                        bot.Shown = true;
                        break;
                    }
                    bot = new Robot();
                }
            }

            if (string.IsNullOrEmpty(bot.id))
            {
                processDetails.ProcessSelected.FirstBot = true;
                //all processed
                foreach (var r in processDetails.ProcessSelected.Releases)
                {
                    if (r.robots.Count > 1)
                    {
                        var robots = new List <string>();
                        foreach (var b in r.robots)
                        {
                            if (b.Selected)
                            {
                                robots.Add(b.id);
                            }
                        }
                        if (robots.Count == 0)
                        {
                            foreach (var re in processDetails.ProcessSelected.Releases)
                            {
                                if (re.robots.Count > 1)
                                {
                                    foreach (var b in re.robots)
                                    {
                                        b.Shown = false;
                                    }
                                }
                            }
                            processDetails.ProcessSelected.ReEnterBot = true;
                            return(await stepContext.ReplaceDialogAsync(nameof(RobotsDialog), processDetails, cancellationToken));
                        }
                        r.u_robots = string.Join(',', robots);
                    }
                }
                //if needs params
                if (processDetails.ProcessSelected.Releases.Any(r => r.parameters_required == true))
                {
                    var rpaService = new RPAService();
                    //set all params for this conversation to false(maybe was interrupted by a notification)
                    rpaService.DeactivatedConversationFlow(string.Empty, stepContext.Context.Activity.Conversation.Id);
                    rpaService.SaveConversationFlow(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
                    return(await stepContext.ReplaceDialogAsync(nameof(ParametersProcessDialog), processDetails, cancellationToken));
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken));
                }
            }
            else
            {
                var message = string.Empty;
                if (processDetails.ProcessSelected.FirstBot)
                {
                    if (processDetails.ProcessSelected.ReEnterBot)
                    {
                        message = "You have to select at least one Bot." + Environment.NewLine;
                        processDetails.ProcessSelected.ReEnterBot = false;
                    }
                    message += "Select the Bot(s) to trigger " + processDetails.ProcessSelected.Name + " process." + Environment.NewLine + "For each one select " + '"' + "Yes or No" + '"';
                    processDetails.ProcessSelected.FirstBot = false;
                }
                processDetails.ProcessSelected.Bot = bot;
                var rpaService = new RPAService();
                var choices    = rpaService.GetConfirmChoices();
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, message + Environment.NewLine + bot.name)
                }, cancellationToken));
            }
        }
        private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var serviceUrl = turnContext.Activity.ServiceUrl;

            // If you encounter permission-related errors when sending this message, see
            // https://aka.ms/BotTrustServiceUrl
            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            //var user = await((DialogBot<MainDialog>)_bot)._userAccessor.GetAsync(turnContext, () => new User());
            var rpaService = new RPAService();
            var response   = rpaService.GetUser(turnContext.Activity.Conversation.Id);
            var user       = new List <User>();

            if (response.IsSuccess)
            {
                user = JsonConvert.DeserializeObject <List <User> >(response.Content);
            }
            if (user[0].u_user == _processStatus.ChatbotUser)            // && turnContext.Activity.Conversation.Id == _processStatus.ConversationId)
            {
                var endTime   = _processStatus.End != null ? "End Time: " + _processStatus.End + Environment.NewLine : string.Empty;
                var startTime = _processStatus.Start != null ? "Start Time: " + _processStatus.Start + Environment.NewLine : string.Empty;

                var include = "Total Transactions Processed: " + _processStatus.TotalTransactions + Environment.NewLine +
                              startTime +
                              endTime;
                //"Run Time: " + _processStatus.Runtime + Environment.NewLine;
                if (_processStatus.ProcessType == "procedural")
                {
                    include = string.Empty;
                }
                var message = string.Empty;
                if (_processStatus.IsCompletation)
                {
                    var reason = string.Empty;
                    if (_processStatus.State.value == "Faulted")
                    {
                        reason = "Reason: " + _processStatus.Info + Environment.NewLine;
                    }
                    message = "Process " + _processStatus.Process + " has finished with the following updates:" + Environment.NewLine +
                              "Status: " + _processStatus.State.label + Environment.NewLine + reason +
                              "Bot Name: " + _processStatus.Robot + Environment.NewLine +
                              startTime +
                              endTime +
                              "Successful Executions: " + _processStatus.SuccessfulExecutions + Environment.NewLine +
                              "Exceptions: " + _processStatus.Exceptions;
                }
                else
                {
                    message = "Here is the status for " + _processStatus.Process + " process." + Environment.NewLine +
                              //"Status: " + _processStatus.State + Environment.NewLine +
                              include +
                              "Total Transactions Successful: " + Convert.ToInt32(_processStatus.TotalTransSuccessful) + Environment.NewLine +
                              "Total Exceptions: " + Convert.ToInt32(_processStatus.TotalExceptions) + Environment.NewLine +
                              "Bot Name: " + _processStatus.Robot;
                }

                var noti = MessageFactory.Text(message);
                noti.SuggestedActions = new SuggestedActions
                {
                    Actions = new List <CardAction>
                    {
                        new CardAction()
                        {
                            Value       = "ProcessCompletionDone",
                            Type        = ActionTypes.PostBack,
                            Title       = "Click Here to continue",
                            Text        = "Click Here to continue",
                            DisplayText = "Click Here to continue"
                        }
                    }
                };
                await turnContext.SendActivityAsync(noti);
            }
        }
        private async Task <DialogTurnResult> RecognizeText(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var user = new User();

            var processDetails = new ProcessDetails();

            try
            {
                var promptOption = new PromptOption();
                try
                {
                    promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Context.Activity.Text);
                }
                catch (Exception) { }
                if (!string.IsNullOrEmpty(promptOption.Value))
                {
                    stepContext.Context.Activity.Text = promptOption.Value;
                }

                var luisResult = await _luisRecognizer.RecognizeAsync <Process>(stepContext.Context, cancellationToken);

                switch (luisResult.TopIntent().intent)
                {
                case Process.Intent.RPA:
                    var choices    = new List <Choice>();
                    var rpaOptions = new RPAOptions();

                    foreach (var option in rpaOptions.Options)
                    {
                        var value = JsonConvert.SerializeObject(option);

                        choices.Add(new Choice
                        {
                            Value  = option.Value,
                            Action = new CardAction(ActionTypes.PostBack, option.Text, null, option.Text, option.DisplayText, value: value, null)
                                     //ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: value, null
                        });
                    }

                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.HeroCard(choices, "Below is a list of available commands:"),                                //.ForChannel(stepContext.Context.Activity.ChannelId, choices, "Here is a list of your available commands.", null, ChoiceFactoryOptions.),
                    }, cancellationToken));

                /*return await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions
                 * {
                 *      Prompt = MessageFactory.Text("Here is a list of your available commands."),
                 *      Choices = choices,
                 *      Style = ListStyle.HeroCard
                 * }, cancellationToken);*/

                default:
                    processDetails.Action = "default";
                    // Catch all for unhandled intents
                    var didntUnderstandMessageText = "I am sorry, I do not understand your request. Please try asking a different way or type " + '"' + "Menu" + '"' + " for available options.";
                    var didntUnderstandMessage     = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput);
                    //start this dialog again
                    return(await stepContext.NextAsync(processDetails, cancellationToken));                           //.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = didntUnderstandMessage }, cancellationToken);
                }
                // return await stepContext.BeginDialogAsync(nameof(ProcessDialog), processDetails, cancellationToken);
            }
            catch (Exception ex)
            {
                var rpaService = new RPAService();
                var rpaSupport = rpaService.GetRPASupportOption();
                var choices    = new List <Choice> {
                    rpaSupport
                };
                processDetails.Action = "error";

                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "To continue to run this bot, please contact RPA Support.")

                             /*Prompt = MessageFactory.Text("To continue to run this bot, please contact RPA Support."),
                              * Choices = choices*/
                }, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var user       = new List <User>();
            var rpaService = new RPAService();
            var option     = string.Empty;

            try
            {
                this.processDetails = (ProcessDetails)stepContext.Result;
            }
            catch (Exception)
            {
                option = stepContext.Result.ToString();
            }
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
                processDetails.PromptOption = promptOption;
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "rpaSuport" && promptOption.Id != "RPAOptions")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                option = promptOption.Value;
            }
            var result = rpaService.GetUser(stepContext.Context.Activity.Conversation.Id);

            if (result.IsSuccess)
            {
                user = JsonConvert.DeserializeObject <List <User> >(result.Content);
            }
            //var _user = await _userAccessor.GetAsync(stepContext.Context, () => new User(), cancellationToken);


            if (this.processDetails.User != null)
            {
                this.processDetails.User.UserId = user[0].u_user;
            }
            else
            {
                this.processDetails.User = new User
                {
                    UserId = user[0].u_user
                };
            }
            if (!string.IsNullOrEmpty(option))
            {
                switch (option.ToLower())
                {
                case "start process":
                case "start":
                case "restart bot":
                case "start bot":
                    processDetails.Action = "start";
                    return(await stepContext.BeginDialogAsync(nameof(StartProcessDialog), processDetails, cancellationToken));

                case "process status":
                case "status":
                case "metrics":
                    processDetails.Action = "check status";
                    return(await stepContext.BeginDialogAsync(nameof(StatusDialog), processDetails, cancellationToken));

                case "stop a process":
                case "stop":
                case "stop process":
                case "stop bot":
                    processDetails.Action = "stop";
                    return(await stepContext.BeginDialogAsync(nameof(StopProcessDialog), processDetails, cancellationToken));

                case "report an issue":
                case "issue":
                case "report":
                case "report issue":
                case "bot failed":
                case "bot not working":
                case "bam?id=rpa_new_request&type=incident":
                    processDetails.Action = string.IsNullOrEmpty(promptOption.Id)? "typed" : string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(OpenURLDialog), processDetails, cancellationToken));

                /*var value = JsonConvert.SerializeObject(new PromptOption { Id = "FinalStep", Value = "bam?id=rpa_new_request&type=incident" });
                 * var choices = new List<Choice> { new Choice
                 *      {
                 *              Value = "bam?id=rpa_new_request&type=incident",
                 *              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: value, null)
                 *       }
                 * };
                 * choices.Add(rpaService.GetMainMenuOption());
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "To Report an Issue, click Button below")
                 * }, cancellationToken);*/
                case "**contact rpa support**":
                case "contact rpa support":
                case "rpa support":
                case "support":
                case "contact support":
                case "help":
                case "need help":
                case "help needed":
                    return(await stepContext.BeginDialogAsync(nameof(SupportDialog), processDetails, cancellationToken));

                case "request an enhancement":
                case "enhancement":
                case "request":
                case "new request":
                case "bam?id=rpa_new_request&type=enhancement":
                    processDetails.Action = string.IsNullOrEmpty(promptOption.Id) ? "typed" : string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(OpenURLDialog), processDetails, cancellationToken));

                /*var enhancementValue = JsonConvert.SerializeObject(new PromptOption { Id = "FinalStep", Value = "bam?id=rpa_new_request&type=enhancement" });
                 * var options = new List<Choice> { new Choice
                 *      {
                 *              Value = "bam?id=rpa_new_request&type=enhancement",
                 *              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: enhancementValue, null)
                 *       } };
                 * options.Add(rpaService.GetMainMenuOption());
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(options, "To Request an Enhancement, click Button below")
                 * }, cancellationToken);*/
                case "submit a new idea":
                case "new idea":
                case "idea":
                case "new project":
                case "new process":
                case "project request":
                case "bam?id=sc_cat_item&sys_id=a41ac289db7c6f0004b27709af9619a3":
                    processDetails.Action = string.IsNullOrEmpty(promptOption.Id) ? "typed" : string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(OpenURLDialog), processDetails, cancellationToken));

                /*var ideaValue = JsonConvert.SerializeObject(new PromptOption { Id = "FinalStep", Value = "bam?id=sc_cat_item&sys_id=a41ac289db7c6f0004b27709af9619a3" });
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(new List<Choice> { new Choice
                 *      {
                 *              Value = "bam?id=sc_cat_item&sys_id=a41ac289db7c6f0004b27709af9619a3",
                 *              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: ideaValue, null)
                 *       } ,rpaService.GetMainMenuOption()}, "To Submit an Idea, click Button below")
                 *
                 * }, cancellationToken);*/
                case "Bot Portal":
                case "bot portal":
                case "bam?id=rpa_processes":
                    processDetails.Action = string.IsNullOrEmpty(promptOption.Id) ? "typed" : string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(OpenURLDialog), processDetails, cancellationToken));

                /*var rpaProcessValue = JsonConvert.SerializeObject(new PromptOption { Id = "FinalStep", Value = "bam?id=rpa_processes" });
                 * options = new List<Choice> { new Choice
                 *      {
                 *              Value = "bam?id=rpa_processes",
                 *              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: rpaProcessValue, null)
                 *       } };
                 * options.Add(rpaService.GetMainMenuOption());
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(options, "To go to Bot Portal, click Button below")
                 * }, cancellationToken);*/
                case "RPA Process Schedules":
                case "rpa process schedules":
                case "bam?id=rpa_process_scheduler":
                    processDetails.Action = string.IsNullOrEmpty(promptOption.Id) ? "typed" : string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(OpenURLDialog), processDetails, cancellationToken));

                /*var rpaProcessSchValue = JsonConvert.SerializeObject(new PromptOption { Id = "FinalStep", Value = "bam?id=rpa_process_scheduler" });
                 * options = new List<Choice> { new Choice
                 *      {
                 *              Value = "bam?id=rpa_processes",
                 *              Action = new CardAction(ActionTypes.PostBack, "Click Here", null, "Click Here", "openUrl", value: rpaProcessSchValue, null)
                 *       } };
                 * options.Add(rpaService.GetMainMenuOption());
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(options, "To go to RPA Process Schedules, click Button below")
                 * }, cancellationToken);*/

                case "end chat":
                case "exit":
                case "exit chat":
                case "close":
                case "close chat":
                case "end":
                    //processDetails.Action = "done";
                    return(await stepContext.ReplaceDialogAsync(nameof(EndConversationDialog), processDetails, cancellationToken));

                //this happen if an exception
                case "*****@*****.**":
                    processDetails.Action = string.Empty;
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));

                //if type something instead of clicking an option
                default:
                    return(await stepContext.ReplaceDialogAsync(InitialDialogId, null, cancellationToken));
                }
            }
            else
            {            //if luis not recognize what the user enter
                return(await stepContext.ReplaceDialogAsync(InitialDialogId, processDetails, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> ShowParametersStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var value          = string.Empty;

            try
            {
                processDetails = (ProcessDetails)stepContext.Result;
            }
            catch (Exception)
            {
                value = stepContext.Result.ToString();
            }
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "boolParam")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                value = promptOption.Value;
            }

            var rpaService = new RPAService();

            //have entered all params
            if (string.IsNullOrEmpty(processDetails.CurrentQuestion.sys_id))
            {
                var inputs = new List <ConversationFlowInput>();

                //all parameters are entered
                foreach (var r in processDetails.ProcessSelected.Releases)
                {
                    if (r.parameters_required)
                    {
                        //get params
                        var response = rpaService.GetConversationFlowInputs(stepContext.Context.Activity.Conversation.Id, r.sys_id);
                        var result   = new List <ConversationFlowInput>();
                        if (response.IsSuccess)
                        {
                            result = JsonConvert.DeserializeObject <List <ConversationFlowInput> >(response.Content);
                        }
                        inputs.AddRange(result);
                        var processParametersList = new List <ProcessParameters>();

                        foreach (var p in result)
                        {
                            if (p.u_is_object)
                            {
                                foreach (var o in r.parameters)
                                {
                                    var objectParam = o.obj.Find(obj => obj.parmName == p.paramName);
                                    if (objectParam != null)
                                    {
                                        objectParam.value = p.u_value;
                                        break;
                                    }
                                    else
                                    {
                                        foreach (var a in o.obj)
                                        {
                                            objectParam = a.array.Find(arr => arr.parmName == p.paramName && string.IsNullOrEmpty(arr.value));
                                            if (objectParam != null)
                                            {
                                                objectParam.value = p.u_value;
                                                break;
                                            }
                                            else
                                            {
                                                objectParam = a.array.Find(arr => a.parmName + '[' + arr.parmName + ']' == p.paramName && string.IsNullOrEmpty(arr.value));
                                                if (objectParam != null)
                                                {
                                                    objectParam.value = p.u_value;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (p.u_is_array)
                            {
                                foreach (var a in r.parameters)
                                {
                                    var arrParam = a.array.Find(arr => arr.parmName == p.paramName && string.IsNullOrEmpty(arr.value));
                                    if (arrParam != null)
                                    {
                                        arrParam.value = p.u_value;
                                        break;
                                    }
                                    else
                                    {
                                        arrParam = a.array.Find(arr => a.parmName + '[' + arr.parmName + ']' == p.paramName && string.IsNullOrEmpty(arr.value));
                                        if (arrParam != null)
                                        {
                                            arrParam.value = p.u_value;
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var _param = r.parameters.Find(pp => pp.parmName == p.paramName);
                                if (_param != null)
                                {
                                    _param.value = p.u_value;
                                }
                            }
                        }
                    }
                }

                /*var message = string.Empty;
                 * foreach (var i in inputs)
                 * {
                 *      message += i.paramName + ": " + i.u_value + Environment.NewLine;
                 * }
                 *
                 * return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                 * {
                 *      Prompt = (Activity)ChoiceFactory.SuggestedAction(ChoiceFactory.ToChoices(new List<string> { "Yes", "No" }), "You have entered " +Environment.NewLine+ message + "Is that correct?")
                 *
                 * }, cancellationToken);*/
                //clear data in SN table
                rpaService.DeleteConversationFlowInputs(stepContext.Context.Activity.Conversation.Id);
                return(await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken));
            }
            else
            {
                var conversationFlowInput = new ConversationFlowInput
                {
                    u_chatbot_conversation_flow = processDetails.CurrentQuestion.sys_id,
                    u_value           = value.ToString(),
                    u_conversation_id = stepContext.Context.Activity.Conversation.Id
                };
                rpaService.SaveConversationFlowInput(conversationFlowInput);
                return(await stepContext.ReplaceDialogAsync(nameof(ParametersProcessDialog), processDetails, cancellationToken));
            }
        }
Example #23
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;

            /*conversationFlow.AskingForParameters = false;
             * await this._conversationFlow.SetAsync(stepContext.Context, conversationFlow);*/
            if (processDetails.ProcessSelected.LastRun.State == "Faulted" || processDetails.ProcessSelected.LastRun.State == "Successful" || processDetails.ProcessSelected.LastRun.State == "Stopped" || string.IsNullOrEmpty(processDetails.ProcessSelected.LastRun.State))
            {
                var rpaService     = new RPAService();
                var response       = new APIResponse();
                var hasInputParams = false;
                if (processDetails.ProcessSelected.Releases.Any(r => r.parameters_required == true))
                {
                    processDetails.ProcessSelected.ConversationId = stepContext.Context.Activity.Conversation.Id;
                    response       = rpaService.StartProcessWithParams(processDetails.ProcessSelected);
                    hasInputParams = true;
                }
                else
                {
                    response = rpaService.StartProcess(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
                }

                var error = false;
                if (string.IsNullOrEmpty(response.Content) || !response.IsSuccess)
                {
                    error = true;
                }
                if (error)
                {
                    if (hasInputParams)
                    {
                        processDetails.AttemptCount = processDetails.AttemptCount + 1;
                        if (processDetails.AttemptCount == 3)
                        {
                            processDetails.AttemptCount = 0;
                            //contact rpa support
                            return(await stepContext.ReplaceDialogAsync(nameof(StartProcessWithParamsErrorDialog), processDetails, cancellationToken));
                        }
                        else
                        {
                            rpaService.SaveConversationFlow(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
                            return(await stepContext.ReplaceDialogAsync(nameof(ParametersProcessDialog), processDetails, cancellationToken));
                        }
                    }
                    else
                    {
                        return(await stepContext.ReplaceDialogAsync(nameof(StartProcessErrorDialog), processDetails, cancellationToken));
                    }
                }
                else
                {
                    processDetails.AttemptCount = 0;
                    processDetails.Jobs         = JsonConvert.DeserializeObject <List <Job> >(response.Content);
                    var choices = rpaService.GetConfirmChoices();
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, processDetails.ProcessSelected.Name + "  process has started and you will be notified when it finishes." + Environment.NewLine + " Do you want to run another process?")
                    }, cancellationToken));
                }
            }
            else
            {
                processDetails.AttemptCount = 0;
                processDetails.Action       = "error";
                processDetails.Error        = "Cannot start " + processDetails.ProcessSelected.Name + " because the process is already running.";
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> SelectStrategyStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var msg            = string.Empty;
            var result         = stepContext.Result.ToString();
            var processDetails = (ProcessDetails)stepContext.Options;

            processDetails.Action = string.Empty;
            var rpaService   = new RPAService();
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "Confirm")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                result = promptOption.Value;
            }

            if (result.ToLower() == "yes" || result.ToLower() == "y")
            {
                //check if process is queued
                if (!string.IsNullOrEmpty(processDetails.ProcessSelected.queuedId))
                {
                    var cancel = JsonConvert.SerializeObject(new PromptOption {
                        Id = "Stop", Value = "3"
                    });
                    var choices = new List <Choice>
                    {
                        new Choice {
                            Value  = "3",
                            Action = new CardAction(ActionTypes.PostBack, "Cancel Queued Process", null, "Cancel Queued Process", "Cancel Queued Process", value: cancel, null)
                        }
                    };
                    choices.Add(rpaService.GetMainMenuOption());
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "Process " + processDetails.ProcessSelected.Name + " will be deleted from the queue and will not run." + Environment.NewLine + "Please click on below button to Cancel Queued Process")
                    }, cancellationToken));
                }
                else
                {
                    var stop = JsonConvert.SerializeObject(new PromptOption {
                        Id = "Stop", Value = "1"
                    });
                    var terminate = JsonConvert.SerializeObject(new PromptOption {
                        Id = "Stop", Value = "2"
                    });
                    var choices = new List <Choice>
                    {
                        new Choice {
                            Value  = "1",
                            Action = new CardAction(ActionTypes.PostBack, "Safely Stop Run", null, "Safely Stop Run", "Safely Stop Run", value: stop, null)
                        },
                        new Choice {
                            Value  = "2",
                            Action = new CardAction(ActionTypes.PostBack, "Terminate Process", null, "Terminate Process", "Terminate Process", value: terminate, null)
                        }
                    };
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "Please select one of the buttons below to Stop the Process:")
                    }, cancellationToken));
                }
            }
            else if (result.ToLower() == "no" || result.ToLower() == "n")
            {
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }
            else
            {
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
            }
        }
        private async Task <DialogTurnResult> ShowRunningProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rpaService     = new RPAService();
            var processDetails = (ProcessDetails)stepContext.Options;
            var result         = stepContext.Result.ToString();
            var promptOption   = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "availableProcesses" && promptOption.Id != "menu")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                result = promptOption.Value;
            }
            var _response = rpaService.GetUser(stepContext.Context.Activity.Conversation.Id);
            var user      = new List <User>();

            if (_response.IsSuccess)
            {
                user = JsonConvert.DeserializeObject <List <User> >(_response.Content);
            }
            if (result.ToLower() == "menu" || result.ToLower() == "m" /*"*****@*****.**"*/)
            {
                //save index
                user[0].u_last_index = "0";
                rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                //_user.u_last_index = 0;
                //await _userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);
                processDetails.Action = string.Empty;
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
            }
            else if (result.ToLower() == "load_more")
            {
                processDetails.LoadMore = true;
                return(await stepContext.ReplaceDialogAsync(nameof(StatusDialog), processDetails, cancellationToken));
            }
            else
            {
                processDetails.ProcessSelected = rpaService.GetSelectedProcess(processDetails.Processes, result);
                //check if a process was selected, or something was written
                if (!string.IsNullOrEmpty(processDetails.ProcessSelected.Sys_id))
                {
                    //save index
                    user[0].u_last_index = "0";
                    rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                    //_user.u_last_index = 0;
                    //await _userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);
                    var apiRequest = new APIRequest
                    {
                        ProcessId = processDetails.ProcessSelected.Sys_id
                    };
                    if (!string.IsNullOrEmpty(processDetails.ProcessSelected.queuedId))
                    {
                        apiRequest.Queued = true;
                    }

                    var jobIds     = new List <string>();
                    var releaseIds = new List <string>();
                    //if there was a process started
                    if (processDetails.Jobs.Count > 0)
                    {
                        foreach (var job in processDetails.Jobs)
                        {
                            foreach (var item in job.Result.Body.Value)
                            {
                                jobIds.Add(item.Id);
                            }
                        }
                        apiRequest.Ids   = jobIds;
                        apiRequest.IsJob = true;
                    }
                    else
                    {
                        foreach (var release in processDetails.ProcessSelected.Releases)
                        {
                            releaseIds.Add(release.sys_id);
                        }
                        apiRequest.Ids   = releaseIds;
                        apiRequest.IsJob = false;
                    }

                    var response = rpaService.ProcessStatus(apiRequest);
                    var text     = string.Empty;
                    if (response.IsSuccess)
                    {
                        var processSatus = JsonConvert.DeserializeObject <List <ProcessStatus> >(response.Content);

                        text  = processSatus.Count > 1 ? "Here are the status for " : "Here is the latest status for ";
                        text += processDetails.ProcessSelected.Name + " process." + Environment.NewLine;
                        foreach (var item in processSatus)
                        {
                            var include = "Total Transactions Processed: " + item.TotalTransactions + Environment.NewLine;                            /* +
                                                                                                                                                       * "Run Time: " + item.Runtime + Environment.NewLine;*/
                            if (item.ProcessType == "procedural")
                            {
                                include = string.Empty;
                            }
                            var endTime   = item.End != null ? "End Time: " + item.End + Environment.NewLine : string.Empty;
                            var startTime = item.Start != null ? "Start Time: " + item.Start + Environment.NewLine : string.Empty;

                            text +=
                                "Status: " + item.State.label + Environment.NewLine +
                                startTime +
                                endTime +
                                include +
                                "Total Transactions Successful: " + Convert.ToInt32(item.TotalTransSuccessful) + Environment.NewLine +
                                "Total Exceptions: " + Convert.ToInt32(item.TotalExceptions) + Environment.NewLine +
                                "Bot Name: " + item.Robot + Environment.NewLine +
                                "Started By: " + item.startedBy;
                        }
                    }
                    else
                    {
                        text = response.Content;
                    }
                    var choices = rpaService.GetConfirmChoices();
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, text + Environment.NewLine + "Do you want to check the status of another process?")

                                 /*Prompt = MessageFactory.Text(text + Environment.NewLine + "Do you want to check the status of another process?"),
                                  * Choices = ChoiceFactory.ToChoices(new List<string> { "Yes", "No" })*/
                    }, cancellationToken));
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
                }
            }
        }
        private async Task <DialogTurnResult> StopProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var msg            = string.Empty;
            var result         = stepContext.Result.ToString();
            var processDetails = (ProcessDetails)stepContext.Options;

            processDetails.Action = string.Empty;
            var rpaService   = new RPAService();
            var promptOption = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "Stop" && promptOption.Id != "mainMenu")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                result = promptOption.Value;
            }

            if (result.ToLower() == "1" || result.ToLower() == "2" || result.ToLower() == "3")
            {
                var response = new APIResponse();
                if (result.ToLower() == "3")
                {
                    response = rpaService.CancelQueuedProcess(processDetails.ProcessSelected);
                }
                else
                {
                    response = rpaService.StopProcess(processDetails.ProcessSelected.Sys_id, Convert.ToInt32(result));
                }

                if (response.IsSuccess)
                {
                    if (!string.IsNullOrEmpty(response.Content))
                    {
                        msg = response.Content;
                    }
                    else
                    {
                        if (result.ToLower() == "3")
                        {
                            msg = "Process " + processDetails.ProcessSelected.Name + " has been successfully deleted from the queue.";
                        }
                        else
                        {
                            msg = "Request to Stop Process " + processDetails.ProcessSelected.Name + " Submitted. Please allow a few minutes for the status to refresh.";
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(response.Error))
                    {
                        msg = response.Error;
                    }
                    else
                    {
                        msg = response.Message;
                    }
                }
                await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = MessageFactory.Text(msg)
                }, cancellationToken);

                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
            }


            return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
        }
        private async Task <DialogTurnResult> ConfirmStopProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rpaService     = new RPAService();
            var processDetails = (ProcessDetails)stepContext.Options;
            var result         = stepContext.Result.ToString();
            var promptOption   = new PromptOption();

            try
            {
                promptOption = JsonConvert.DeserializeObject <PromptOption>(stepContext.Result.ToString());
            }
            catch (Exception) { }

            if (!string.IsNullOrEmpty(promptOption.Id))
            {
                if (promptOption.Id != "availableProcesses" && promptOption.Id != "rpaSuport")
                {
                    processDetails.Action = "pastMenu";
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));
                }
                result = promptOption.Value;
            }

            var response = rpaService.GetUser(stepContext.Context.Activity.Conversation.Id);
            var user     = new List <User>();

            if (response.IsSuccess)
            {
                user = JsonConvert.DeserializeObject <List <User> >(response.Content);
            }
            //var _user = await _userAccessor.GetAsync(stepContext.Context, () => new User(), cancellationToken);
            switch (result.ToLower())
            {
            case "load_more":
                processDetails.LoadMore = true;
                return(await stepContext.ReplaceDialogAsync(nameof(StopProcessDialog), processDetails, cancellationToken));

            case "*****@*****.**":
                //save index
                user[0].u_last_index = "0";
                rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                //_user.u_last_index = 0;
                //await _userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);
                processDetails.Action = string.Empty;
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), processDetails, cancellationToken));

            default:
                processDetails.ProcessSelected = rpaService.GetSelectedProcess(processDetails.Processes, result);
                if (!string.IsNullOrEmpty(processDetails.ProcessSelected.Sys_id))
                {
                    //save index
                    user[0].u_last_index = "0";
                    rpaService.UpdateUser(user[0], stepContext.Context.Activity.Conversation.Id);
                    //_user.u_last_index = 0;
                    //await _userAccessor.SetAsync(stepContext.Context, _user, cancellationToken);
                    var choices = rpaService.GetConfirmChoices();
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, "You have selected " + processDetails.ProcessSelected.Name + ". Stop this process?")

                                 /*Prompt = MessageFactory.Text("You have selected " + processDetails.ProcessSelected.Name + ". Stop this process?"),
                                  * Choices = ChoiceFactory.ToChoices(new List<string> { "Yes", "No" })*/
                    }, cancellationToken));
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));
                }
            }
        }