Ejemplo n.º 1
0
        public static Task <TokenResponse> GetUserTokenAsync(this IDialogContext context, string connectionName, string magicCode)
        {
            var userId = context.Activity.From.Id;
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials());

            return(factory.MakeOAuthClient().OAuthApi.GetUserTokenAsync(userId, connectionName, magicCode));
        }
Ejemplo n.º 2
0
        public static Task <bool> SignOutUserAsync(this IDialogContext context, string connectionName)
        {
            var userId = context.Activity.From.Id;
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials());

            return(factory.MakeOAuthClient().OAuthApi.SignOutUserAsync(userId, connectionName));
        }
        /// <summary>
        /// Confirm swap shift submit.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <param name="obj">Swap shift object.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public async Task SwapShiftConfirmation(IDialogContext context, SwapShiftObj obj)
        {
            try
            {
                var     activity = context.Activity as Activity;
                JToken  token    = JObject.Parse(activity.Value.ToString());
                JObject tenant   = context.Activity.ChannelData as JObject;
                string  tenantId = tenant["tenant"].SelectToken("id").ToString();

                AdaptiveCard card = this.swapShiftCard.GetSwapShiftCnfCard(context, obj);

                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                var conversationId = context.Activity.Conversation.Id;
                var activityId     = context.Activity.ReplyToId;

                activity.Text  = null;
                activity.Value = null;
                activity.Attachments.Add(new Attachment()
                {
                    Content     = card,
                    ContentType = "application/vnd.microsoft.card.adaptive",
                });
                await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 4
0
        public IChannelCapability Detect()
        {
            var isEmulator = ConnectorClientFactory.IsEmulator(this.address);
            var capability = new ChannelCapability(supportButtons: !isEmulator);

            return(capability);
        }
Ejemplo n.º 5
0
        public static Task <TokenResponse> GetUserTokenAsync(this IDialogContext context, string connectionName)
        {
            var channelId = context.Activity.Conversation.Id;
            var userId    = context.Activity.From.Id;
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials());

            return(factory.MakeOAuthClient().GetOAuthApiEx().GetUserTokenAsync(channelId, userId, connectionName, null, default(CancellationToken)));
        }
        private async Task ShowAvailableShiftsCard(IDialogContext context, string command)
        {
            var     activity     = context.Activity as Activity;
            string  jSession     = string.Empty;
            JToken  token        = JObject.Parse(activity.Value.ToString());
            JObject tenant       = context.Activity.ChannelData as JObject;
            string  tenantId     = tenant["tenant"].SelectToken("id").ToString();
            string  personNumber = string.Empty;

            if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response))
            {
                personNumber = this.response.PersonNumber;
                jSession     = this.response.JsessionID;
            }

            var obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");

            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
            var conversationId = context.Activity.Conversation.Id;
            var activityId     = context.Activity.ReplyToId;

            List <ScheduleShift> scheduleShifts = new List <ScheduleShift>();
            List <Models.ResponseEntities.HyperFind.ResponseHyperFindResult> personIdentities = this.CreatePersonIdentities(obj.SelectedEmployee);

            context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
            UpcomingShift.Response scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, superSession, obj.Emp1FromDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture), obj.Emp1ToDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture), string.Empty, personIdentities);

            if (scheduleResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
            {
                await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
            }
            else
            {
                try
                {
                    var workingdaySchedule = scheduleResponse.Schedule.ScheduleItems.ScheduleShift;
                    var listOfEmps         = await this.hyperFindActivity.GetHyperFindQueryValues(tenantId, superSession, obj.Emp1FromDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture), obj.Emp1ToDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture), ApiConstants.ReportsToHyperFindQuery, ApiConstants.PersonalVisibilityCode);

                    var card = this.swapShiftCard.GetAvailableShiftsCard(context, workingdaySchedule.ToList(), listOfEmps.HyperFindResult);
                    activity.Text  = null;
                    activity.Value = null;
                    activity.Attachments.Add(new Attachment()
                    {
                        Content     = card,
                        ContentType = "application/vnd.microsoft.card.adaptive",
                    });
                }
                catch (Exception)
                {
                    activity.Text  = KronosResourceText.ScheduleError;
                    activity.Value = null;
                }
            }

            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

            context.Done(default(string));
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken cancellationToken)
        {
            // Get the current culture info to use in resource files
            if (activity.Locale != null)
            {
            }

            // This name is sent by MS Teams to indicate sign in. We do this so that we can pass handling to the right logic in the dialog. You can
            // set this to be whatever string you want.
            if (activity.Name == Constants.VerifyState)
            {
                activity.Text = Constants.SignInCompleteText;
            }

            if (activity.Type == ActivityTypes.Message || activity.Name == Constants.VerifyState)
            {
                if (activity.ChannelId == Constants.ActivityChannelId)
                {
                    JObject tenant   = activity.ChannelData as JObject;
                    string  tenantId = tenant["tenant"].SelectToken("id").ToString();
                    AppInsightsLogger.CustomEventTrace("Received Input Message for Bot", new Dictionary <string, string>()
                    {
                        { "TenantId", tenantId }, { "User", activity.From.Id }, { "methodName", "Post" }, { "Capability", "Bot" }
                    });
                }

                MicrosoftAppCredentials.TrustServiceUrl($"{activity.ServiceUrl}", DateTime.MaxValue);

                // Adding typing indicator to incoming message
                var typingReply = activity.CreateReply();
                typingReply.Type = ActivityTypes.Typing;
                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(typingReply), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                await factory.MakeConnectorClient().Conversations.ReplyToActivityAsync(typingReply);

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var dialog = scope.Resolve <IDialog <object> >();
                    await Conversation.SendAsync(activity, () => dialog, cancellationToken);
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var dialog = scope.Resolve <IDialog <object> >();
                    MicrosoftAppCredentials.TrustServiceUrl($"{activity.ServiceUrl}", DateTime.MaxValue);
                    await Conversation.SendAsync(activity, () => dialog);
                }
            }
            else if (activity.Type == ActivityTypes.Invoke)
            {
                return(await this.HandleInvokeMessagesAsync(activity, cancellationToken));
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Ejemplo n.º 8
0
        private async Task Previous(IDialogContext context)
        {
            var            activity               = context.Activity as Activity;
            JToken         token                  = JObject.Parse(activity.Value.ToString());
            var            currentPage            = Convert.ToInt32(token.SelectToken("CurrentPage"));
            var            employeesHashTable     = context.PrivateConversationData.GetValue <Hashtable>("EmployeeHashTable");
            var            employeesRoleHashTable = context.PrivateConversationData.GetValue <Hashtable>("EmployeeRoleHashTable");
            var            filtersHashTable       = context.PrivateConversationData.GetValue <Hashtable>("FiltersHashTable");
            var            pagewiseRequests       = context.PrivateConversationData.GetValue <Hashtable>("PagewiseRequests");
            ViewTorListObj obj = new ViewTorListObj
            {
                Employees        = employeesHashTable,
                EmployeesRoles   = employeesRoleHashTable,
                Filters          = filtersHashTable,
                TotalPages       = pagewiseRequests.Count,
                CurrentPageCount = currentPage - 1,
            };

            // string actionSet = "FRN";
            string actionSet = "FN";

            if (obj.CurrentPageCount != 1)
            {
                // actionSet = "FRNP";
                actionSet = "FNP";
            }

            obj.ConversationId = context.Activity.Conversation.Id;
            obj.ActivityId     = context.Activity.ReplyToId;

            var comments = context.PrivateConversationData.GetValue <List <Models.ResponseEntities.CommentList.Comment> >("Comments");
            var current  = JsonConvert.DeserializeObject <List <TimeOffResponse.GlobalTimeOffRequestItem> >(Convert.ToString(pagewiseRequests[(obj.CurrentPageCount - 1).ToString()]));
            var card     = this.supervisorTimeOffcard.GetCard(current, obj, actionSet, comments);

            var conversationId = context.Activity.Conversation.Id;
            var activityId     = context.Activity.ReplyToId;

            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));

            activity.Text  = null;
            activity.Value = null;
            activity.Attachments.Add(new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive",
            });
            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

            context.Done(default(string));
        }
        /// <summary>
        /// Send approval notifications.
        /// </summary>
        /// <param name="tenantId">Tenant Id.</param>
        /// <param name="jsession">J Session.</param>
        /// <param name="context">Dialog context.</param>
        /// <param name="conversationId">Conversation Id to which notification has to be sent.</param>
        /// <param name="note">Note entered.</param>
        /// <param name="obj">Swap shift object.</param>
        /// <param name="approvalType">Approval type: 1-Employee, 2-Supervisor.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public async Task SendApprovalNotification(string tenantId, string jsession, IDialogContext context, string conversationId, string note, SwapShiftObj obj, int approvalType)
        {
            try
            {
                var    activity = context.Activity as Activity;
                JToken token    = JObject.Parse(activity.Value.ToString());
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                var channelData = new TeamsChannelData
                {
                    Tenant = new TenantInfo()
                    {
                        Id = tenantId,
                    },
                };

                var message = Activity.CreateMessageActivity();
                message.From = new ChannelAccount(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword);

                MicrosoftAppCredentials.TrustServiceUrl(context.Activity.ServiceUrl);
                message.ChannelData  = channelData;
                message.ChannelId    = Constants.ActivityChannelId;
                message.Conversation = new ConversationAccount(
                    conversationType: "personal",
                    id: conversationId,
                    isGroup: false);
                var comments = await this.commentsActivity.GetComments(tenantId, superSession);

                AdaptiveCard card = this.swapShiftCard.GetNotificationCard(context, obj, note, comments, approvalType);

                message.Attachments.Add(new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = card,
                });

                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                await factory.MakeConnectorClient().Conversations.SendToConversationAsync((Activity)message);
            }
            catch (Exception)
            {
                await context.PostAsync("Something went wrong while sending notification");

                throw;
            }
        }
        private async Task ShowSearchFilterCard(IDialogContext context, string command)
        {
            var    activity = context.Activity as Activity;
            string jSession = string.Empty;

            JObject tenant       = context.Activity.ChannelData as JObject;
            string  tenantId     = tenant["tenant"].SelectToken("id").ToString();
            string  personNumber = string.Empty;

            if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response))
            {
                personNumber = this.response.PersonNumber;
                jSession     = this.response.JsessionID;
            }

            var obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");

            context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);

            var allJob = await this.swapShiftActivity.LoadAllJobs(tenantId, superSession, personNumber, obj.Emp1FromDateTime.ToString("M/dd/yyyy", CultureInfo.InvariantCulture), obj.Emp1FromDateTime.ToString("M/dd/yyyy", CultureInfo.InvariantCulture), obj.Emp1FromDateTime.ToString("hh:mmtt", CultureInfo.InvariantCulture), obj.Emp1ToDateTime.ToString("hh:mmtt", CultureInfo.InvariantCulture));

            Models.ResponseEntities.SwapShift.LoadEligibleEmployees.Response loadEligibleEmps;

            loadEligibleEmps = await this.swapShiftActivity.LoadEligibleEmployees(tenantId, superSession, personNumber, obj.Emp1FromDateTime.ToString("M/dd/yyyy", CultureInfo.InvariantCulture), obj.Emp1FromDateTime.ToString("hh:mmtt", CultureInfo.InvariantCulture), obj.Emp1ToDateTime.ToString("hh:mmtt", CultureInfo.InvariantCulture));

            var card = this.swapShiftCard.GetFilterCard(context, allJob, loadEligibleEmps);

            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
            var conversationId = context.Activity.Conversation.Id;
            var activityId     = context.Activity.ReplyToId;

            activity.Text  = null;
            activity.Value = null;
            activity.Attachments.Add(new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive",
            });
            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

            context.Done(default(string));
        }
        private async Task Previous(IDialogContext context)
        {
            var    activity                 = context.Activity as Activity;
            JToken token                    = JObject.Parse(activity.Value.ToString());
            var    currentPage              = Convert.ToString(token.SelectToken("CurrentPage"));
            var    payPeriod                = Convert.ToString(token.SelectToken("PayPeriod"));
            var    conversationId           = context.Activity.Conversation.Id;
            var    activityId               = context.Activity.ReplyToId;
            var    card                     = this.adaptiveTeamOvertimesCard.GetCard(context, payPeriod, string.Empty, string.Empty, Convert.ToInt32(currentPage) - 1);
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));

            activity.Text  = null;
            activity.Value = null;
            activity.Attachments.Add(new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive",
            });
            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
        }
Ejemplo n.º 12
0
        public async Task EmitIncidentAsync(IcmIncident incident)
        {
            var cert = await _keyVault.GetCertificateAsync(_connectorCertificateName);

            var incidentToSend = GetIncidentToSend(incident);

            using var client = ConnectorClientFactory.CreateClient(_uri, cert);
            try
            {
                var result = client.AddOrUpdateIncident2(_connectorId, incidentToSend, RoutingOptions.None);
                if (result.Status != IncidentAddUpdateStatus.AddedNew)
                {
                    throw new Exception($"Result status does not indicate success: {result.Status}.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to submit incident to IcM:\n" + e.ToString());
                throw;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Get previous 5 vacation requests.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <returns>Task.</returns>
        private async Task ShowAllTimeOffOnPrevious(IDialogContext context)
        {
            var       activity       = context.Activity as Activity;
            JToken    token          = JObject.Parse(activity.Value.ToString());
            var       currentPage    = Convert.ToInt32(token.SelectToken("CurrentPage"));
            Hashtable pages          = context.PrivateConversationData.GetValue <Hashtable>("PagewiseAllTimeOffRequests");
            var       card           = this.cardObj.GetCard(JsonConvert.DeserializeObject <IList <EmployeeGlobalTimeOffRequestItem> >(Convert.ToString(pages[(currentPage - 1).ToString()])), (currentPage - 1) == 1 ? "TN" : "TNP", currentPage - 1, 2);
            var       conversationId = context.Activity.Conversation.Id;
            var       activityId     = context.Activity.ReplyToId;

            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));

            activity.Text  = null;
            activity.Value = null;
            activity.Attachments.Add(new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive",
            });
            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
        }
Ejemplo n.º 14
0
        public async Task EmitIncidentAsync(IcmIncident incident)
        {
            if (incident.CacheTimeToLive is not null)
            {
                if (_cachedIcms.Contains(incident.Title))
                {
                    // Update TTL and return.
                    _cachedIcms.Add(incident.Title, incident.CacheTimeToLive.Value);
                    return;
                }
                else
                {
                    // Add to cached incidents.
                    _cachedIcms.Add(incident.Title, incident.CacheTimeToLive.Value);
                }
            }

            var cert = await _keyVault.GetCertificateAsync(_connectorCertificateName);

            var incidentToSend = GetIncidentToSend(incident);

            using var client = ConnectorClientFactory.CreateClient(_uri, cert);
            try
            {
                var result = client.AddOrUpdateIncident2(_connectorId, incidentToSend, RoutingOptions.None);
                if (result.Status != IncidentAddUpdateStatus.AddedNew &&
                    // Discarded means that we're updating hit count or it was suppressed because it's too soon
                    // since we updated hit count last and the incident is still active.
                    result.Status != IncidentAddUpdateStatus.Discarded)
                {
                    throw new Exception($"Result status does not indicate success: {result.Status}.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to submit incident to IcM:\n" + e.ToString());
                throw;
            }
        }
        /// <summary>
        /// Send OAuth card to user for sign in.
        /// </summary>
        /// <param name="context">Dialog Context.</param>
        /// <param name="activity">Activity object.</param>
        /// <returns>sign in card.</returns>
        public async Task SendAuthCardAsync(IDialogContext context, Activity activity)
        {
            var     buttonLabel = $"{KronosResourceText.ClickLogin}";
            var     reply       = ((Activity)context.Activity).CreateReply();
            JObject tenant      = activity.ChannelData as JObject;
            string  tenantId    = tenant["tenant"].SelectToken("id").ToString();
            string  teamsUserId = activity.From.Id;
            string  convId      = activity.Conversation.Id;
            var     loginUrl    = $"{ConfigurationManager.AppSettings["BaseUri"].ToString()}/Login?tid={tenantId}";

            reply.Attachments = new List <Attachment>()
            {
                new Attachment()
                {
                    ContentType = HeroCard.ContentType,
                    Content     = new HeroCard()
                    {
                        Title    = KronosResourceText.SignInLabel,
                        Subtitle = KronosResourceText.LoginToContinue,
                        Buttons  = new CardAction[]
                        {
                            new CardAction()
                            {
                                Title = buttonLabel, Value = loginUrl, Type = ActionTypes.Signin
                            },
                        },
                    },
                },
            };

            // Create the ConnectorClientFactory
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(reply), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
            var msgToUpdate = await factory.MakeConnectorClient().Conversations.SendToConversationAsync(reply.Conversation.Id, reply);

            // saving the activity Id to update the card after successful authentication
            context.PrivateConversationData.SetValue(activity.From.Id + "SignIn", msgToUpdate.Id);
        }
Ejemplo n.º 16
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity != null)
            {
                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(activity), new MicrosoftAppCredentials(_configuration, _httpContextAccessor, _memoryCache));

                // one of these will have an interface and process it
                switch (activity.GetActivityType())
                {
                case ActivityTypes.Message:

                    using (IConnectorClient connectorClient = factory.MakeConnectorClient())
                    {
                        IBotToUser botToUser = new AlwaysSendDirect_BotToUser(activity, connectorClient);
                        await botToUser.PostAsync($"HELLO, {activity.From.Name}!");

                        // .. OR NOT HELPER EXTENSION:
                        //IMessageActivity msgActivity = botToUser.MakeMessage();
                        //msgActivity.Text = "HELLO!!! HI!";
                        //await botToUser.PostAsync(msgActivity);
                    }

                    break;

                case ActivityTypes.ConversationUpdate:
                case ActivityTypes.ContactRelationUpdate:
                case ActivityTypes.Typing:
                case ActivityTypes.DeleteUserData:
                case ActivityTypes.Ping:
                default:
                    //LOG: Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                    break;
                }
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
Ejemplo n.º 17
0
        public static Task <string> GetSignInUrlAsync(this IDialogContext context, string connectionName)
        {
            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials());

            return(factory.MakeOAuthClient().OAuthApi.GetSignInLinkAsync(context.Activity, connectionName));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Create time off request draft and submit it.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <returns>Task.</returns>
        private async Task SubmitAdvancedTimeOffRequest(IDialogContext context)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            var     activity = context.Activity as Activity;
            JToken  token    = JObject.Parse(activity.Value.ToString());
            JObject tenant   = context.Activity.ChannelData as JObject;
            string  tenantId = tenant["tenant"].SelectToken("id").ToString();

            var advancedObj = context.PrivateConversationData.GetValue <AdvancedTimeOff>("AdvancedRequestObj");

            advancedObj.Comment = (string)token.SelectToken("Comment");
            advancedObj.Note    = (string)token.SelectToken("note");

            if (!string.IsNullOrEmpty(advancedObj.Note) && string.IsNullOrEmpty(advancedObj.Comment))
            {
                await context.PostAsync(Resources.KronosResourceText.CommentSelectionValidation);
            }
            else
            {
                context.PrivateConversationData.SetValue("AdvancedRequestObj", advancedObj);
                DateTime.TryParse(advancedObj.sdt, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime sdt);
                DateTime.TryParse(advancedObj.edt, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime edt);

                edt = edt.AddHours(23);
                edt = edt.AddMinutes(59);
                string querySpan = sdt.ToString("M/d/yyyy", CultureInfo.InvariantCulture) + "-" + edt.ToString("M/d/yyyy", CultureInfo.InvariantCulture);

                var startDate = sdt.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);
                var endDate   = edt.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);

                advancedObj.sdt = startDate;
                advancedObj.edt = endDate;

                string jSessionId   = this.response?.JsessionID;
                string personNumber = this.response?.PersonNumber;
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);

                Models.ResponseEntities.TimeOff.AddResponse.Response timeOffResponse = await this.timeOffActivity.AdvancedTimeOffRequest(tenantId, jSessionId, personNumber, advancedObj);

                if (timeOffResponse?.Status == ApiConstants.Failure)
                {
                    if (timeOffResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                    {
                        await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                    }
                    else
                    {
                        await context.PostAsync(Resources.KronosResourceText.UnableToProceed);
                    }
                }

                if (timeOffResponse?.Status == ApiConstants.Success)
                {
                    Models.ResponseEntities.TimeOff.SubmitResponse.Response submitTimeOffResponse = await this.timeOffActivity.SubmitTimeOffRequest(tenantId, jSessionId, personNumber, timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id, querySpan);

                    if (submitTimeOffResponse?.Status == ApiConstants.Failure)
                    {
                        if (submitTimeOffResponse.Error.DetailErrors.Error.FirstOrDefault().ErrorCode == "611")
                        {
                            await context.PostAsync(Resources.KronosResourceText.TimeOffRequestOverlap);
                        }
                        else
                        {
                            await context.PostAsync(Resources.KronosResourceText.UnableToProceed);
                        }
                    }

                    if (submitTimeOffResponse?.Status == ApiConstants.Success)
                    {
                        var conversationId = context.Activity.Conversation.Id;
                        var activityId     = context.Activity.ReplyToId;

                        IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                        var card = this.timeOffCard.ShowTimeOffSuccessCard(context, timeOffResponse, advancedObj);
                        var supervisorConversationId = await this.commonActivity.GetConversationId(personNumber, tenantId, superSession, activity.ChannelId);

                        var timePeriod = advancedObj.duration.ToLowerInvariant() == Constants.FullDay.ToLowerInvariant() ? Constants.FullDay : advancedObj.duration.ToLowerInvariant() == Constants.HalfDay.ToLowerInvariant() ? Constants.HalfDay : advancedObj.duration.ToLowerInvariant() == Constants.FirstHalfDay.ToLowerInvariant() ? Constants.FirstHalfDay : Constants.Hours;
                        if (advancedObj.duration.ToLowerInvariant() == Constants.Hours.ToLowerInvariant())
                        {
                            var shr   = Convert.ToInt32(advancedObj.StartTime.Split(' ')[0].Split(':')[0]);
                            var smin  = Convert.ToInt32(advancedObj.StartTime.Split(' ')[0].Split(':')[1]);
                            var ehr   = Convert.ToInt32(advancedObj.EndTime.Split(' ')[0].Split(':')[0]);
                            var emin  = Convert.ToInt32(advancedObj.EndTime.Split(' ')[0].Split(':')[1]);
                            var stime = new DateTime(2000, 1, 1, shr, smin, 0);
                            var etime = new DateTime(2000, 1, 1, ehr, emin, 0);
                            timePeriod += " (" + stime.ToString("h:mm tt", CultureInfo.InvariantCulture) + " to " + etime.ToString("h:mm tt", CultureInfo.InvariantCulture) + ")";
                        }

                        var period   = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault();
                        var duration = period.Duration == Constants.full_day ? Constants.FullDay : period.Duration == Constants.half_day ? Constants.HalfDay : period.Duration == Constants.first_half_day ? Constants.FirstHalfDay : Constants.Hours;
                        if (supervisorConversationId != null)
                        {
                            await this.SendNotificationToSupervisor(tenantId, personNumber, timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id, supervisorConversationId, advancedObj.DeductFrom, context, duration, advancedObj);
                        }

                        try
                        {
                            activity.Text  = null;
                            activity.Value = null;
                            activity.Attachments.Add(new Attachment()
                            {
                                Content     = card,
                                ContentType = "application/vnd.microsoft.card.adaptive",
                            });
                            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

                            if (supervisorConversationId == null)
                            {
                                await context.PostAsync(Resources.KronosResourceText.SupervisorNotFoundForNotification);
                            }

                            context.PrivateConversationData.RemoveValue("AdvancedRequestObj");
                        }
                        catch (Exception)
                        {
                            return;
                        }
                    }
                }
            }

            context.Done(default(string));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Create time off request draft and submit it.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <returns>Task.</returns>
        private async Task SubmitTimeOffRequest(IDialogContext context)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            var     activity = context.Activity as Activity;
            JToken  token    = JObject.Parse(activity.Value.ToString());
            JObject tenant   = context.Activity.ChannelData as JObject;
            string  tenantId = tenant["tenant"].SelectToken("id").ToString();

            DateTime.TryParse((string)token.SelectToken("sdt"), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime sdt);
            DateTime.TryParse((string)token.SelectToken("edt"), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime edt);
            string querySpan = sdt.ToString("M/d/yyyy", CultureInfo.InvariantCulture) + "-" + edt.ToString("M/d/yyyy", CultureInfo.InvariantCulture);

            edt = edt.AddHours(23);
            edt = edt.AddMinutes(59);
            var startDate = sdt.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);
            var endDate   = edt.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);

            string jSessionId   = this.response?.JsessionID;
            string personNumber = this.response?.PersonNumber;

            context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
            Models.ResponseEntities.TimeOff.AddResponse.Response timeOffResponse = await this.timeOffActivity.TimeOffRequest(tenantId, jSessionId, startDate, endDate, personNumber, (string)token.SelectToken("reason"));

            if (timeOffResponse?.Status == ApiConstants.Failure)
            {
                if (timeOffResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                {
                    await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                }
            }

            if (timeOffResponse?.Status == ApiConstants.Success)
            {
                Models.ResponseEntities.TimeOff.SubmitResponse.Response submitTimeOffResponse = await this.timeOffActivity.SubmitTimeOffRequest(tenantId, jSessionId, personNumber, timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id, querySpan);

                if (submitTimeOffResponse?.Status == ApiConstants.Failure)
                {
                    if (submitTimeOffResponse?.Error.DetailErrors.Error.FirstOrDefault().ErrorCode == "611")
                    {
                        await context.PostAsync(Resources.KronosResourceText.TimeOffRequestOverlap);
                    }
                    else
                    {
                        await context.PostAsync(Resources.KronosResourceText.UnableToProceed);
                    }
                }

                if (submitTimeOffResponse?.Status == ApiConstants.Success)
                {
                    var conversationId = context.Activity.Conversation.Id;
                    var activityId     = context.Activity.ReplyToId;

                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                    var card = this.timeOffCard.ShowTimeOffSuccessCard(context, timeOffResponse, null);

                    var supervisorConversationId = await this.commonActivity.GetConversationId(personNumber, tenantId, superSession, activity.ChannelId);

                    if (supervisorConversationId != null)
                    {
                        await this.SendNotificationToSupervisor(tenantId, personNumber, timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id, supervisorConversationId, (string)token.SelectToken("reason"), context, "Full Day", null);
                    }

                    try
                    {
                        activity.Text  = null;
                        activity.Value = null;
                        activity.Attachments.Add(new Attachment()
                        {
                            Content     = card,
                            ContentType = "application/vnd.microsoft.card.adaptive",
                        });
                        await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

                        if (supervisorConversationId == null)
                        {
                            await context.PostAsync(Resources.KronosResourceText.SupervisorNotFoundForNotification);
                        }
                    }
                    catch (Exception)
                    {
                        return;
                    }
                    finally
                    {
                        context.PrivateConversationData.RemoveValue("AdvancedRequestObj");
                    }
                }
            }

            context.Done(default(string));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Send approval notification to supervisor.
        /// </summary>
        /// <param name="tenantId">Tenand Id.</param>
        /// <param name="personNumber">Person number of employee who raised time off request.</param>
        /// <param name="reqId">Request Id generated for submitted request.</param>
        /// <param name="conversationId">Supervisor conversation Id to send notification.</param>
        /// <param name="paycode">Pay code for request.</param>
        /// <param name="context">Dialog context.</param>
        /// <param name="timePeriod">Time period for request.</param>
        /// <param name="advancedTimeOff">Advanced time off request object ('null' for normal time off request).</param>
        /// <returns>Task.</returns>
        public async Task SendNotificationToSupervisor(string tenantId, string personNumber, string reqId, string conversationId, string paycode, IDialogContext context, string timePeriod, AdvancedTimeOff advancedTimeOff)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            try
            {
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                var      activity = context.Activity as Activity;
                JToken   token = JObject.Parse(activity.Value.ToString());
                DateTime sdt, edt;
                string   note = null;
                if (advancedTimeOff == null)
                {
                    DateTime.TryParse((string)token.SelectToken("sdt"), CultureInfo.InvariantCulture, DateTimeStyles.None, out sdt);
                    DateTime.TryParse((string)token.SelectToken("edt"), CultureInfo.InvariantCulture, DateTimeStyles.None, out edt);
                }
                else
                {
                    note = advancedTimeOff.Note;
                    DateTime.TryParse(advancedTimeOff.sdt, CultureInfo.InvariantCulture, DateTimeStyles.None, out sdt);
                    DateTime.TryParse(advancedTimeOff.edt, CultureInfo.InvariantCulture, DateTimeStyles.None, out edt);
                }
                edt = edt.AddDays(1);
                var requests = await this.timeOffActivity.GetTimeOffRequestDetails(tenantId, superSession, sdt.ToString("M/d/yyyy", CultureInfo.InvariantCulture) + "-" + edt.ToString("M/d/yyyy", CultureInfo.InvariantCulture), personNumber);

                var filteredRequest = (from d in requests.RequestMgmt.RequestItems.GlobalTimeOffRequestItem where d.Id == reqId select d).FirstOrDefault();

                var requestorInfo = await this.roleActivity.GetPersonInfo(tenantId, personNumber, superSession);

                for (int i = 0; i < filteredRequest.RequestStatusChanges.RequestStatusChange.Count; i++)
                {
                    var personInfo = await this.roleActivity.GetPersonInfo(tenantId, filteredRequest.RequestStatusChanges.RequestStatusChange[i].User.PersonIdentity.PersonNumber, superSession);

                    filteredRequest.RequestStatusChanges.RequestStatusChange[i].User.PersonIdentity.PersonNumber = personInfo.PersonInformation.PersonDat.PersonDetail.FullName;
                }

                var comments = await this.commentsActivity.GetComments(tenantId, superSession);

                var channelData = new TeamsChannelData
                {
                    Tenant = new TenantInfo()
                    {
                        Id = tenantId,
                    },
                };

                var message = Activity.CreateMessageActivity();
                message.From = new ChannelAccount(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword);

                MicrosoftAppCredentials.TrustServiceUrl(context.Activity.ServiceUrl);
                message.ChannelData  = channelData;
                message.ChannelId    = Constants.ActivityChannelId;
                message.Conversation = new ConversationAccount(
                    conversationType: "personal",
                    id: conversationId,
                    isGroup: false);

                AdaptiveCard card = this.timeOffCard.GetSupervisorNotificationCard(context, reqId, personNumber, paycode, timePeriod, filteredRequest, note, requestorInfo.PersonInformation.PersonDat.PersonDetail.FullName, comments, advancedTimeOff);

                message.Attachments.Add(new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = card,
                });

                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                await factory.MakeConnectorClient().Conversations.SendToConversationAsync((Activity)message);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 21
0
        private async Task SubmitTimeOffApproval(IDialogContext context, string command)
        {
            try
            {
                var     activity = context.Activity as Activity;
                JToken  token    = JObject.Parse(activity.Value.ToString()).SelectToken("data");
                JObject tenant   = context.Activity.ChannelData as JObject;
                string  tenantId = tenant["tenant"].SelectToken("id").ToString();

                string jSessionId     = this.response?.JsessionID;
                string personNumber   = (string)token.SelectToken("PersonNumber");
                string querySpan      = (string)token.SelectToken("QueryDateSpan");
                string reqId          = (string)token.SelectToken("RequestId");
                string index          = (string)token.SelectToken("Index");
                string currentPage    = (string)token.SelectToken("CurrentPage");
                string comment        = (string)token.SelectToken("Comment");
                string note           = (string)token.SelectToken("note");
                string conversationId = (string)token.SelectToken("conversationId");
                string activityId     = (string)token.SelectToken("activityId");
                command = command.ToLowerInvariant() == Constants.TORApproveRequest.ToLowerInvariant() ? Constants.ApproveTimeoff : Constants.RefuseTimeoff;
                Models.ResponseEntities.TimeOff.SubmitResponse.Response response = await this.timeOffRequestActivity.SubmitApproval(tenantId, jSessionId, reqId, personNumber, command, querySpan, comment, note);

                if (response?.Status == ApiConstants.Failure)
                {
                    if (response.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                    {
                        await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                    }
                    else
                    {
                        await context.PostAsync(response.Error.DetailErrors.Error.FirstOrDefault().Message.Substring(9));
                    }
                }

                if (response?.Status == ApiConstants.Success)
                {
                    var empConversationId = await this.commonActivity.GetEmpConversationId(personNumber, tenantId, jSessionId, activity.ChannelId);

                    var status = command.ToLowerInvariant() == Constants.ApproveTimeoff.ToLowerInvariant() ? Constants.Approved.ToUpper() : Constants.Refused.ToUpper();

                    if (empConversationId == null)
                    {
                        await context.PostAsync(Resources.KronosResourceText.EmpNotFoundForNotification);
                    }
                    else
                    {
                        await this.SendApprovalResponseNotiToEmployee(tenantId, context, status, empConversationId, note, querySpan, reqId);
                    }

                    var pagewiseRequests = context.PrivateConversationData.GetValue <Hashtable>("PagewiseRequests");
                    var toChange         = JsonConvert.DeserializeObject <List <TimeOffResponse.GlobalTimeOffRequestItem> >(Convert.ToString(pagewiseRequests[Convert.ToString(Convert.ToInt32(currentPage) - 1)]));
                    for (int i = 0; i < toChange.Count; i++)
                    {
                        if (i == Convert.ToInt32(index))
                        {
                            toChange[i].StatusName = status;
                        }
                    }

                    pagewiseRequests[Convert.ToString(Convert.ToInt32(currentPage) - 1)] = JsonConvert.SerializeObject(toChange).ToString();
                    context.PrivateConversationData.SetValue("PagewiseRequests", pagewiseRequests);
                    var            employeesHashTable     = context.PrivateConversationData.GetValue <Hashtable>("EmployeeHashTable");
                    var            employeesRoleHashTable = context.PrivateConversationData.GetValue <Hashtable>("EmployeeRoleHashTable");
                    var            filtersHashTable       = context.PrivateConversationData.GetValue <Hashtable>("FiltersHashTable");
                    ViewTorListObj obj = new ViewTorListObj
                    {
                        Employees        = employeesHashTable,
                        Filters          = filtersHashTable,
                        EmployeesRoles   = employeesRoleHashTable,
                        TotalPages       = pagewiseRequests.Count,
                        CurrentPageCount = Convert.ToInt32(currentPage),
                    };

                    // string actionSet = "FR";
                    string actionSet = "F";
                    if (obj.TotalPages != 1)
                    {
                        if (obj.CurrentPageCount < obj.TotalPages && obj.CurrentPageCount > 1)
                        {
                            // actionSet = "FRNP";
                            actionSet = "FNP";
                        }
                        else if (obj.CurrentPageCount == 1)
                        {
                            // actionSet = "FRN";
                            actionSet = "FN";
                        }
                        else if (obj.CurrentPageCount == obj.TotalPages)
                        {
                            // actionSet = "FRP";
                            actionSet = "FP";
                        }
                    }

                    var          comments = context.PrivateConversationData.GetValue <List <Models.ResponseEntities.CommentList.Comment> >("Comments");
                    AdaptiveCard card     = new AdaptiveCard("1.0");
                    card = this.supervisorTimeOffcard.GetCard(JsonConvert.DeserializeObject <List <TimeOffResponse.GlobalTimeOffRequestItem> >(Convert.ToString(pagewiseRequests[Convert.ToString(obj.CurrentPageCount - 1)])), obj, actionSet, comments);

                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                    activity.Text  = null;
                    activity.Value = null;
                    activity.Attachments.Add(new Attachment()
                    {
                        Content     = card,
                        ContentType = "application/vnd.microsoft.card.adaptive",
                    });
                    await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
                }

                context.Done(default(string));
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Send notification to employee once supervisor approves/refuses time off request.
        /// </summary>
        /// <param name="tenantId">Tenant Id.</param>
        /// <param name="context">Dialog context.</param>
        /// <param name="status">Approval status.</param>
        /// <param name="conversationId">Conversation Id of requestor.</param>
        /// <param name="note">Note entered while approval.</param>
        /// <param name="queryDateSpan">Query date span for request.</param>
        /// <param name="reqId">Request Id of request.</param>
        /// <returns>Task.</returns>
        public async Task SendApprovalResponseNotiToEmployee(string tenantId, IDialogContext context, string status, string conversationId, string note, string queryDateSpan, string reqId)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            try
            {
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                var    activity     = context.Activity as Activity;
                JToken token        = JObject.Parse(activity.Value.ToString());
                string personNumber = (string)token.SelectToken("data").SelectToken("PersonNumber");
                string empName      = (string)token.SelectToken("data").SelectToken("EmpName");
                string jSessionId   = this.response?.JsessionID;

                var info = await this.commonActivity.GetJobAssignment(personNumber, tenantId, superSession);

                var reviewer    = info?.JobAssign?.jobAssignDetData?.JobAssignDet?.SupervisorName;
                var channelData = new TeamsChannelData
                {
                    Tenant = new TenantInfo()
                    {
                        Id = tenantId,
                    },
                };

                var message = Activity.CreateMessageActivity();
                message.From = new ChannelAccount(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword);

                MicrosoftAppCredentials.TrustServiceUrl(context.Activity.ServiceUrl);
                message.ChannelData  = channelData;
                message.ChannelId    = Constants.ActivityChannelId;
                message.Conversation = new ConversationAccount(
                    conversationType: "personal",
                    id: conversationId,
                    isGroup: false);

                var requests = await this.timeOffRequestActivity.GetTimeOffRequestDetails(tenantId, superSession, queryDateSpan, personNumber);

                var filteredRequest = (from d in requests.RequestMgmt.RequestItems.GlobalTimeOffRequestItem where d.Id == reqId select d).FirstOrDefault();

                for (int i = 0; i < filteredRequest.RequestStatusChanges.RequestStatusChange.Count; i++)
                {
                    var personInfo = await this.roleActivity.GetPersonInfo(tenantId, filteredRequest.RequestStatusChanges.RequestStatusChange[i].User.PersonIdentity.PersonNumber, superSession);

                    filteredRequest.RequestStatusChanges.RequestStatusChange[i].User.PersonIdentity.PersonNumber = personInfo.PersonInformation.PersonDat.PersonDetail.FullName;
                }

                AdaptiveCard card = this.supervisorTimeOffcard.GetEmployeeNotificationCard(context, status, reviewer, note, filteredRequest);

                message.Attachments.Add(new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = card,
                });

                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                await factory.MakeConnectorClient().Conversations.SendToConversationAsync((Activity)message);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 23
0
        private async Task ApplyFilter(IDialogContext context, string command)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            try
            {
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                var     activity              = context.Activity as Activity;
                JObject tenant                = context.Activity.ChannelData as JObject;
                string  tenantId              = tenant["tenant"].SelectToken("id").ToString();
                string  jSessionId            = this.response?.JsessionID;
                string  personNumber          = this.response?.PersonNumber;
                JToken  token                 = JObject.Parse(activity.Value.ToString());
                var     empName               = Convert.ToString(token.SelectToken("EmpName"));
                var     startDate             = Convert.ToString(token.SelectToken("StartDate"));
                var     endDate               = Convert.ToString(token.SelectToken("EndDate"));
                var     showCompletedRequests = Convert.ToString(token.SelectToken("ShowCompletedToggle"));
                var     filters               = context.PrivateConversationData.ContainsKey("FiltersHashTable") ? context.PrivateConversationData.GetValue <Hashtable>("FiltersHashTable") : new Hashtable();
                if (command.ToLowerInvariant() == Constants.TORRemoveEmpName.ToLowerInvariant())
                {
                    empName               = string.Empty;
                    startDate             = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[0] : null;
                    endDate               = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[1] : null;
                    showCompletedRequests = filters.ContainsKey("ShowCompletedRequests") ? Convert.ToString(filters["ShowCompletedRequests"]) : "false";
                }

                if (command.ToLowerInvariant() == Constants.TORRemoveDateRange.ToLowerInvariant())
                {
                    startDate = endDate = null;
                    empName   = filters.ContainsKey("EmpName") ? Convert.ToString(filters["EmpName"]) : string.Empty;
                }

                if (command.ToLowerInvariant() == Constants.TORRemoveShowCompletedRequests.ToLowerInvariant())
                {
                    empName               = filters.ContainsKey("EmpName") ? Convert.ToString(filters["EmpName"]) : string.Empty;
                    startDate             = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[0] : null;
                    endDate               = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[1] : null;
                    showCompletedRequests = "false";
                }

                if (command.ToLowerInvariant() == Constants.TORListRefresh.ToLowerInvariant())
                {
                    empName               = filters.ContainsKey("EmpName") ? Convert.ToString(filters["EmpName"]) : string.Empty;
                    startDate             = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[0] : null;
                    endDate               = filters.ContainsKey("DateRange") ? Convert.ToString(filters["DateRange"]).Split(';')[1] : null;
                    showCompletedRequests = filters.ContainsKey("ShowCompletedRequests") ? Convert.ToString(filters["ShowCompletedRequests"]) : "false";
                }

                AdaptiveCard card = new AdaptiveCard("1.0");
                DateTime     sdt1 = DateTime.Now;
                DateTime     edt  = DateTime.Now;
                if (!string.IsNullOrEmpty(startDate) && string.IsNullOrEmpty(endDate))
                {
                    await context.PostAsync(Resources.KronosResourceText.SelectEndDate);

                    context.Done(default(string));
                    return;
                }

                if (string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
                {
                    await context.PostAsync(Resources.KronosResourceText.SelectStartDate);

                    context.Done(default(string));
                    return;
                }

                var employeesResult = await this.hyperFindActivity.GetHyperFindQueryValues(tenantId, jSessionId, DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), "Report", "Private");

                if (employeesResult.Status == ApiConstants.Failure && employeesResult.Error.ErrorCode == ApiConstants.UserNotLoggedInError)
                {
                    await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                }

                if (employeesResult.Status == ApiConstants.Success)
                {
                    Hashtable employeesHashTable     = new Hashtable();
                    Hashtable employeesRoleHashTable = new Hashtable();
                    Hashtable filtersHashTable       = new Hashtable();
                    List <Models.ResponseEntities.HyperFind.ResponseHyperFindResult> filteredEmployees = new List <Models.ResponseEntities.HyperFind.ResponseHyperFindResult>();
                    if (!string.IsNullOrEmpty(empName))
                    {
                        var empSplit = empName.Split(';');
                        filteredEmployees = employeesResult.HyperFindResult.Where(n => empSplit.Any(m => n.FullName.ToLower().Contains(m.ToLower()))).ToList();
                    }
                    else
                    {
                        filteredEmployees = employeesResult.HyperFindResult;
                    }

                    empName = string.Join(";", filteredEmployees.Select(w => w.FullName).ToArray());
                    filtersHashTable.Add("EmpName", empName);

                    foreach (var item in filteredEmployees)
                    {
                        employeesHashTable.Add(item.PersonNumber, item.FullName);
                    }

                    context.PrivateConversationData.SetValue("EmployeeHashTable", employeesHashTable);

                    if (!string.IsNullOrEmpty(startDate))
                    {
                        DateTime.TryParse(startDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out sdt1);
                        DateTime.TryParse(endDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out edt);
                        filtersHashTable.Add("DateRange", startDate + ";" + endDate);
                    }

                    if (filteredEmployees.Count == 0)
                    {
                        await context.PostAsync(KronosResourceText.NoEmployees);
                    }
                    else
                    {
                        var response = await this.timeOffActivity.GetTimeOffRequest(tenantId, jSessionId, sdt1.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), edt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), filteredEmployees);

                        var requests = response.RequestMgmt?.RequestItems?.GlobalTimeOffRequestItem;
                        requests = requests.Where(w => w.StatusName.ToLowerInvariant() == Constants.Submitted.ToLowerInvariant() || w.StatusName.ToLowerInvariant() == Constants.Approved.ToLowerInvariant() || w.StatusName.ToLowerInvariant() == Constants.Refused.ToLowerInvariant()).ToList();
                        for (int i = 0; i < requests.Count; i++)
                        {
                            DateTime.TryParse(requests[i].TimeOffPeriods.TimeOffPeriod.StartDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime sdt);
                            requests[i].TimeOffPeriods.TimeOffPeriod.Sdt = sdt;
                        }

                        requests = requests.OrderBy(w => w.TimeOffPeriods.TimeOffPeriod.Sdt).ToList();

                        var personNumbers = (from d in requests select d.Employee.PersonIdentity.PersonNumber).Distinct().ToList();
                        var tasks         = personNumbers.Select(async emp =>
                        {
                            if (!employeesRoleHashTable.ContainsKey(Convert.ToString(emp)))
                            {
                                var jobAssignent = await this.commonActivity.GetJobAssignment(Convert.ToString(emp), tenantId, superSession);
                                var role         = jobAssignent?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Split('/').LastOrDefault();
                                employeesRoleHashTable.Add(Convert.ToString(emp), role);
                            }
                        });
                        await Task.WhenAll(tasks);

                        context.PrivateConversationData.SetValue("EmployeeRoleHashTable", employeesRoleHashTable);
                        if (!string.IsNullOrEmpty(showCompletedRequests))
                        {
                            if (showCompletedRequests.ToLowerInvariant() == "true")
                            {
                                requests = requests.Where(w => (w.StatusName.ToLowerInvariant() == Constants.Approved.ToLowerInvariant()) || (w.StatusName.ToLowerInvariant() == Constants.Refused.ToLowerInvariant())).ToList();
                            }
                            else
                            {
                                requests = requests.Where(w => (w.StatusName.ToLowerInvariant() == Constants.Submitted.ToLowerInvariant())).ToList();
                            }

                            filtersHashTable.Add("ShowCompletedRequests", showCompletedRequests);
                        }
                        else
                        {
                            requests = requests.Where(w => (w.StatusName.ToLowerInvariant() == Constants.Submitted.ToLowerInvariant())).ToList();
                        }

                        int totalPages       = (requests?.Count > 0) ? (int)Math.Ceiling((double)requests.Count / 5) : 0;
                        var currentPageItems = this.GetPage(requests, 0, 5);

                        Hashtable pagewiseRequests = new Hashtable();
                        for (int i = 0; i < totalPages; i++)
                        {
                            pagewiseRequests.Add(i.ToString(), JsonConvert.SerializeObject(this.GetPage(requests, i, 5)).ToString());
                        }

                        context.PrivateConversationData.SetValue("PagewiseRequests", pagewiseRequests);
                        context.PrivateConversationData.SetValue("FiltersHashTable", filtersHashTable);
                        ViewTorListObj obj = new ViewTorListObj
                        {
                            Employees        = employeesHashTable,
                            EmployeesRoles   = employeesRoleHashTable,
                            Filters          = filtersHashTable,
                            TotalPages       = totalPages,
                            CurrentPageCount = 1,
                        };

                        // string actionSet = "FR";
                        string actionSet = "F";
                        if (obj.CurrentPageCount < obj.TotalPages)
                        {
                            // actionSet = "FRN";
                            actionSet = "FN";
                        }

                        obj.ConversationId = context.Activity.Conversation.Id;
                        obj.ActivityId     = context.Activity.ReplyToId;

                        var comments = context.PrivateConversationData.GetValue <List <Models.ResponseEntities.CommentList.Comment> >("Comments");
                        if (requests.Count > 0)
                        {
                            card = this.supervisorTimeOffcard.GetCard(JsonConvert.DeserializeObject <List <TimeOffResponse.GlobalTimeOffRequestItem> >(Convert.ToString(pagewiseRequests[Convert.ToString(obj.CurrentPageCount - 1)])), obj, actionSet, comments);
                        }
                        else
                        {
                            card = this.supervisorTimeOffcard.GetCard(new List <TimeOffResponse.GlobalTimeOffRequestItem>(), obj, actionSet, comments);
                        }

                        var conversationId = context.Activity.Conversation.Id;
                        var activityId     = context.Activity.ReplyToId;
                        context.PrivateConversationData.SetValue("conversationId", conversationId);
                        context.PrivateConversationData.SetValue("activityId", activityId);
                        IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                        activity.Text  = null;
                        activity.Value = null;
                        activity.Attachments.Add(new Attachment()
                        {
                            Content     = card,
                            ContentType = "application/vnd.microsoft.card.adaptive",
                        });
                        await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
                    }
                }

                context.Done(default(string));
            }
            catch (Exception)
            {
                throw;
            }
        }
        private async Task ProcessCommand(IDialogContext context, IAwaitable <string> result)
        {
            var     activity = context.Activity as Activity;
            var     message  = await result;
            JObject tenant   = context.Activity.ChannelData as JObject;
            string  tenantId = tenant?["tenant"].SelectToken("id").ToString();

            AppInsightsLogger.CustomEventTrace("SwapShiftDialog", new Dictionary <string, string>()
            {
                { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ProcessCommand" }, { "Command", message }
            });

            if (message == Constants.SwapShift)
            {
                await this.ShowShiftSelectionCard(context, Constants.SwapShift);
            }
            else if (message == Constants.SwapShiftNext2)
            {
                JToken       token    = JObject.Parse(activity.Value.ToString());
                var          shift    = Convert.ToString(token.SelectToken("SelectedShift"));
                var          splitted = shift.Split('-');
                SwapShiftObj obj      = new SwapShiftObj();
                DateTime     shiftStart;
                DateTime     shiftEnd;
                string       startTime;
                string       endTime;
                if (splitted[2].Length == 6)
                {
                    startTime = splitted[2].Insert(4, " ");
                }
                else
                {
                    startTime = splitted[2].Insert(5, " ");
                }

                if (splitted[3].Length == 6)
                {
                    endTime = splitted[3].Insert(4, " ");
                }
                else
                {
                    endTime = splitted[3].Insert(5, " ");
                }

                DateTime.TryParse(splitted[0] + " " + startTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out shiftStart);
                DateTime.TryParse(splitted[1] + " " + endTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out shiftEnd);

                obj.Emp1FromDateTime      = shiftStart;
                obj.Emp1ToDateTime        = shiftEnd;
                obj.RequestorPersonNumber = splitted[4];
                obj.RequestorName         = splitted[5];
                obj.SelectedShiftToSwap   = shift;

                context.PrivateConversationData.SetValue("SwapShiftObj", obj);
                await this.ShowSearchFilterCard(context, Constants.SwapShiftNext2);
            }
            else if (message == Constants.SwapShiftNext3)
            {
                JToken token            = JObject.Parse(activity.Value.ToString());
                var    selectedLocation = Convert.ToString(token.SelectToken("SelectedLocation"));
                var    selectedJob      = Convert.ToString(token.SelectToken("SelectedJob"));
                var    selectedEmployee = Convert.ToString(token.SelectToken("SelectedEmployee"));
                var    obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");
                obj.SelectedEmployee = selectedEmployee;
                obj.SelectedLocation = selectedLocation;
                obj.SelectedJob      = selectedJob;

                context.PrivateConversationData.SetValue("SwapShiftObj", obj);

                await this.ShowAvailableShiftsCard(context, Constants.SwapShiftNext3);
            }
            else if (message == Constants.SwapShiftBack1)
            {
                JToken token             = JObject.Parse(activity.Value.ToString());
                var    selectedLocation1 = Convert.ToString(token.SelectToken("SelectedLocation"));
                var    selectedJob1      = Convert.ToString(token.SelectToken("SelectedJob"));
                var    selectedEmployee1 = Convert.ToString(token.SelectToken("SelectedEmployee"));
                var    obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");
                obj.SelectedEmployee = selectedEmployee1;
                obj.SelectedLocation = selectedLocation1;
                obj.SelectedJob      = selectedJob1;

                context.PrivateConversationData.SetValue("SwapShiftObj", obj);
                await this.ShowShiftSelectionCard(context, Constants.SwapShiftBack1);
            }
            else if (message == Constants.SwapShiftBack2)
            {
                JToken token = JObject.Parse(activity.Value.ToString());
                var    selectedShiftToSwap = Convert.ToString(token.SelectToken("Choice1"));
                var    obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");
                obj.SelectedShiftToSwap = selectedShiftToSwap;

                context.PrivateConversationData.SetValue("SwapShiftObj", obj);
                await this.ShowSearchFilterCard(context, Constants.SwapShiftBack2);
            }
            else if (message == Constants.SwapShiftBack3)
            {
                await this.ShowAvailableShiftsCard(context, Constants.SwapShiftBack3);
            }
            else if (message == Constants.SwapShiftNext4)
            {
                JToken token = JObject.Parse(activity.Value.ToString());
                var    selectedShiftToSwap = Convert.ToString(token.SelectToken("SelectedShift"));
                var    obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");
                obj.SelectedShiftToSwap = selectedShiftToSwap;
                var      splitted = selectedShiftToSwap.Split('-');
                DateTime shiftStart1;
                DateTime shiftEnd1;
                string   startTime1;
                string   endTime1;
                if (splitted[2].Length == 6)
                {
                    startTime1 = splitted[2].Insert(4, " ");
                }
                else
                {
                    startTime1 = splitted[2].Insert(5, " ");
                }

                if (splitted[3].Length == 6)
                {
                    endTime1 = splitted[3].Insert(4, " ");
                }
                else
                {
                    endTime1 = splitted[3].Insert(5, " ");
                }

                DateTime.TryParse(splitted[0] + " " + startTime1, CultureInfo.InvariantCulture, DateTimeStyles.None, out shiftStart1);
                DateTime.TryParse(splitted[1] + " " + endTime1, CultureInfo.InvariantCulture, DateTimeStyles.None, out shiftEnd1);

                obj.Emp2FromDateTime        = shiftStart1;
                obj.Emp2ToDateTime          = shiftEnd1;
                obj.RequestedToPersonNumber = splitted[4];
                obj.RequestedToName         = splitted[5];
                context.PrivateConversationData.SetValue("SwapShiftObj", obj);
                await this.SwapShiftConfirmation(context, obj);
            }
            else if (message == Constants.CancelSwapShift)
            {
                var          conversationId = context.Activity.Conversation.Id;
                var          activityId     = context.Activity.ReplyToId;
                AdaptiveCard card           = new AdaptiveCard("1.0")
                {
                    Body = new List <AdaptiveElement>
                    {
                        new AdaptiveContainer
                        {
                            Items = new List <AdaptiveElement>
                            {
                                new AdaptiveTextBlock
                                {
                                    Text = KronosResourceText.CancelSwapShift,
                                    Wrap = true,
                                },
                            },
                        },
                    },
                };
                IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                context.PrivateConversationData.RemoveValue("SwapShiftObj");
                activity.Text  = null;
                activity.Value = null;
                activity.Attachments.Add(new Attachment()
                {
                    Content     = card,
                    ContentType = "application/vnd.microsoft.card.adaptive",
                });
                await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
            }
            else if (message == Constants.SubmitSwapShift)
            {
                await this.SubmitSwapShiftRequest(context);
            }
            else if (message.Contains("approve") || message.Contains("refuse"))
            {
                await this.SubmitApproval(context, message);
            }

            context.Done(default(string));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Show list of employees who are either present or absent, in a card.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <param name="punchList">List of punches.</param>
        /// <param name="isHere">Boolean to check whether employee is present.</param>
        /// <param name="message">bot command.</param>
        /// <param name="currentPage">current page value.</param>
        /// <returns>A task.</returns>
        public async Task ShowPresentEmployeesData(IDialogContext context, IEnumerable <KeyValuePair <string, string> > punchList, bool isHere, string message, int currentPage, int totalEmp)
        {
            string title = string.Empty;

            if (isHere)
            {
                // title = $"Showing {(currentPage * 5) - 4} - {((currentPage * 5) - 4) + (punchList.Count() - 1)} of {totalEmp} present employees";
                title = KronosResourceText.ShowPresentEmployeesTxt.Replace("{first}", ((currentPage * 5) - 4).ToString())
                        .Replace("{last}", ((currentPage * 5) - 4 + (punchList.Count() - 1)).ToString())
                        .Replace("{totalEmp}", totalEmp.ToString());
            }
            else
            {
                title = KronosResourceText.ShowAbsentEmployeesTxt.Replace("{first}", ((currentPage * 5) - 4).ToString())
                        .Replace("{last}", ((currentPage * 5) - 4 + (punchList.Count() - 1)).ToString())
                        .Replace("{totalEmp}", totalEmp.ToString());
            }

            if (punchList.Any())
            {
                var dynamicContainer = new AdaptiveContainer()
                {
                    Items = new List <AdaptiveElement>
                    {
                        new AdaptiveTextBlock
                        {
                            Size   = AdaptiveTextSize.Medium,
                            Weight = AdaptiveTextWeight.Bolder,
                            Text   = title,
                        },
                    },
                };

                var dynamicItems = new List <AdaptiveElement>();
                foreach (var punch in punchList)
                {
                    var columnList = new List <AdaptiveColumn>
                    {
                        new AdaptiveColumn
                        {
                            Items = new List <AdaptiveElement>
                            {
                                new AdaptiveImage
                                {
                                    Style = AdaptiveImageStyle.Person,
                                    Url   = new Uri("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAASuSURBVGhD7ZpZyFdFGIe/yooWCi1B224iKMMMEyIsBAlaoJWiRXKBjEJaIKKrumhRW4iCsqK6iCIioohWumghKgLLiIQuMrXCNtvLitbnOTUwHM//nJn5L1/K94MHnf85M+c9Z7b3fecbm9B2rANhIdwDL8En8C38Db/BN/A+PAHXw/GwG/wvNAUuhdWgwblsgYfhBNgBRq59YSX8AMGor+Fx8MXmwwGwByiNnAyHw5lwI7wJf0Co/y6cBSORBl0IX4EP/wuegdNgZ8jVfnA1rIfwQg7Lw2Bo2gc0OjzwaZgFg5AfYTFsAtv+BS6CgetQ2AA+5DM4FVK1O+z47387tRfcCfa0z7oPdoKBaA5sBht+BaZBLzn0ToK7YS38CNYTV7EH4Qjo0unwPVjvKdgF+tIM+BJs8FFoa1ADncDB8F64FF8BLhhtOhLsfev47OKecU58DDb0CLQ1ZK99B7HBXfwKy6Gt3UMgfMhb/CFXDpEwsV+Gtp5wLwlfroQHoE1Hg5PfeXOKP+RoKfiQz6FtTih36bpxuRwHbboEvM/ecT9KkmM3TO6U1elDiI0q4SHo0rPgvS4kSboJrOA+0SU3tNigUlzRunQwOMR+B+dOqxzvLpmOx5n+0KFjoMmwXP6EFM/APcb7u+bV2GXgjSm9oY6F2KB+2Bu6dBDYI/ZM6/1vg42mrg6DehGNmwQpCnPFBalRvq03ONFTHUCdu9igUj6CVJ0H1vGFGqXT5g2PVaU0+RXd2GKjSngRUuWq6pwyhGj84PeCjS6rSulaA3XDcrkBcvQeWG92VarpVfDivKqULr9mbFQJF0COdJms5zDbSp+CF/evSmnyXrs5NqqE1FUy6Dqw3jVVqaYQtuYkBI6C2KBS3oEchW3i1qpUkxfcCHM0FWKDSjGzkqMlYL1VVakm13Iv5uoNiI0qwTRSjgyDrXdXVaopxBOGmzkybg8xQwn2Rm7QdCVYd0VVqsnQ1ItGhbnyi8bGpeLH2xVydTtY//KqVJMrhxdzEgtB+j0hq5hD49BIUHBTTq5KNbkpeTF3cwoyPxUb2YVetkm8XBm9hqFsmnYrmbb04utVKV+6KzkT35WnRIYX1l9XlRq0J/wMpjGn+0OBUveVt6BU14JtmCzvKdMu3uSqUKLwtboofRGH1QdgG+aXe+pE8Cbd6tT4IFZqxKjTVyInt/W1rzV76RuHZXiRP2QqZDu6MAmuV5AjbQtz0Ix/p84Fb9aJdN6kyL3gKjAEjQ1uw0MfI8xUnQ/WM2mY5A/65q+Ble7whxaZ3L4NQvqoBA+JLoa2GNxgKmTqfaFkubt7mtSU3fOB+jqD8LFiwumVR3Lx+PfDhqznc/+Vs2SkaGXdCFcjX0DfJj6lGhYOu7NB+Ux/+wK6sp49dT/YiPMlBF6jxDjFf83gz4VimbwOfs144QZ9DvQtX+ZJaHrIsLEnBnpAarxwMzQ9bFg4J/oaTm06AzxqaHrwIHkeTJAPVa7pOmwhNB4kGyE3NdS3TJe6qrn+NxmVg2csRnvj+icdHkX4RwQvwE/QZGgTHnd7aKMXm3p8PTLpMZvGXAAmzwxlTcWKroxf3VA6Jwk4oW1QY2P/ANttdsxdJ2yfAAAAAElFTkSuQmCC"),
                                    Size  = AdaptiveImageSize.Small,
                                },
                            },
                            Width = "auto",
                        },
                        new AdaptiveColumn
                        {
                            Items = new List <AdaptiveElement>
                            {
                                new AdaptiveTextBlock
                                {
                                    Weight = AdaptiveTextWeight.Bolder,
                                    Text   = punch.Key,
                                    Wrap   = true,
                                },
                                new AdaptiveTextBlock
                                {
                                    Weight   = AdaptiveTextWeight.Bolder,
                                    Text     = punch.Value,
                                    Size     = AdaptiveTextSize.Small,
                                    IsSubtle = true,
                                    Spacing  = AdaptiveSpacing.None,
                                    Wrap     = true,
                                },
                            },
                            Width = "3",
                        },
                    };

                    dynamicItems.Add(new AdaptiveColumnSet
                    {
                        Columns   = columnList,
                        Separator = true,
                    });
                }

                AdaptiveCard card = new AdaptiveCard("1.0");
                dynamicContainer.Items.AddRange(dynamicItems);
                card.Body.Add(dynamicContainer);
                card.Actions.AddRange(this.GetButtons(context, message, currentPage, isHere));

                // show card
                if (message.Contains(Constants.presentEmpPrevpage) || message.Contains(Constants.presentEmpNextpage) || message.Contains(Constants.absentEmpNextpage) || message.Contains(Constants.absentEmpPrevpage))
                {
                    var replyMessage   = ((Activity)context.Activity).CreateReply();
                    var conversationId = context.Activity.Conversation.Id;
                    var activityId     = context.Activity.ReplyToId;
                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                    replyMessage.Attachments.Add(new Attachment()
                    {
                        Content     = card,
                        ContentType = "application/vnd.microsoft.card.adaptive",
                    });
                    await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, replyMessage);
                }
                else
                {
                    var replyMessage = context.MakeMessage();
                    replyMessage.Attachments = new List <Attachment>
                    {
                        new Attachment()
                        {
                            Content     = card,
                            ContentType = "application/vnd.microsoft.card.adaptive",
                        },
                    };
                    await context.PostAsync(replyMessage);
                }
            }
            else
            {
                if (isHere)
                {
                    await context.PostAsync(KronosResourceText.NoEmployeesClockedToday);
                }
                else
                {
                    await context.PostAsync(KronosResourceText.NoEmployeesNotClockedToday);
                }
            }
        }
        private async Task ShowOvertimeEmployees(IDialogContext context, string tenantId, string startDate, string endDate, List <string> overtimeEmployeeList, string payPeriod, LoginResponse response)
        {
            var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

            if (superUserLogonRes?.Status == ApiConstants.Success)
            {
                context.UserData.SetValue(context.Activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
            }

            string personNumber = this.response?.PersonNumber;
            string isManager    = await this.authenticateUser.IsUserManager(context);

            var activity = context.Activity as Activity;
            var message  = activity.Text?.ToLowerInvariant().Trim();

            if (isManager.Equals(Constants.Yes))
            {
                Models.ResponseEntities.HyperFind.Response hyperFindResponse = await this.hyperFindActivity.GetHyperFindQueryValues(tenantId, response.JsessionID, startDate, endDate, ApiConstants.OvertimeHyperFindQuery, ApiConstants.PubilcVisibilityCode);

                if (hyperFindResponse?.Status == ApiConstants.Failure)
                {
                    // User is not logged in - Send Sign in card
                    if (hyperFindResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                    {
                        await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                    }
                    else
                    {
                        await context.PostAsync(hyperFindResponse.Error?.Message);
                    }
                }
                else
                {
                    context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                    if (hyperFindResponse.HyperFindResult.Count > 0)
                    {
                        var overtimeMappingEntity = await this.azureTableStorageHelper.ExecuteQueryUsingPointQueryAsync <OvertimeMappingEntity>(Constants.ActivityChannelId, $"{tenantId}${Constants.TeamOvertimes}", AppSettings.Instance.OvertimeMappingtableName);

                        List <string> lst     = new List <string>();
                        var           emplist = hyperFindResponse.HyperFindResult.Where(w => w.PersonNumber != personNumber);

                        var tasks = emplist.Select(async emp =>
                        {
                            var showHoursWorkedResponse = await this.hoursWorkedActivity.ShowHoursWorked(tenantId, response, startDate, endDate, emp.PersonNumber);

                            // var totalHours = showPunchesResponse?.Timesheet?.DailyTotals?.DateTotals?
                            //    .Where(t => t.Totals != null && t.Totals.Total != null)
                            //    .SelectMany(x => x.Totals.Total.Where(f => f.PayCodeName.ToLowerInvariant().Contains(overtimeMappingEntity.PayCodeName.ToLowerInvariant())))
                            //    .Sum(x => Convert.ToDouble(x.AmountInTime.Replace(':', '.')));
                            var showHoursWorkedOrderedList = showHoursWorkedResponse?.Timesheet?.PeriodTotalData?.PeriodTotals?.Totals?.Total?.FindAll(x => x.PayCodeName == Constants.AllHours).Select(x => new { x.PayCodeName, x.AmountInTime }).ToList();
                            var allHours = showHoursWorkedOrderedList.FirstOrDefault(x => x.PayCodeName.Contains(Constants.AllHours))?.AmountInTime;

                            if (allHours != null)
                            {
                                var jobAssignent     = await this.jobAssignment.getJobAssignment(Convert.ToString(emp.PersonNumber), tenantId, superSession);
                                var role             = jobAssignent?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Split('/').LastOrDefault();
                                DateTime stDateTime  = default(DateTime);
                                DateTime eDateTime   = default(DateTime);
                                double assignedHours = default(double);
                                UpcomingShiftsAlias.Response scheduleResponse           = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, superSession, startDate, endDate, emp.PersonNumber);
                                List <UpcomingShiftsAlias.ScheduleShift> scheduleShifts = scheduleResponse?.Schedule?.ScheduleItems?.ScheduleShift?.OrderBy(x => x.StartDate).ToList();
                                if (scheduleShifts != null)
                                {
                                    foreach (var scheduleShift in scheduleShifts)
                                    {
                                        var shiftSegment = scheduleShift.ShiftSegments.FirstOrDefault();
                                        stDateTime       = DateTime.Parse($"{shiftSegment.StartDate} {shiftSegment.StartTime}", CultureInfo.InvariantCulture, DateTimeStyles.None);
                                        eDateTime        = DateTime.Parse($"{shiftSegment.EndDate} {shiftSegment.EndTime}", CultureInfo.InvariantCulture, DateTimeStyles.None);
                                        assignedHours    = assignedHours + Math.Abs(Math.Round((stDateTime - eDateTime).TotalHours, 2));
                                    }
                                }

                                // overtimeEmployeeList.Add($"{emp.FullName} - {totalHours} <br />");
                                overtimeEmployeeList.Add($"{emp.FullName} - {role} - {Convert.ToString(allHours).Replace(':', '.')}/{assignedHours}");
                            }
                        });
                        await Task.WhenAll(tasks);

                        var pagewiseOvertimes = this.GetPagewiseList(overtimeEmployeeList);
                        context.PrivateConversationData.SetValue("PagewiseOvertimes", pagewiseOvertimes);
                        var card = this.adaptiveTeamOvertimesCard.GetCard(context, payPeriod, startDate, endDate, 1);
                        if (message.Contains(Constants.PreviousWeekTeamOvertimes) || message.Contains(Constants.CurrentWeekTeamOvertimes))
                        {
                            var conversationId = context.Activity.Conversation.Id;
                            var activityId     = context.Activity.ReplyToId;
                            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                            activity.Text  = null;
                            activity.Value = null;
                            activity.Attachments.Add(new Attachment()
                            {
                                Content     = card,
                                ContentType = "application/vnd.microsoft.card.adaptive",
                            });
                            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
                        }
                        else
                        {
                            var reply = activity.CreateReply();
                            reply.Attachments = new List <Attachment>
                            {
                                new Attachment()
                                {
                                    Content     = card,
                                    ContentType = "application/vnd.microsoft.card.adaptive",
                                },
                            };
                            await context.PostAsync(reply);
                        }
                    }
                    else
                    {
                        var pagewiseOvertimes = this.GetPagewiseList(overtimeEmployeeList);
                        context.PrivateConversationData.SetValue("PagewiseOvertimes", pagewiseOvertimes);
                        var card = this.adaptiveTeamOvertimesCard.GetCard(context, payPeriod, startDate, endDate, 1);
                        if (message.Contains(Constants.PreviousWeekTeamOvertimes) || message.Contains(Constants.CurrentWeekTeamOvertimes))
                        {
                            var conversationId = context.Activity.Conversation.Id;
                            var activityId     = context.Activity.ReplyToId;
                            IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                            activity.Text  = null;
                            activity.Value = null;
                            activity.Attachments.Add(new Attachment()
                            {
                                Content     = card,
                                ContentType = "application/vnd.microsoft.card.adaptive",
                            });
                            await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
                        }
                        else
                        {
                            var reply = activity.CreateReply();
                            reply.Attachments = new List <Attachment>
                            {
                                new Attachment()
                                {
                                    Content     = card,
                                    ContentType = "application/vnd.microsoft.card.adaptive",
                                },
                            };
                            await context.PostAsync(reply);
                        }
                    }
                }
            }
            else if (isManager.Equals(Constants.No))
            {
                await context.PostAsync(KronosResourceText.NoPermission);
            }
        }
        private async Task ShowShiftSelectionCard(IDialogContext context, string command)
        {
            string  jSession = string.Empty;
            var     reply    = context.MakeMessage();
            JObject tenant   = context.Activity.ChannelData as JObject;
            string  tenantId = tenant["tenant"].SelectToken("id").ToString();

            string       startDate = DateTime.Today.AddDays(1).ToString("M/d/yyyy", CultureInfo.InvariantCulture);
            DateTime     start     = context.Activity.LocalTimestamp.Value.DateTime.StartWeekDate(DayOfWeek.Sunday).AddDays(6);
            AdaptiveCard card;
            string       endDate = start.EndOfWeek().ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);

            // get person number
            string personNumber = string.Empty;
            string personName   = string.Empty;

            if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response))
            {
                personNumber = this.response.PersonNumber;
                personName   = this.response.Name;
                jSession     = this.response.JsessionID;
            }

            context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);

            UpcomingShift.Response scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, superSession, startDate, endDate, personNumber);

            if (scheduleResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
            {
                await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
            }
            else if (scheduleResponse.Error?.ErrorCode == ApiConstants.UserUnauthorizedError)
            {
                await context.PostAsync(KronosResourceText.NoPermission);
            }
            else
            {
                try
                {
                    var workingdaySchedule = scheduleResponse.Schedule.ScheduleItems.ScheduleShift.ToList();
                    if (workingdaySchedule.Count() == 0)
                    {
                        card = this.swapShiftCard.GetShiftSelectionCard(context, null, null);
                    }
                    else
                    {
                        var listOfEmps = await this.hyperFindActivity.GetHyperFindQueryValues(tenantId, superSession, startDate, endDate, ApiConstants.ReportsToHyperFindQuery, ApiConstants.PersonalVisibilityCode);

                        card = this.swapShiftCard.GetShiftSelectionCard(context, workingdaySchedule, listOfEmps.HyperFindResult);
                    }
                }
                catch (Exception)
                {
                    card = this.swapShiftCard.GetShiftSelectionCard(context, null, null);
                }

                if (command.Contains("back"))
                {
                    var activity = context.Activity as Activity;
                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                    var conversationId = context.Activity.Conversation.Id;
                    var activityId     = context.Activity.ReplyToId;

                    activity.Text  = null;
                    activity.Value = null;
                    activity.Attachments.Add(new Attachment()
                    {
                        Content     = card,
                        ContentType = "application/vnd.microsoft.card.adaptive",
                    });
                    await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);
                }
                else
                {
                    reply.Attachments.Add(new Attachment()
                    {
                        ContentType = "application/vnd.microsoft.card.adaptive",
                        Content     = card,
                    });
                    await context.PostAsync(reply);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Handle the user response to the file consent card.
        /// </summary>
        /// <param name="context">Dialog context</param>
        /// <param name="message">The invoke activity triggered by the user action</param>
        /// <returns>Tracking task</returns>
        private async Task HandleFileConsentResponseAsync(IDialogContext context, Activity message)
        {
            // Create a connector client for deleting the file consent card
            IConnectorClientFactory connectorClientFactory = new ConnectorClientFactory(Address.FromActivity(message), this.appCredentialsProvider.GetCredentials(message.Recipient.Id));
            var connectorClient = connectorClientFactory.MakeConnectorClient();

            // Convert the value in the invoke to the expected type
            var fileConsentCardResponse = ((JObject)message.Value).ToObject <FileConsentCardResponse>();

            switch (fileConsentCardResponse.Action)
            {
            // User declined the file
            case FileConsentCardResponse.DeclineAction:
                // Delete the file consent card
                if (message.ReplyToId != null)
                {
                    await connectorClient.Conversations.DeleteActivityAsync(message.Conversation.Id, message.ReplyToId);
                }

                await context.PostAsync("Ok! If you change your mind, just send me the picture again.");

                break;

            // User accepted the file
            case FileConsentCardResponse.AcceptAction:
                // Send typing activity while the file is uploading
                var typingActivity = context.MakeMessage();
                typingActivity.Type = ActivityTypes.Typing;
                await context.PostAsync(typingActivity);

                // Check that response is for the current OCR result
                var responseContext = ((JObject)fileConsentCardResponse.Context).ToObject <FileConsentContext>();
                var lastOcrResult   = context.ConversationData.GetValueOrDefault <OcrResultData>(OcrResultKey);
                if (lastOcrResult?.ResultId != responseContext.ResultId)
                {
                    await context.PostAsync("That result has expired. Send me the picture again, and I'll rescan it.");

                    return;
                }

                try
                {
                    // Upload the file contents to the upload session we got from the invoke value
                    // See https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session
                    await this.UploadFileAsync(fileConsentCardResponse.UploadInfo.UploadUrl, lastOcrResult.Text);

                    // Delete the file consent card
                    if (message.ReplyToId != null)
                    {
                        await connectorClient.Conversations.DeleteActivityAsync(message.Conversation.Id, message.ReplyToId);
                    }

                    // Send the user a link to the uploaded file
                    // The fields in the file info card are populated from the upload info we got in the incoming invoke
                    var fileInfoCard = FileInfoCard.FromFileUploadInfo(fileConsentCardResponse.UploadInfo);
                    var reply        = context.MakeMessage();
                    reply.Attachments = new List <Attachment> {
                        fileInfoCard.ToAttachment()
                    };
                    await context.PostAsync(reply);
                }
                catch (Exception ex)
                {
                    await context.PostAsync(string.Format("There was an error uploading the file: {0}", ex.Message));
                }
                break;
            }
        }
        /// <summary>
        /// get user info.
        /// </summary>
        /// <param name="context">dialog context.</param>
        /// <returns>user login info.</returns>
        public async Task <LoginResponse> GetUserInfo(IDialogContext context)
        {
            var activity = (Activity)context.Activity;

            if (!context.UserData.TryGetValue(activity.From.Id, out LoginResponse response))
            {
                this.response = response;
            }

            if (string.IsNullOrEmpty(response?.JsessionID) && activity.Name != Constants.VerifyState)
            {
                // User is not logged in - Send Sign in card
                await this.authenticationService.SendAuthCardAsync(context, activity);
            }
            else if (activity.Name == Constants.VerifyState)
            {
                JObject data = activity.Value as JObject;
                if (data != null && data["state"] != null)
                {
                    // set the key and value
                    response = Newtonsoft.Json.JsonConvert.DeserializeObject <LoginResponse>(data["state"].ToString());
                    context.UserData.SetValue(activity.From.Id, response);
                    JObject tenant = activity.ChannelData as JObject;

                    string tenantId = tenant["tenant"].SelectToken("id").ToString();

                    // update sign in card
                    var reply          = ((Activity)context.Activity).CreateReply();
                    var conversationId = context.Activity.Conversation.Id;

                    // get the reply to id
                    context.PrivateConversationData.TryGetValue(activity.From.Id + "SignIn", out string activityId);

                    // Create the ConnectorClientFactory
                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));
                    HeroCard heroCard = new HeroCard()
                    {
                        Title    = KronosResourceText.SignInLabel,
                        Subtitle = KronosResourceText.SignInSuccess,
                    };
                    reply.Attachments.Add(heroCard.ToAttachment());

                    await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, reply);

                    await context.PostAsync(KronosResourceText.NiceToSeeYou.Replace("{response.Name}", response.Name));

                    // store user details in azure table
                    this.botUserEntity.TenantId       = tenantId;
                    this.botUserEntity.PersonNumber   = response.PersonNumber;
                    this.botUserEntity.TeamsUserId    = activity.From.Id;
                    this.botUserEntity.ConversationId = activity.Conversation.Id;
                    this.botUserEntity.PartitionKey   = Constants.ActivityChannelId;
                    this.botUserEntity.RowKey         = response.PersonNumber + "===" + activity.From.Id;

                    await this.azureTableStorageHelper.InsertOrMergeTableEntityAsync(this.botUserEntity, AppSettings.Instance.KronosUserTableName);

                    // login super user
                    var superUserLogonRes = await this.authenticationService.LoginSuperUser((Activity)context.Activity);

                    if (superUserLogonRes?.Status == ApiConstants.Success)
                    {
                        context.UserData.SetValue(activity.From.Id + Constants.SuperUser, superUserLogonRes.Jsession);
                    }
                    else
                    {
                        await context.PostAsync(KronosResourceText.SuperUserLoginError);
                    }
                }
                else
                {
                    // handle error response
                }
            }

            return(response);
        }
        private async Task SubmitSwapShiftRequest(IDialogContext context)
        {
            var     activity     = context.Activity as Activity;
            string  jSession     = string.Empty;
            JToken  token        = JObject.Parse(activity.Value.ToString());
            JObject tenant       = context.Activity.ChannelData as JObject;
            string  tenantId     = tenant["tenant"].SelectToken("id").ToString();
            string  personNumber = string.Empty;

            if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response))
            {
                personNumber = this.response.PersonNumber;
                jSession     = this.response.JsessionID;
            }

            var obj = context.PrivateConversationData.GetValue <SwapShiftObj>("SwapShiftObj");

            obj.QueryDateSpan = obj.Emp1FromDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture) + "-" + obj.Emp1ToDateTime.AddDays(10).ToString("M/d/yyyy", CultureInfo.InvariantCulture);
            context.PrivateConversationData.SetValue("SwapShiftObj", obj);

            context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);

            var result = await this.swapShiftActivity.DraftSwapShift(tenantId, superSession, obj);

            if (result?.Status == ApiConstants.Failure)
            {
                // check if authentication failure then send sign in card
                // User is not logged in - Send Sign in card
                if (result.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                {
                    await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                }
                else
                {
                    await context.PostAsync(result.Error.DetailErrors.Error.FirstOrDefault().Message);
                }
            }
            else
            {
                var reqId = result.EmployeeRequestMgm.RequestItem.EmployeeSwapShiftRequestItems.FirstOrDefault().Id;
                obj.RequestId = reqId;
                context.PrivateConversationData.SetValue("SwapShiftObj", obj);
                result = await this.swapShiftActivity.SubmitSwapShift(tenantId, superSession, obj.RequestorPersonNumber, reqId, obj.QueryDateSpan, null);

                if (result?.Status == ApiConstants.Failure)
                {
                    await context.PostAsync(result.Error.DetailErrors.Error.FirstOrDefault().Message);
                }
                else
                {
                    var conversationId = context.Activity.Conversation.Id;
                    var activityId     = context.Activity.ReplyToId;

                    IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(context.Activity), new MicrosoftAppCredentials(AppSettings.Instance.MicrosoftAppId, AppSettings.Instance.MicrosoftAppPassword));

                    var conversationId1 = await this.commonActivity.GetEmpConversationId(obj.RequestedToPersonNumber, tenantId, superSession, activity.ChannelId);

                    if (conversationId1 != null)
                    {
                        await this.SendApprovalNotification(tenantId, superSession, context, conversationId1, null, obj, 1);
                    }

                    try
                    {
                        AdaptiveCard submitterCard = this.swapShiftCard.GetSwapSubmitCard(context, obj, null, Constants.Submitted);
                        activity.Text  = null;
                        activity.Value = null;
                        activity.Attachments.Add(new Attachment()
                        {
                            Content     = submitterCard,
                            ContentType = "application/vnd.microsoft.card.adaptive",
                        });
                        await factory.MakeConnectorClient().Conversations.UpdateActivityAsync(conversationId, activityId, activity);

                        if (conversationId1 == null)
                        {
                            await context.PostAsync(KronosResourceText.SwapShiftEmpNotFoundToNotify);
                        }

                        context.PrivateConversationData.RemoveValue("SwapShiftObj");
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }
            }

            context.Done(default(string));
        }