Exemple #1
0
        /// <summary>
        /// This method retrieves all the upcoming shifts.
        /// </summary>
        /// <param name="endPointUrl">The Kronos API endpoint.</param>
        /// <param name="jSession">The Kronos "token".</param>
        /// <param name="startDate">The query start date.</param>
        /// <param name="endDate">The query end date.</param>
        /// <param name="employees">The list of users to query.</param>
        /// <returns>A unit of execution that contains the response.</returns>
        public async Task <UpcomingShifts.Response> ShowUpcomingShiftsInBatchAsync(
            Uri endPointUrl,
            string jSession,
            string startDate,
            string endDate,
            List <ResponseHyperFindResult> employees)
        {
            if (employees is null)
            {
                throw new ArgumentNullException(nameof(employees));
            }

            var xmlScheduleRequest = this.CreateUpcomingShiftsRequestEmployees(
                startDate,
                endDate,
                employees);

            var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
                endPointUrl,
                ApiConstants.SoapEnvOpen,
                xmlScheduleRequest,
                ApiConstants.SoapEnvClose,
                jSession).ConfigureAwait(false);

            UpcomingShifts.Response scheduleResponse = this.ProcessResponse(tupleResponse.Item1);
            scheduleResponse.Jsession = tupleResponse.Item2;
            return(scheduleResponse);
        }
        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));
        }
        /// <summary>
        /// show employee details card.
        /// </summary>
        /// <param name="context">dialog context.</param>
        /// <param name="shiftData">shifts data.</param>
        /// <param name="punchData">punch data.</param>
        /// <param name="employeeName">emp name.</param>
        /// <param name="jobAssignmentData">job assignment data.</param>
        /// <returns>emp details card.</returns>
        public async Task ShowEmployeeDetailCard(IDialogContext context, UpcomingShiftAlias.Response shiftData, ShowPunchesAlias.Response punchData, string employeeName, JobAssignmentAlias.Response jobAssignmentData)
        {
            var reply    = context.MakeMessage();
            var heroCard = new HeroCard();

            heroCard.Title = employeeName;
            var           showPunchesDataOrderedList = punchData?.Timesheet?.TotaledSpans?.TotaledSpan?.OrderByDescending(x => x.InPunch.Punch.Date ?? x.OutPunch.Punch.Date).ThenByDescending(x => x.InPunch.Punch.Time ?? x.OutPunch.Punch.Time).FirstOrDefault();
            var           shiftsToday = shiftData.Schedule?.ScheduleItems?.ScheduleShift?.OrderBy(x => x.StartDate).FirstOrDefault();
            int           lastIndex   = (jobAssignmentData != null) ? (jobAssignmentData?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath).LastIndexOf('/') : 0;
            StringBuilder str         = new StringBuilder();

            str.Append("<br/><u><b>" + Resources.KronosResourceText.Location + "</b></u>");
            str.Append($"<br/><b>{Resources.KronosResourceText.PrimaryOrg}</b> - {jobAssignmentData?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Substring(0, lastIndex)}");
            str.Append($"<br/><b>{Resources.KronosResourceText.PrimaryJob}</b> - {jobAssignmentData?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Substring(lastIndex + 1)}");
            str.Append($"<br/><br/><u><b>{Resources.KronosResourceText.Shifts}</b></u>");

            if (shiftsToday?.ShiftSegments?.Count > 0)
            {
                foreach (UpcomingShiftAlias.ShiftSegment shiftSegment in shiftsToday?.ShiftSegments)
                {
                    str.Append($"<br/><b>{shiftSegment.StartTime} - {shiftSegment.EndTime}</b> {shiftSegment.SegmentTypeName}");
                }
            }
            else
            {
                str.Append("<br/>" + Resources.KronosResourceText.NoShiftsForToday);
            }

            str.Append("<br/><br/><u><b>" + Resources.KronosResourceText.LastPunch + "</b></u><br/>");

            if (showPunchesDataOrderedList == null || string.IsNullOrEmpty(showPunchesDataOrderedList.InPunch.Punch?.EnteredOnDate))
            {
                str.Append(Resources.KronosResourceText.NoPunchesForToday);
            }
            else
            {
                if (showPunchesDataOrderedList?.OutPunch?.Punch?.Time != null)
                {
                    // if outpunch available then show out punch
                    str.Append($"<b>{Resources.KronosResourceText.PunchTime}</b> - {DateTime.Parse(showPunchesDataOrderedList.OutPunch.Punch?.EnteredOnDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture)} {showPunchesDataOrderedList.OutPunch.Punch.Time}");
                    str.Append($"<br/><b>{Resources.KronosResourceText.EnteredOn}</b> - {DateTime.Parse(showPunchesDataOrderedList.OutPunch.Punch?.EnteredOnDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture)} {showPunchesDataOrderedList.OutPunch.Punch.EnteredOnTime}");
                }
                else
                {
                    str.Append($"<b>{Resources.KronosResourceText.PunchTime}</b> - {DateTime.Parse(showPunchesDataOrderedList.InPunch.Punch?.EnteredOnDate, CultureInfo.InvariantCulture , DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture)} {showPunchesDataOrderedList.InPunch.Punch.Time}");
                    str.Append($"<br/><b>{Resources.KronosResourceText.EnteredOn}</b> - {DateTime.Parse(showPunchesDataOrderedList.InPunch.Punch?.EnteredOnDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture)} {showPunchesDataOrderedList.InPunch.Punch.EnteredOnTime}");
                }
            }

            heroCard.Text = str.ToString();
            str.Clear();
            reply.Attachments.Add(heroCard.ToAttachment());
            await context.PostAsync(reply);
        }
Exemple #4
0
        /// <summary>
        /// Shows upcoming shifts
        /// </summary>
        /// <param name="tenantId">Tenant ID</param>
        /// <param name="jSession">jSession Object</param>
        /// <param name="startDate">Start Date</param>
        /// <param name="endDate">End Date</param>
        /// <param name="personNumber">Person number</param>
        /// <param name="employees">Employees object</param>
        /// <returns>Upcoming shifts response</returns>
        public async Task <UpcomingShifts.Response> ShowUpcomingShifts(string tenantId, string jSession, string startDate, string endDate, string personNumber, List <ResponseHyperFindResult> employees = null)
        {
            string xmlScheduleRequest = string.Empty;

            if (employees == null)
            {
                xmlScheduleRequest = this.CreateUpcomingShiftsRequest(startDate, endDate, personNumber);
            }
            else
            {
                xmlScheduleRequest = this.CreateUpcomingShiftsRequestEmployees(startDate, endDate, personNumber, employees);
            }

            TenantMapEntity tenantMapEntity = await this.azureTableStorageHelper.ExecuteQueryUsingPointQueryAsync <TenantMapEntity>(Constants.ActivityChannelId, tenantId);

            var tupleResponse = await ApiHelper.Instance.SendSoapPostRequest(tenantMapEntity.EndpointUrl, ApiConstants.SoapEnvOpen, xmlScheduleRequest, ApiConstants.SoapEnvClose, jSession);

            UpcomingShifts.Response scheduleResponse = this.ProcessResponse(tupleResponse.Item1);
            scheduleResponse.Jsession = tupleResponse.Item2;
            return(scheduleResponse);
        }
Exemple #5
0
        /// <summary>
        /// show employee details.
        /// </summary>
        /// <param name="context">dialog context.</param>
        /// <param name="result">awaitable string.</param>
        /// <returns>employee details.</returns>
        private async Task ShowEmployeeDetails(IDialogContext context, IAwaitable <string> result)
        {
            string  message      = await result;
            string  jSession     = string.Empty;
            string  personNumber = string.Empty;
            string  startDate    = default(string);
            string  endDate      = default(string);
            JObject tenant       = context.Activity.ChannelData as JObject;
            string  tenantId     = tenant["tenant"].SelectToken("id").ToString();

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

            AppInsightsLogger.CustomEventTrace("EmployeeLocationDialog", new Dictionary <string, string>()
            {
                { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowEmployeeDetails" }, { "Command", message }
            });
            // todays date
            startDate = context.Activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);
            endDate   = context.Activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);

            // get person number from employee name
            Response hyperFindResponse = await this.hyperFindActivity.GetHyperFindQueryValues(tenantId, jSession, startDate, endDate, ApiConstants.ReportsToHyperFindQuery, ApiConstants.PersonalVisibilityCode);

            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
            {
                var employee = hyperFindResponse.HyperFindResult.Where(x => x.FullName.ToLowerInvariant().Contains(message)).FirstOrDefault();
                if (employee == null)
                {
                    await context.PostAsync(Resources.KronosResourceText.NoEmpFoundByName.Replace("{txt}", message));
                }
                else
                {
                    JobAssignmentAlias.Response jobAssignmentResponse = await this.jobAssignmentActivity.getJobAssignment(employee?.PersonNumber, tenantId, jSession);

                    if (jobAssignmentResponse?.Status == ApiConstants.Failure)
                    {
                        if (jobAssignmentResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError)
                        {
                            await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
                        }
                    }
                    else
                    {
                        UpcomingShiftAlias.Response scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, jSession, startDate, endDate, employee?.PersonNumber);

                        ShowPunchesAlias.Response showPunchesResponse = await this.showPunchesActivity.ShowPunches(tenantId, jSession, employee?.PersonNumber, startDate, endDate);

                        if (showPunchesResponse?.Status != ApiConstants.Failure && scheduleResponse?.Status != ApiConstants.Failure)
                        {
                            await this.heroEmployeeLocation.ShowEmployeeDetailCard(context, scheduleResponse, showPunchesResponse, employee.FullName, jobAssignmentResponse);
                        }
                    }
                }
            }

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

            string   startDate     = string.Empty;
            string   endDate       = string.Empty;
            var      personNumber  = string.Empty;
            var      jSession      = string.Empty;
            string   allHours      = string.Empty;
            double   assignedHours = default(double);
            DateTime stDateTime    = default(DateTime);
            DateTime eDateTime     = default(DateTime);

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

            var      message             = activity.Text?.ToLowerInvariant().Trim();
            Response showPunchesResponse = default(Response);
            var      punchText           = string.Empty;

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

            switch (message)
            {
            case string command when command == Constants.PreviousPayPeriodPunches:
                punchText = Constants.PreviousPayPeriodPunchesText;
                CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.PreviousPayPeriodPunches);
                break;

            case string command when command == Constants.CurrentpayPeriodPunches || command == Constants.Punches || command == Constants.ShowMeMyPunches:
                punchText = Constants.CurrentpayPeriodPunchesText;
                CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.CurrentpayPeriodPunches);
                break;

            case string command when command.Contains(Constants.DateRangePunches):
                await this.dateRangeCard.ShowDateRange(context, Constants.SubmitDateRangePunches, Constants.PunchesDateRangeText);

                return;

            case string command when command.Contains(Constants.SubmitDateRangePunches):
                dynamic value = activity.Value;

                DateRange dateRange;

                if (value != null)
                {
                    dateRange = DateRange.Parse(value);
                    var  results = new List <ValidationResult>();
                    bool valid   = Validator.TryValidateObject(dateRange, new ValidationContext(dateRange, null, null), results, true);
                    if (!valid)
                    {
                        var errors = string.Join("\n", results.Select(o => " - " + o.ErrorMessage));
                        await context.PostAsync($"{Constants.DateRangeParseError}" + errors);

                        return;
                    }

                    startDate = DateTime.Parse(dateRange.StartDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);
                    endDate   = DateTime.Parse(dateRange.EndDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture);
                }

                break;
            }

            showPunchesResponse = await this.showPunchesActivity.ShowPunches(tenantId, jSession, personNumber, startDate, endDate);

            if (showPunchesResponse?.Status == ApiConstants.Success)
            {
                // get all hours worked and assigned hours
                context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession);
                UpcomingShiftsAlias.Response scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, superSession, startDate, endDate, 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));
                    }
                }

                // Getting the list of recorded punches
                var showPunchesDataOrderedList = showPunchesResponse?.Timesheet?.TotaledSpans?.TotaledSpan?
                                                 .Where(x => x.InPunch.Punch.EnteredOnDate != null).ToList();

                // Getting all hours worked time
                var showHoursWorkedOrderedList = showPunchesResponse?.Timesheet?.PeriodTotalData?.PeriodTotals?.Totals?.Total?.FindAll(x => x.PayCodeName == Constants.AllHours).Select(x => new { x.PayCodeName, x.AmountInTime }).FirstOrDefault();
                allHours = string.IsNullOrEmpty(showHoursWorkedOrderedList?.AmountInTime) ? "0" : showHoursWorkedOrderedList?.AmountInTime.Replace(':', '.');

                await this.showPunchesDataCard.ShowPunchesData(context, showPunchesDataOrderedList, punchText, startDate, endDate, response, string.Format("{0:0.00}", assignedHours), allHours);
            }
            else
            {
                await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity);
            }

            context.Done(showPunchesResponse);
        }
        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);
                }
            }
        }