/// <summary> /// Process recieved message. /// </summary> /// <param name="context">Dialog context.</param> /// <param name="result">Awaitable string.</param> /// <returns>Task.</returns> private async Task ProcessRequest(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; var message = activity.Text?.Trim(); JObject tenant = context.Activity.ChannelData as JObject; string tenantId = tenant["tenant"].SelectToken("id").ToString(); string jSessionId = string.Empty; string personNumber = string.Empty; if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response)) { jSessionId = this.response.JsessionID; personNumber = this.response.PersonNumber; } AppInsightsLogger.CustomEventTrace("ViewTimeOffRequestsDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ProcessRequest" }, { "Command", message } }); if (message.ToLowerInvariant().Contains(Constants.ShowAllTimeOff.ToLowerInvariant())) { await this.ProcessShowAllTimeoff(context, tenantId, jSessionId, personNumber, message); } 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)); }
/// <summary> /// show employees on approved leave. /// </summary> /// <param name="context">dialog context.</param> /// <param name="result">awaitable result.</param> /// <returns>employee on leave card.</returns> private async Task ShowEmployeesonLeaveAsync(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("OnLeaveDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowEmployeesonLeaveAsync" }, { "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.Success) { var leaveResult = await this.supervisorViewTimeOffActivity.GetTimeOffRequest(tenantId, jSession, startDate, endDate, hyperFindResponse?.HyperFindResult); if (leaveResult?.Status == ApiConstants.Success) { OvertimeMappingEntity entitySick = await this.azureTableStorageHelper.ExecuteQueryUsingPointQueryAsync <OvertimeMappingEntity>(Constants.ActivityChannelId, tenantId + "$" + Constants.SickAZTS, AppSettings.Instance.OvertimeMappingtableName); OvertimeMappingEntity entityVacation = await this.azureTableStorageHelper.ExecuteQueryUsingPointQueryAsync <OvertimeMappingEntity>(Constants.ActivityChannelId, tenantId + "$" + Constants.VacationAZTS, AppSettings.Instance.OvertimeMappingtableName); var vacationResult = leaveResult?.RequestMgmt?.RequestItems?.GlobalTimeOffRequestItem?.FindAll(x => (x.TimeOffPeriods?.TimeOffPeriod.PayCodeName.ToLowerInvariant() == entityVacation?.PayCodeName.ToLowerInvariant() || x.TimeOffPeriods?.TimeOffPeriod.PayCodeName.ToLowerInvariant() == entitySick?.PayCodeName.ToLowerInvariant()) && x.StatusName.ToLowerInvariant() == Constants.Approved.ToLowerInvariant()); Dictionary <string, string> resultData = new Dictionary <string, string>(); foreach (var v in vacationResult) { var employee = hyperFindResponse.HyperFindResult.Where(x => x.PersonNumber.Contains(v.CreatedByUser.PersonIdentity.PersonNumber)).FirstOrDefault(); resultData.Add(employee.FullName, v.TimeOffPeriods.TimeOffPeriod.PayCodeName); } await this.heroLeaveCard.ShowEmployeesonLeaveCard(context, resultData); } } context.Done(default(string)); }
private async Task SaveWorkRuleTransfer(IDialogContext context, IAwaitable <string> result) { var command = await result; context.PrivateConversationData.TryGetValue($"{context.Activity.From.Id}WorkRule", out string workRuleName); var activity = context.Activity as Activity; string jSession = this.response.JsessionID; 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; } AppInsightsLogger.CustomEventTrace("SaveWorkRuleTransferDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "SaveWorkRuleTransfer" }, { "Command", command } }); if (command.ToLowerInvariant() == Constants.Yes) { var addPunchResponse = await this.addPunchActivity.AddPunch(tenantId, jSession, personNumber, context.Activity.LocalTimestamp, workRuleName); var error = await this.CheckErrorResponse(addPunchResponse, context); if (!error) { await context.PostAsync(KronosResourceText.PunchWithTransferDone.Replace("{workRuleName}", workRuleName).Replace("{txt}", context.Activity.LocalTimestamp.Value.DateTime.ToString("dddd, dd MMMM yyyy h:mm tt", CultureInfo.InvariantCulture))); context.PrivateConversationData.SetValue($"{context.Activity.From.Id}WorkRule", string.Empty); } } else if (command.ToLowerInvariant() == Constants.No) { await context.PostAsync(KronosResourceText.TransferCanceled); } context.Done(string.Empty); }
/// <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); }
/// <summary> /// process the command and call respective method. /// </summary> /// <param name="context">dialog context.</param> /// <param name="result">awaitable string.</param> /// <returns>time off request.</returns> private async Task ProcessRequest(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; string isManager = await this.authUser.IsUserManager(context); if (isManager.ToLowerInvariant().Equals(Constants.Yes.ToLowerInvariant())) { var message = activity.Text?.ToLowerInvariant().Trim(); JObject tenant = context.Activity.ChannelData as JObject; string tenantId = tenant?["tenant"].SelectToken("id").ToString(); AppInsightsLogger.CustomEventTrace("SupervisorViewTimeOffDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ProcessRequest" }, { "Command", message } }); if (message.ToLowerInvariant() == Constants.SupervisorTORList.ToLowerInvariant()) { var managerCheck = await this.authUser.IsUserManager(context); if (!string.IsNullOrEmpty(managerCheck)) { if (managerCheck.ToLowerInvariant().Equals(Constants.Yes.ToLowerInvariant())) { context.PrivateConversationData.RemoveValue("FiltersHashTable"); await this.ShowTimeOffRequests(context); } } } else if (message.ToLowerInvariant() == Constants.TORRemoveEmpName.ToLowerInvariant()) { await this.ApplyFilter(context, message); } else if (message.ToLowerInvariant() == Constants.TORRemoveDateRange.ToLowerInvariant()) { await this.ApplyFilter(context, message); } else if (message.ToLowerInvariant() == Constants.TORRemoveShowCompletedRequests.ToLowerInvariant()) { await this.ApplyFilter(context, message); } else if (message.ToLowerInvariant() == Constants.TORListNext.ToLowerInvariant()) { await this.Next(context); } else if (message.ToLowerInvariant() == Constants.TORListPrevious.ToLowerInvariant()) { await this.Previous(context); } else if (message.ToLowerInvariant() == Constants.TORListRefresh.ToLowerInvariant()) { await this.ApplyFilter(context, message); } else if (message.ToLowerInvariant() == Constants.TORListApplyFilter.ToLowerInvariant()) { context.PrivateConversationData.RemoveValue("FiltersHashTable"); await this.ApplyFilter(context, message); } else if (message.ToLowerInvariant() == Constants.TORApproveRequest.ToLowerInvariant() || message.ToLowerInvariant() == Constants.TORRefuseRequest.ToLowerInvariant()) { await this.SubmitTimeOffApproval(context, message); } else { context.PrivateConversationData.RemoveValue("FiltersHashTable"); await this.ShowTimeOffRequests(context); } } context.Done(default(string)); }
/// <summary> /// show shifts. /// </summary> /// <param name="context">dialog context.</param> /// <param name="result">awaitable string.</param> /// <returns>show shifts for date or date ranges.</returns> private async Task ShowSchedule(IDialogContext context, IAwaitable <string> result) { string message = await result; string jSession = string.Empty; JObject tenant = context.Activity.ChannelData as JObject; string tenantId = tenant["tenant"].SelectToken("id").ToString(); string startDate = default(string); string endDate = default(string); // get person number string personNumber = string.Empty; if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response)) { personNumber = this.response.PersonNumber; jSession = this.response.JsessionID; } AppInsightsLogger.CustomEventTrace("UpcomingShiftsDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowSchedule" }, { "Command", message } }); if (message.Contains(KronosResourceText.Current)) { // current week DateTime start = context.Activity.LocalTimestamp.Value.DateTime.StartWeekDate(DayOfWeek.Sunday); startDate = start.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); endDate = start.EndOfWeek().ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); } else if (message.Contains(KronosResourceText.Next)) { // next week DateTime start = context.Activity.LocalTimestamp.Value.DateTime.StartWeekDate(DayOfWeek.Sunday).AddDays(6); startDate = start.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); endDate = start.EndOfWeek().ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); } else if (message.Equals(Constants.DateRangeShift, StringComparison.CurrentCultureIgnoreCase)) { // send date range card await this.carouselUpcomingShifts.ShowDateRange(context, Constants.SubmitDateRangeShift); context.Done(default(string)); return; } else if (message.Equals(Constants.SubmitDateRangeShift, StringComparison.CurrentCultureIgnoreCase)) { // date range submitted dynamic value = ((Activity)context.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); } } else { // default shifts for today startDate = context.Activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); endDate = context.Activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); } context.UserData.TryGetValue(context.Activity.From.Id + Constants.SuperUser, out string superSession); Response scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, superSession, startDate, endDate, personNumber); if (scheduleResponse?.Status == ApiConstants.Failure) { // check if authentication failure then send sign in card // User is not logged in - Send Sign in card if (scheduleResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError) { await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity); } else { await context.PostAsync(scheduleResponse.Error.Message); } } else { // send shift card if (message.Contains(KronosResourceText.Current)) { await context.PostAsync(KronosResourceText.DefaultShiftsText + " **" + Constants.CurrentWeek + "**"); } else if (message.Contains(KronosResourceText.Next)) { await context.PostAsync(KronosResourceText.DefaultShiftsText + " **" + Constants.NextWeek + "**"); } else if (message.Equals(Constants.SubmitDateRangeShift, StringComparison.CurrentCultureIgnoreCase)) { await context.PostAsync(KronosResourceText.DefaultShiftsText + KronosResourceText.From + " **" + DateTime.Parse(startDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture) + "** " + KronosResourceText.Till + " **" + DateTime.Parse(endDate, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy", CultureInfo.InvariantCulture) + "**"); } else { await context.PostAsync(KronosResourceText.DefaultShiftsText + " " + KronosResourceText.Today); } await this.carouselUpcomingShifts.ShowUpcomingShiftsCard(context, scheduleResponse, message); } context.Done(default(string)); }
private async Task ShowHoursWorked(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; bool status = false; if (!context.UserData.TryGetValue(context.Activity.From.Id, out LoginResponse response)) { response = this.response; } var message = activity.Text?.ToLowerInvariant().Trim(); Response showHoursWorkedResponse = default(Response); var punchText = string.Empty; AppInsightsLogger.CustomEventTrace("ShowHoursWorkedDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowHoursWorked" }, { "Command", message } }); var overtimeMappingEntity = await this.azureTableStorageHelper.ExecuteQueryUsingPointQueryAsyncFiltered <OvertimeMappingEntity>(Constants.ActivityChannelId, tenantId, AppSettings.Instance.OvertimeMappingtableName); var filteredResults = overtimeMappingEntity.Where(x => x.PayCodeType == Constants.TeamOvertimes || x.PayCodeType == Constants.Regular).Select(x => x.PayCodeName); switch (message) { case string command when command.Contains(Constants.PreviousPayPeriodHoursWorkedText): punchText = Constants.PreviousPayPeriodPunchesText; CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.PreviousPayPeriodPunches); break; case string command when command.Contains(Constants.DateRangeHoursWorked): await this.dateRangeCard.ShowDateRange(context, Constants.SubmitDateRangeHoursWorked, Constants.HoursWorkedDateRangeText); return; case string command when command.Contains(Constants.SubmitDateRangeHoursWorked): 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; case string command when command.Contains(Constants.CurrentpayPeriodHoursWorkedText) || command.Contains(Constants.HowManyHoursWorked) || command.Contains(Constants.Hour): punchText = Constants.CurrentpayPeriodPunchesText; CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.CurrentpayPeriodPunches); break; } showHoursWorkedResponse = await this.hoursWorkedActivity.ShowHoursWorked(tenantId, response, startDate, endDate); status = this.CheckResponseStatus(context, showHoursWorkedResponse); if (status) { var showHoursWorkedOrderedList = showHoursWorkedResponse?.Timesheet?.PeriodTotalData?.PeriodTotals?.Totals?.Total?.FindAll(x => filteredResults.Contains(x.PayCodeName) || x.PayCodeName == Constants.AllHours).Select(x => new { x.PayCodeName, x.AmountInTime }).ToList(); var regular = showHoursWorkedOrderedList?.FirstOrDefault(x => x.PayCodeName.Contains(Constants.Regular))?.AmountInTime ?? "0:00"; var overtime = showHoursWorkedOrderedList?.FirstOrDefault(x => x.PayCodeName.Contains(Constants.TeamOvertimes))?.AmountInTime ?? "0:00"; var allHours = showHoursWorkedOrderedList?.FirstOrDefault(x => x.PayCodeName.Contains(Constants.AllHours))?.AmountInTime; await this.showHoursWorkedCard.ShowHoursWorkedData(context, showHoursWorkedResponse, punchText, startDate, endDate, regular, overtime, allHours); } else { await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity); } context.Done(showHoursWorkedResponse); }
/// <summary> /// Method is used to show overtime employees list. /// </summary> /// <param name="context">Dialog context.</param> /// <param name="result">Awaitable string.</param> /// <returns>A task.</returns> private async Task ShowOvertimeEmployeesList(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; var tenant = activity.ChannelData as JObject; var tenantId = tenant["tenant"].SelectToken("id").ToString(); var startDate = activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); var endDate = activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); var overtimeEmployeeList = new List <string>(); var payPeriod = string.Empty; if (!context.UserData.TryGetValue(context.Activity.From.Id, out LoginResponse response)) { response = this.response; } var message = activity.Text?.ToLowerInvariant().Trim(); AppInsightsLogger.CustomEventTrace("TeamOvertimesDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowOvertimeEmployeesList" }, { "Command", message } }); switch (message) { case string command when command.ToLowerInvariant().Contains(Constants.OvertimeNext.ToLowerInvariant()): await this.Next(context); break; case string command when command.ToLowerInvariant().Contains(Constants.OvertimePrevious.ToLowerInvariant()): await this.Previous(context); break; case string command when command.Contains(Constants.PreviousWeekTeamOvertimes): CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.PreviousPayPeriodPunches); payPeriod = Constants.PreviousPayPeriodPunchesText; await this.ShowOvertimeEmployees(context, tenantId, startDate, endDate, overtimeEmployeeList, payPeriod, response); break; case string command when command.Contains(Constants.DateRangeTeamOvertimes): await this.dateRangeCard.ShowDateRange(context, Constants.SubmitDateRangeTeamOvertimes, Constants.TeamOvertimesDateRangeText); break; case string command when command.Contains(Constants.SubmitDateRangeTeamOvertimes): 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); } await this.ShowOvertimeEmployees(context, tenantId, startDate, endDate, overtimeEmployeeList, payPeriod, response); break; case string command when command.Contains(Constants.CurrentWeekTeamOvertimes) || command.Contains(Constants.TeamOvertimes.ToLowerInvariant()): CalculatePayPeriod(context.Activity.LocalTimestamp, out startDate, out endDate, Constants.CurrentpayPeriodPunches); payPeriod = Constants.CurrentpayPeriodPunchesText; await this.ShowOvertimeEmployees(context, tenantId, startDate, endDate, overtimeEmployeeList, payPeriod, response); break; } context.Done(string.Empty); }
private async Task AddPunch(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; string jSession = this.response.JsessionID; JObject tenant = context.Activity.ChannelData as JObject; string tenantId = tenant["tenant"].SelectToken("id").ToString(); string personNumber = string.Empty; context.PrivateConversationData.TryGetValue($"{context.Activity.From.Id}WorkRule", out string workRuleName); context.PrivateConversationData.TryGetValue($"{context.Activity.From.Id}AddPunch", out string addPunch); if (context.UserData.TryGetValue(context.Activity.From.Id, out this.response)) { personNumber = this.response.PersonNumber; } var message = activity.Text?.ToLowerInvariant().Trim(); AppInsightsLogger.CustomEventTrace("AddPunchDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "AddPunch" }, { "Command", message } }); switch (message) { case string command when command.Contains(Constants.WorkRuleTransfer): var response = await this.addPunchActivity.LoadAllWorkRules(tenantId, jSession, personNumber); if (response?.Status == ApiConstants.Failure && response.Error?.ErrorCode == ApiConstants.UserNotLoggedInError) { await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity); break; } await this.addPunchCard.ShowAllWorkRules(context, response); break; case string command when command.Contains(Constants.RecentTransfer): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.RecentTransfer); break; case string command when command.Contains(Constants.Punch): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.Punch); break; case string command when command.Contains(Constants.WRTAdminAssistant.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTAdminAssistant, true); break; case string command when command.Contains(Constants.WRTAdminAssistant.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTAdminAssistant, true); break; case string command when command.Contains(Constants.WRTAdministration.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTAdministration, true); break; case string command when command.Contains(Constants.WRTCA8hrDay.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTCA8hrDay, true); break; case string command when command.Contains(Constants.WRTCA9HrDay.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTCA9HrDay, true); break; case string command when command.Contains(Constants.WRTCAFullTime.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTCAFullTime, true); break; case string command when command.Contains(Constants.WRTCallback.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTCallback, true); break; case string command when command.Contains(Constants.WRTFullTimeExecutive.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTFullTimeExecutive, true); break; case string command when command.Contains(Constants.WRTExecutive.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTExecutive, true); break; case string command when command.Contains(Constants.WRTFullTime30Min.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTFullTime30Min, true); break; case string command when command.Contains(Constants.WRTFullTime60MinNoZone.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTFullTime60MinNoZone, true); break; case string command when command.Contains(Constants.WRTFullTime60Min.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTFullTime60Min, true); break; case string command when command.Contains(Constants.WRTOnCall.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTOnCall, true); break; case string command when command.Contains(Constants.WRTPartTime.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTPartTime, true); break; case string command when command.Contains(Constants.WRTProfessionalHourly.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTProfessionalHourly, true); break; case string command when command.Contains(Constants.WRTProfessionalSalariedWFS.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTProfessionalSalariedWFS, true); break; case string command when command.Contains(Constants.WRTProfessionalSalaried.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTProfessionalSalaried, true); break; case string command when command.Contains(Constants.WRTSalaried.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTSalaried, true); break; case string command when command.Contains(Constants.WRTSupport.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTSupport, true); break; case string command when command.Contains(Constants.WRTTechnicalService.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTTechnicalService, true); break; case string command when command.Contains(Constants.WRTTraining.ToLowerInvariant().Trim()): await this.addPunchCard.AddPunches(context, context.Activity.LocalTimestamp, Constants.WRTTraining, true); break; } context.Done(default(Response)); }
/// <summary> /// Method is used to show present or absent employees. /// </summary> /// <param name="context">Dialog context.</param> /// <param name="result">Awaitable string.</param> /// <returns>A task.</returns> private async Task ShowPresentEmployees(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; JObject tenant = activity.ChannelData as JObject; string tenantId = tenant["tenant"].SelectToken("id").ToString(); var personNumber = string.Empty; var jSession = string.Empty; if (!context.UserData.TryGetValue(context.Activity.From.Id, out LoginResponse response)) { response = this.response; } else { personNumber = response.PersonNumber; jSession = response.JsessionID; } AppInsightsLogger.CustomEventTrace("PresentEmployeesDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ShowPresentEmployees" }, { "Command", activity.Text } }); List <TotaledSpan> totaledSpan = new List <TotaledSpan>(); var presentEmployeeList = new SortedList <string, string>(); var personName = string.Empty; string message = activity.Text.ToLowerInvariant().Trim(); var startDate = activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); var endDate = activity.LocalTimestamp.Value.DateTime.Date.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); var isHere = activity.Text.ToLowerInvariant().Contains(Constants.WhoIsHere); switch (message) { case string command when command.Contains(Constants.presentEmpNextpage) || command.Contains(Constants.presentEmpPrevpage) || command.Contains(Constants.absentEmpPrevpage) || command.Contains(Constants.absentEmpNextpage): var item = command.Split('/'); await this.PrevNext(context, Convert.ToInt32(item[2]), message); break; default: string isManager = await this.authenticateUser.IsUserManager(context); if (isManager.Equals(Constants.Yes)) { Models.ResponseEntities.HyperFind.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 { await context.PostAsync(hyperFindResponse.Error?.Message); } } else { var scheduleResponse = await this.upcomingShiftsActivity.ShowUpcomingShifts(tenantId, jSession, startDate, endDate, personNumber, hyperFindResponse.HyperFindResult); if (scheduleResponse?.Status == ApiConstants.Failure) { if (scheduleResponse.Error?.ErrorCode == ApiConstants.UserNotLoggedInError) { await this.authenticationService.SendAuthCardAsync(context, (Activity)context.Activity); } else { await context.PostAsync(scheduleResponse.Error?.Message); } } else { var scheduleShift = scheduleResponse?.Schedule?.ScheduleItems?.ScheduleShift?.GroupBy(x => x.Employee[0].PersonNumber); // Employee has a shift if (scheduleShift != null && scheduleShift.Any() && scheduleShift?.Count() > 0) { var pNumber = string.Empty; var currentDay = activity.LocalTimestamp.Value.Date; endDate = currentDay.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); startDate = currentDay.ToString(ApiConstants.DateFormat, CultureInfo.InvariantCulture); foreach (var items in scheduleShift) { var startDates = items.Select(x => x.ShiftSegments[0].StartDate).FirstOrDefault(); var endDates = items.Select(x => x.ShiftSegments.LastOrDefault().EndDate).FirstOrDefault(); var startTime = items.Select(x => x.ShiftSegments.FirstOrDefault().StartTime).FirstOrDefault(); var endTime = items.Select(x => x.ShiftSegments.LastOrDefault().EndTime).LastOrDefault(); var shiftStartDate = DateTime.Parse($"{startDates} {startTime}", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture); var shiftEndDate = DateTime.Parse($"{endDates} {endTime}", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture); pNumber = items.Key; var showPunchesResponse = await this.showPunchesActivity.ShowPunches(tenantId, jSession, pNumber, startDate, endDate); totaledSpan = showPunchesResponse?.Timesheet?.TotaledSpans?.TotaledSpan; personName = hyperFindResponse.HyperFindResult.Find(x => x.PersonNumber == pNumber).FullName; JobAssignmentAlias.Response jobAssignmentResponse = await this.jobAssignmentActivity.getJobAssignment(pNumber, tenantId, jSession); int lastIndex = (jobAssignmentResponse != null) ? (jobAssignmentResponse?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath).LastIndexOf('/') : 0; if (totaledSpan.Count > 0) { if (activity.Text.ToLowerInvariant().Contains(Constants.WhoIsHere) && totaledSpan.Any(x => x.InPunch.Punch.EnteredOnDate != null)) { presentEmployeeList.Add(personName, jobAssignmentResponse?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Substring(lastIndex + 1)); } else if (activity.Text.ToLowerInvariant().Contains(Constants.WhoIsNotHere) && totaledSpan.Any(x => x.InPunch.Punch.EnteredOnDate == null)) { // absent employees presentEmployeeList.Add(personName, jobAssignmentResponse?.JobAssign?.PrimaryLaborAccList?.PrimaryLaborAcc?.OrganizationPath?.Substring(lastIndex + 1)); } } } } var pagewiseAttendance = this.GetPagewiseList(presentEmployeeList); // save data for pagination if (isHere) { context.PrivateConversationData.SetValue("PagewisePresentAttendance", pagewiseAttendance); } else { context.PrivateConversationData.SetValue("PagewiseAbsentAttendance", pagewiseAttendance); } await this.presentEmployeesCard.ShowPresentEmployeesData(context, presentEmployeeList.Take(5), isHere, message, 1, presentEmployeeList.Count); } } } else if (isManager.Equals(Constants.No)) { await context.PostAsync(KronosResourceText.NoPermission); } break; } context.Done(string.Empty); }
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)); }
/// <summary> /// process the command and call respective method. /// </summary> /// <param name="context">Dialog context.</param> /// <param name="result">Awaitable string.</param> /// <returns>Time off request.</returns> private async Task ProcessRequest(IDialogContext context, IAwaitable <string> result) { var activity = context.Activity as Activity; var message = activity.Text?.ToLowerInvariant().Trim(); JObject tenant = context.Activity.ChannelData as JObject; string tenantId = tenant["tenant"].SelectToken("id").ToString(); AppInsightsLogger.CustomEventTrace("TimeOffDialog", new Dictionary <string, string>() { { "TenantId", tenantId }, { "User", context.Activity.From.Id }, { "methodName", "ProcessRequest" }, { "Command", message } }); if (message.ToLowerInvariant().Equals(Constants.SubmitTimeOff.ToLowerInvariant())) { await this.SubmitTimeOffRequest(context); } else if (message.ToLowerInvariant().Equals(Constants.CancelTimeOff.ToLowerInvariant())) { string fullPath = HttpContext.Current.Server.MapPath("/Cards/AdaptiveCards/TimeOff/CancelTimeOffRequest.json"); var json = File.ReadAllText(fullPath); var card = AdaptiveCard.FromJson(json).Card; 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)); try { context.PrivateConversationData.RemoveValue("AdvancedRequestObj"); 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; } } else if (message.ToLowerInvariant() == Constants.SubmitAdvancedTimeOff.ToLowerInvariant()) { await this.SubmitAdvancedTimeOffRequest(context); } else if (message.ToLowerInvariant() == Constants.ApproveTimeoff.ToLowerInvariant() || message.ToLowerInvariant() == Constants.RefuseTimeoff.ToLowerInvariant()) { await this.SubmitTimeOffApproval(context, message); } else if (message.ToLowerInvariant().Contains("advanced")) { await this.ProcessAdvancedTimeOffRequest(context); } else { var allPaycodes = await this.azureTableStorageHelper.GetTimeOffPaycodes(AppSettings.Instance.OvertimeMappingtableName); var filteredPaycodes = (from d in allPaycodes where d.RowKey.Contains(tenantId) select d).Select(w => w.Properties["PayCodeName"].StringValue).ToList(); IMessageActivity reply = this.timeOffCard.GetBasicTimeOffRequestCard(context, filteredPaycodes); if (reply.Attachments.Count > 0) { await context.PostAsync(reply); } else { await context.PostAsync(Resources.KronosResourceText.UnableToProceed); } } context.Done(default(string)); }