public EventCustomerPcpAppointmentEditModel GetEventCustomerEventModel(long eventcustomerId) { var eventCustomer = _eventCustomerRepository.GetById(eventcustomerId); var account = _corporateAccountRepository.GetbyEventId(eventCustomer.EventId); var customer = _customerRepository.GetCustomer(eventCustomer.CustomerId); var theEvent = _eventRepository.GetById(eventCustomer.EventId); var host = _hostRepository.GetHostForEvent(eventCustomer.EventId); var order = _orderRepository.GetOrder(eventCustomer.CustomerId, eventCustomer.EventId); var eventPackage = _eventPackageRepository.GetPackageForOrder(order.Id); var eventTest = _eventTestRepository.GetTestsForOrder(order.Id); var pcpDispositions = _pcpDispositionRepository.GetByCustomerIdEventId(eventCustomer.CustomerId, eventCustomer.EventId); var pcpAppointment = GetPcpAppointment(eventCustomer, pcpDispositions); PcpDisposition pcpDisposition = null; if (!pcpDispositions.IsNullOrEmpty()) { pcpDisposition = pcpDispositions.OrderByDescending(pd => pd.DataRecorderMetaData.DateCreated).First(); } var customerTest = new List<string>(); if (eventPackage != null) { customerTest.AddRange(eventPackage.Tests.Select(x => x.Test.Name)); } if (eventTest != null && eventTest.Any()) { customerTest.AddRange(eventTest.Select(x => x.Test.Name)); } var model = new EventCustomerPcpAppointmentEditModel { EventCustomerId = eventCustomer.Id, EventId = eventCustomer.EventId, CustomerId = customer.CustomerId, CustomerName = customer.Name, PhoneNumber = customer.HomePhoneNumber, CustomerEmail = customer.Email, ScreeningDate = theEvent.EventDate, HostName = host.OrganizationName, Location = host.Address, ScreenedForTest = customerTest, BookAfterNumberOfDays = account != null ? account.NumberOfDays : 0, NotAbleToSchedule = (pcpAppointment == null && pcpDisposition != null), DispositionId = (pcpAppointment == null && pcpDisposition != null) ? (long)pcpDisposition.Disposition : 0, Notes = (pcpAppointment == null && pcpDisposition != null) ? pcpDisposition.Notes : string.Empty, AppointmentDate = pcpAppointment != null ? pcpAppointment.AppointmentOn.Date : (DateTime?)null, AppointmentTime = pcpAppointment != null ? pcpAppointment.AppointmentOn.ToString("hh:mm: tt") : null, PreferredContactMethod = pcpAppointment != null ? pcpAppointment.PreferredContactMethod : -1, EventDate = theEvent.EventDate }; return model; }
public bool CodingCompleted(MedicareCustomerResultCodedViewModel codingCompleted) { try { _logger.Info("Running CodingCompled API for Aces for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId); if (string.IsNullOrWhiteSpace(codingCompleted.EmployeeId)) { _logger.Info("EmployeeId is blank. CodingCompleted API for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId); return(false); } var oru = _organizationRoleUserRepository.GetOrganizationRoleUserByEmployeeIdandRoleId(codingCompleted.EmployeeId, (long)Roles.Coder); if (oru == null) { _logger.Info("EmployeeId or Coder role not exist. CodingCompleted API for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId); return(false); } var account = _corporateAccountRepository.GetbyEventId(codingCompleted.EventId); if (account != null && account.IsHealthPlan) { var eventCustomer = _eventCustomerRepository.Get(codingCompleted.EventId, codingCompleted.CustomerId); var isTestPurchased = _testResultService.IsTestPurchasedByCustomer(eventCustomer.Id, (long)TestType.eAWV); var theEvent = _eventRepository.GetById(codingCompleted.EventId); var questionnaireType = _accountHraChatQuestionnaireHistoryServices.QuestionnaireTypeByAccountIdandEventDate(account.Id, theEvent.EventDate); if ((questionnaireType != QuestionnaireType.HraQuestionnaire) || !isTestPurchased) { _testResultService.SaveCustomerResultCoded(codingCompleted, oru); _logger.Info("customer result state Updated for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId); } else { _logger.Info("Only HRA is allowed to update for customer Id: " + codingCompleted.CustomerId + " EventId: " + codingCompleted.EventId); return(false); } } else { _logger.Info("Coding Completed can be marked only for HealthPlan Events. Customer Id: " + codingCompleted.CustomerId + " EventId: " + codingCompleted.EventId); return(false); } _logger.Info("completed CodingCompleted API for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId + " Successfully"); return(true); } catch (Exception ex) { _logger.Info("completed CodingCompleted API for Customer Id: " + codingCompleted.CustomerId + " EventId : " + codingCompleted.EventId + " With Error"); _logger.Error("Message: " + ex.Message); _logger.Error("StackTrace: " + ex.StackTrace); return(false); } }
public OnlineSchedulingProcessAndCartViewModel GetOnlineCart(TempCart tempCart) { var customer = tempCart.CustomerId == null ? null : _customerRepository.GetCustomer(tempCart.CustomerId.Value); var appointment = tempCart.AppointmentId.HasValue ? _slotRepository.GetbyId(tempCart.AppointmentId.Value) : null; string sponsoredBy = ""; var checkoutPhoneNumber = string.Empty; if (tempCart.EventId.HasValue) { var hospitalPartnerId = _hospitalPartnerRepository.GetHospitalPartnerIdForEvent(tempCart.EventId.Value); if (hospitalPartnerId > 0) { var hospitalPartner = _organizationRepository.GetOrganizationbyId(hospitalPartnerId); sponsoredBy = hospitalPartner.Name; } var account = _corporateAccountRepository.GetbyEventId(tempCart.EventId.Value); if (account != null && account.CheckoutPhoneNumber != null && !string.IsNullOrWhiteSpace(PhoneNumber.ToNumber(account.CheckoutPhoneNumber.ToString()))) { checkoutPhoneNumber = account.CheckoutPhoneNumber.FormatPhoneNumber; } } return(_onlineSchedulingDataFactory.Create(tempCart, customer, appointment, sponsoredBy, checkoutPhoneNumber)); }
private void GeneratexmlforEventCustomers(long eventId, DateTime eventDate, Event eventDetail) { _logger.Info("Getting event customers......"); int totalrecords; var eventCusomters = _eventCustomerRepository.GetHhynEventCustomers(1, 400, new KynCustomerModelFilter { EventId = eventId }, out totalrecords); var corporateAccount = _corporateAccountRepository.GetbyEventId(eventId); if (eventCusomters == null || !eventCusomters.Any()) { return; } _logger.Info(string.Format("{0} event customers found.", eventCusomters.Count())); foreach (var ec in eventCusomters) { try { var corpAccountcode = corporateAccount != null?corporateAccount.AccountCode.Trim() : string.Empty; _kynLipidService.GenerateKynXMlforCustomer(ec, eventId, eventDate, corpAccountcode, generatekynXml: false); } catch (Exception exception) { _logger.Error(string.Format("Error while generating kyn xml for customer Id: {0} and EventId {1} Message: {2}, StackTrace {3}", ec.CustomerId, ec.EventId, exception.Message, exception.StackTrace)); } } GenerateMetadataXmlForEvent(eventDetail); }
public ActionResult Index(AccountVerificationEditModel model) { model = model ?? new AccountVerificationEditModel(); model.CheckoutPhoneNumber = _settings.PhoneTollFree; try { CorporateAccount corporateAccount = null; if (!string.IsNullOrWhiteSpace(model.UrlSuffix)) { corporateAccount = _corporateAccountRepository.GetByUrlSiffix(model.UrlSuffix); } else if (!string.IsNullOrWhiteSpace(model.InvitationCode)) { var theEvent = _eventRepository.GetEventByInvitationCode(model.InvitationCode); if (theEvent != null) { corporateAccount = _corporateAccountRepository.GetbyEventId(theEvent.Id); } } if (corporateAccount != null) { model.Content = corporateAccount.Content; model.AllowVerifiedMembersOnly = corporateAccount.AllowVerifiedMembersOnly; model.CheckoutPhoneNumber = (corporateAccount.CheckoutPhoneNumber != null && !string.IsNullOrWhiteSpace(corporateAccount.CheckoutPhoneNumber.DomesticPhoneNumber)) ? corporateAccount.CheckoutPhoneNumber.FormatPhoneNumber : _settings.PhoneTollFree; } } catch (Exception exception) { _logger.Error(string.Format("While accessing private\\Index Message: {0} \n Stack Trace: {1} ", exception.Message, exception.StackTrace)); } return(View(model)); }
public JsonResult UpdateCustomerVisitInfo(string guid, long visitId) { if (!_settings.SyncWithHra) { return(Json(new { Result = false }, JsonRequestBehavior.DenyGet)); } if (string.IsNullOrEmpty(guid) || Session[guid] == null) { return(Json(new { Result = false }, JsonRequestBehavior.DenyGet)); } var registrationFlowModel = (RegistrationFlowModel)Session[guid]; registrationFlowModel.AwvVisitId = visitId; var account = _corporateAccountRepository.GetbyEventId(registrationFlowModel.EventId); if (account != null) { var theEvent = _eventRepository.GetById(registrationFlowModel.EventId); _medicareApiService.Connect(_sessionContext.UserSession.UserLoginLogId); _medicareApiService.Post <long>(MedicareApiUrl.EventInfoUpdateUrl, new MedicareEventEditModel { EventId = registrationFlowModel.EventId, Tag = account.Tag, VisitId = visitId, VisitDate = theEvent.EventDate }); } return(Json(new { Result = true }, JsonRequestBehavior.DenyGet)); }
public void PollforSendingScondScreeningReminders() { try { var value = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.ScreeningReminderNotification); if (value.ToLower() != bool.TrueString.ToLower()) { return; } var eventCustomers = _eventCustomerRepository.GetEventCustomersForSecondScreeingReminderNotification(_hoursBeforeAppointment, _interval); if (eventCustomers != null && eventCustomers.Any()) { foreach (var eventCustomer in eventCustomers) { try { var account = _corporateAccountRepository.GetbyEventId(eventCustomer.EventId); if (account != null && !(account.SendAppointmentMail && account.AppointmentReminderMailTemplateId > 0)) { continue; } _logger.Info(string.Format("Sending second screening reminder for Customer [Id:{0}] and Event[Id:{1}] ", eventCustomer.CustomerId, eventCustomer.EventId)); var customer = _customerRepository.GetCustomer(eventCustomer.CustomerId); var appointmentConfirmationViewModel = _emailNotificationModelsFactory.GetAppointmentConfirmationModel(eventCustomer.EventId, eventCustomer.CustomerId); string emailTemplateAlias = EmailTemplateAlias.ScreeningReminderMail; if (account != null && account.AppointmentReminderMailTemplateId > 0) { var emailTemplate = _emailTemplateRepository.GetById(account.AppointmentReminderMailTemplateId); emailTemplateAlias = emailTemplate.Alias; } _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.TwoHoursBeforeAppointment, emailTemplateAlias, appointmentConfirmationViewModel, customer.Id, eventCustomer.CustomerId, "Second Automated Reminder Notification"); } catch (Exception ex) { _logger.Error(string.Format("Message:{0} \nStackTrace: {1}", ex.Message, ex.StackTrace)); } } } else { _logger.Info("No Customers Found for Second screening reminder!"); } } catch (Exception exception) { _logger.Error("Exception occurred while Poll for Sending Second Screening Reminders"); _logger.Error("Exception: " + exception.Message); _logger.Error("Exception: " + exception.StackTrace); } }
private void RenameAndCopyMediaFile(long customerId, long eventId, IEnumerable <OrderedPair <string, long> > mediaFiles) { try { var customer = _customerRepository.GetCustomer(customerId); if (customer == null) { _logger.Info("Customer not found for Customer Id :" + customerId + " and Event Id :" + eventId); return; } var eventData = _eventRepository.GetEventOnlyById(eventId); if (eventData == null) { _logger.Info("Event not found for Customer Id :" + customerId + " and Event Id :" + eventId); return; } var eventDate_ = eventData.EventDate; if (eventDate_ < _settings.StopSendingMediaFileDate) { _logger.Info("We are not Sending media file of event which event Date is less then " + _settings.StopSendingMediaFileDate + ". Event Id " + eventId + ", Customer Id " + customerId); return; } var mediaPath = _mediaRepository.GetResultMediaFileLocation(customerId, eventId).PhysicalPath; var account = _corporateAccountRepository.GetbyEventId(eventId); foreach (var fileDetail in mediaFiles) { var testType = (TestType)fileDetail.SecondValue; var mediaFileName = fileDetail.FirstValue; var fileExtention = Path.GetExtension(mediaFileName); var sourceImagePath = Path.Combine(mediaPath, mediaFileName); if (ConvertToPdf(testType)) { var fileAndFolderName = _sendMediaFileHelper.GetSftpFileAndFolder(account, customer, eventData, testType.ToString(), fileExtention, true); var pdfPath = ConvertToPdf(sourceImagePath); CopyMediaFile(pdfPath, fileAndFolderName.SecondValue, fileAndFolderName.FirstValue); } else { var fileAndFolderName = _sendMediaFileHelper.GetSftpFileAndFolder(account, customer, eventData, testType.ToString(), fileExtention, true); CopyMediaFile(sourceImagePath, fileAndFolderName.SecondValue, fileAndFolderName.FirstValue); } } } catch (Exception ex) { _logger.Error("Message:" + ex.Message); _logger.Error("StackTrace:" + ex.StackTrace); } }
public void PollforKynNotification() { var notificationTypes = _notificationTypeRepository.GetAll(); var notificationIsActive = notificationTypes.Any(nt => (nt.NotificationTypeAlias == NotificationTypeAlias.KynFirstNotification) && nt.IsActive); if (!notificationIsActive) { return; } const int pageSize = 50; int pageNumber = 1; while (true) { long totalRecords; var eventCustomers = _eventCustomerRepository.GetEventCustomersForKynFirstNotification(_daysAfterRegistration, pageNumber, pageSize, out totalRecords); if (eventCustomers == null || !eventCustomers.Any()) { _logger.Info("No Customers Found!"); break; } foreach (var eventCustomer in eventCustomers) { try { var corporateAccount = _corporateAccountRepository.GetbyEventId(eventCustomer.EventId); if (corporateAccount != null && !corporateAccount.AllowCustomerPortalLogin) { continue; } var notificationModel = _kynNotificationService.IsApplicableForNotification(eventCustomer); if (notificationModel != null) { _logger.Info(string.Format("Sending First Kyn Notification for Customer [Id:{0}] and Event[Id:{1}] ", eventCustomer.CustomerId, eventCustomer.EventId)); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.KynFirstNotification, EmailTemplateAlias.KynFirstNotification, notificationModel, notificationModel.UserId, eventCustomer.CustomerId, "Kyn First Notification"); } } catch (Exception ex) { _logger.Error(string.Format("Message:{0} \nStackTrace: {1}", ex.Message, ex.StackTrace)); } } if ((pageNumber * pageSize) >= totalRecords) { break; } pageNumber++; } }
private void SendNotification(Customer customer, Event eventData, OrganizationRoleUser createdByOrgRoleUser, string source) { var account = _corporateAccountRepository.GetbyEventId(eventData.Id); if (account == null || account.SendWelcomeEmail) { var welcomeEmailViewModel = _emailNotificationModelsFactory.GetWelcomeWithUserNameNotificationModel(customer.UserLogin.UserName, customer.Name.FullName, customer.DateCreated); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.CustomerWelcomeEmailWithUsername, EmailTemplateAlias.CustomerWelcomeEmailWithUsername, welcomeEmailViewModel, customer.Id, createdByOrgRoleUser.Id, source); SendResetPasswordMail(customer.Id, customer.Name.FullName, createdByOrgRoleUser.Id, source); } SendAppointmentConfirmationMail(customer, eventData, createdByOrgRoleUser.Id, source, account); }
public OnlineRequestValidationModel ValidateOnlineRequest(string guid) { if (string.IsNullOrEmpty(guid)) { return new OnlineRequestValidationModel { RequestStatus = OnlineRequestStatus.Valid, CaptureOnlineHaf = true } } ; var tempCart = _tempCartRepository.Get(guid); var onlineRequestValidationModel = new OnlineRequestValidationModel { TempCart = tempCart }; if (tempCart != null) { if (tempCart.DateCreated.AddDays(1) < DateTime.Now) { onlineRequestValidationModel.RequestStatus = OnlineRequestStatus.InvalidOperation; } else { onlineRequestValidationModel.RequestStatus = OnlineRequestStatus.Valid; } } else { tempCart = _tempCartRepository.Get(guid, true); onlineRequestValidationModel.TempCart = tempCart; onlineRequestValidationModel.RequestStatus = tempCart != null ? OnlineRequestStatus.Completed : OnlineRequestStatus.InValid; } CorporateAccount account = null; if (tempCart != null && tempCart.EventId.HasValue && (onlineRequestValidationModel.RequestStatus == OnlineRequestStatus.Completed || onlineRequestValidationModel.RequestStatus == OnlineRequestStatus.Valid)) { account = _corporateAccountRepository.GetbyEventId(tempCart.EventId.Value); } onlineRequestValidationModel.CaptureOnlineHaf = (account == null || account.CaptureHafOnline); onlineRequestValidationModel.IsCorporateEvent = (account != null); return(onlineRequestValidationModel); }
public GiftCertificateViewModel GetModel(long eventId, long customerId) { var eventData = _eventRepository.GetById(eventId); var customer = _customerRepository.GetCustomer(customerId); var eventCustomer = _eventCustomerRepository.Get(eventId, customerId); var account = _corporateAccountRepository.GetbyEventId(eventId); var patientGiftCardSignatureUrl = string.Empty; var technicianGiftCardSignatureUrl = string.Empty; var giftCardSignatureMediaLocation = _mediaRepository.GetGiftCardSignatureLocation(eventId, customerId); var giftCertificateSignature = _eventCustomerGiftCardRepository.GetByEventCustomerId(eventCustomer.Id); if (giftCertificateSignature != null && (giftCertificateSignature.PatientSignatureFileId.HasValue || giftCertificateSignature.TechnicianSignatureFileId.HasValue)) { var signatureFileIds = new List <long>(); if (giftCertificateSignature.PatientSignatureFileId.HasValue) { signatureFileIds.Add(giftCertificateSignature.PatientSignatureFileId.Value); } if (giftCertificateSignature.TechnicianSignatureFileId.HasValue) { signatureFileIds.Add(giftCertificateSignature.TechnicianSignatureFileId.Value); } var signatureFiles = _fileRepository.GetByIds(signatureFileIds); if (giftCertificateSignature.PatientSignatureFileId.HasValue) { var patientFile = signatureFiles.First(x => x.Id == giftCertificateSignature.PatientSignatureFileId.Value); patientGiftCardSignatureUrl = giftCardSignatureMediaLocation.Url + patientFile.Path; } if (giftCertificateSignature.TechnicianSignatureFileId.HasValue) { var technicianFile = signatureFiles.First(x => x.Id == giftCertificateSignature.TechnicianSignatureFileId.Value); technicianGiftCardSignatureUrl = giftCardSignatureMediaLocation.Url + technicianFile.Path; } } return(new GiftCertificateViewModel { CustomerId = customer.CustomerId, CustomerName = customer.Name, EventDate = eventData.EventDate, GiftAmmount = account.GiftCardAmount ?? 0, GiftCardReceived = giftCertificateSignature != null ? giftCertificateSignature.GiftCardReceived : (bool?)null, PatientSignatureUrl = patientGiftCardSignatureUrl, TechnicianSignatureUrl = technicianGiftCardSignatureUrl }); }
public OnlineEventListModel GetEvents([FromUri] OnlineSchedulingEventListModelFilter filter) { filter.CutOffHourstoMarkEventforOnlineSelection = _cutOffhoursbeforeEventSelection; var onlineRequestValidationModel = _tempcartService.ValidateOnlineRequest(filter.Guid); var model = new OnlineEventListModel { RequestValidationModel = onlineRequestValidationModel }; if (onlineRequestValidationModel.RequestStatus != OnlineRequestStatus.Valid) { return(model); } int totalRecords = 0; if (!string.IsNullOrEmpty(filter.Guid)) { filter = CompleteFilter(model.RequestValidationModel.TempCart, filter); } model.Events = _onlineEventService.GetEvents(filter, _maxNumberOfEventstoFetch, _pageSize, out totalRecords); model.TotalEvents = totalRecords; model.PagingModel = new PagingModel(filter.PageNumber, _pageSize, totalRecords, null); if (string.IsNullOrWhiteSpace(filter.InvitationCode)) { return(model); } ; var theEvent = _eventRepository.GetEventByInvitationCode(filter.InvitationCode); if (theEvent != null) { var account = _corporateAccountRepository.GetbyEventId(theEvent.Id); if (account != null && account.CheckoutPhoneNumber != null && !string.IsNullOrWhiteSpace(account.CheckoutPhoneNumber.DomesticPhoneNumber)) { model.CheckoutPhoneNumber = account.CheckoutPhoneNumber.FormatPhoneNumber; } } return(model); }
public IEnumerable <ExitInterviewQuestionAnswerEditModel> GetQuestions(long eventCustomerId) { var list = new List <ExitInterviewQuestionAnswerEditModel>(); var eventCustomer = _eventCustomerRepository.GetById(eventCustomerId); if (eventCustomer == null) { return(list); } var questions = _exitInterviewQuestionRepository.GetAllQuestions(); var answers = _exitInterviewAnswerRepository.GetByEventCustomerId(eventCustomerId); var account = _corporateAccountRepository.GetbyEventId(eventCustomer.EventId); if (account == null || !account.AttachGiftCard) { questions = questions.Where(q => !GiftCertificateQuestions.Contains(q.Id)); } foreach (var question in questions) { var model = new ExitInterviewQuestionAnswerEditModel { QuestionId = question.Id, Question = question.Question, Index = question.Index }; var answer = answers.FirstOrDefault(x => x.QuestionId == question.Id); if (answer != null && !string.IsNullOrWhiteSpace(answer.Answer)) { model.Answer = answer.Answer.ToLower() == Boolean.TrueString.ToLower(); } list.Add(model); } return(list); }
public string SetCustomerTag(Customer customer, long eventId, long orgRoleId, DateTime eventDate) { //var customer = _customerRepository.GetCustomer(customerId); var previousTag = string.Empty; if (string.IsNullOrEmpty(customer.Tag)) { var account = _corporateAccountRepository.GetbyEventId(eventId); previousTag = customer.Tag; if (account != null) { customer.Tag = account.Tag; customer.ActivityId = (long)UploadActivityType.DoNotCallDoNotMail; if (!account.AllowCustomerPortalLogin) { customer.UserLogin.Locked = true; } else { customer.UserLogin.Locked = false; } _customerTargetedService.Save(customer.CustomerId, eventDate.Year, false, orgRoleId); } else { customer.UserLogin.Locked = false; } customer.DateModified = DateTime.Now; SaveCustomer(customer, orgRoleId); } return(previousTag); }
public void PollforResultNotification() { _logger.Info("Starting the Polling Agent for Result Notification."); var eventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsForResultReadyNotification((int)TestResultStateNumber.PostAudit, (int)NewTestResultStateNumber.PdfGenerated, false); if (eventCustomerResults != null && eventCustomerResults.Any()) { _logger.Info("Get the event customer result list."); eventCustomerResults = eventCustomerResults.Where(ec => ec.DataRecorderMetaData != null && ec.DataRecorderMetaData.DateModified != null && ec.DataRecorderMetaData.DateModified.Value < DateTime.Now.AddMinutes(-1 * _buffer)).ToArray(); bool sendNotification = Convert.ToBoolean(_configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.EnableResultDeliveryNotification)); foreach (var eventCustomerResult in eventCustomerResults) { try { //Check, if is unpaid. if yes, continue var isPaperCopyPurchased = false; var order = _orderRepository.GetOrderByEventCustomerId(eventCustomerResult.Id); if (order != null) { var orderDetail = order.OrderDetails.SingleOrDefault(od => (od.DetailType == OrderItemType.EventPackageItem || od.DetailType == OrderItemType.EventTestItem) && od.EventCustomerOrderDetail != null && od.EventCustomerOrderDetail.IsActive && od.IsCompleted); if (orderDetail != null) { var resultShippingDetails = _shippingDetailRepository.GetShippingDetailsForCancellation(orderDetail.Id); isPaperCopyPurchased = resultShippingDetails != null && resultShippingDetails.Count() > 0 ? true : false; //resultShippingDetails = resultShippingDetails.Where(sd => sd.Status == ShipmentStatus.Processing).Select(sd => sd).ToArray(); } if (order.DiscountedTotal > order.TotalAmountPaid) { _logger.Info("\n Customer [Id: " + eventCustomerResult.CustomerId + "] has not paid for event [Id:" + eventCustomerResult.EventId + "]"); continue; } } _logger.Info(string.Format("\n Customer Id [{0}] & Event Id [{1}] being taken to delivery state. ----------------------------", eventCustomerResult.CustomerId, eventCustomerResult.EventId)); var eventData = _eventRepository.GetById(eventCustomerResult.EventId); var isNewResultFlow = eventData.EventDate >= _settings.ResultFlowChangeDate; //if (isNewResultFlow) //{ // if (!eventCustomerResult.AcesApprovedOn.HasValue || eventCustomerResult.AcesApprovedOn.Value > DateTime.Now.Date) // continue; //} var customerEventScreeningTestIds = _testResultRepository.GetCustomerEventScreeningTestIds(eventCustomerResult.EventId, eventCustomerResult.CustomerId); var customerTests = _eventCustomerResultRepository.GetCustomerTests(eventCustomerResult.Id); using (var scope = new TransactionScope()) { if (isNewResultFlow) { _testResultRepository.SetResultstoState((int)NewTestResultStateNumber.ResultDelivered, false, eventCustomerResult.DataRecorderMetaData.DataRecorderModifier.Id, customerEventScreeningTestIds); } else { _testResultRepository.UpdateStateforCustomerNotification(eventCustomerResult.Id); } _eventCustomerResultRepository.SetEventCustomerResultState(eventCustomerResult.Id, customerTests); var account = _corporateAccountRepository.GetbyEventId(eventCustomerResult.EventId); if (account == null || (account.SendResultReadyMail && account.ResultReadyMailTemplateId > 0)) { if (sendNotification && eventData.NotifyResultReady) { string emailTemplateAlias = EmailTemplateAlias.ResultsReady; if (account != null && account.ResultReadyMailTemplateId > 0) { var emailTemplate = ((IUniqueItemRepository <EmailTemplate>)_emailTemplateRepository).GetById(account.ResultReadyMailTemplateId); emailTemplateAlias = emailTemplate.Alias; } var customer = _customerRepository.GetCustomer(eventCustomerResult.CustomerId); _logger.Info("\n Sending Notification at " + (customer.Email != null ? customer.Email.ToString() : "")); if (emailTemplateAlias == EmailTemplateAlias.ResultsReady) { var resultReadyViewModel = _emailNotificationModelsFactory.GetResultReadyModel(customer.Name.FullName, customer.UserLogin.UserName, isPaperCopyPurchased, eventCustomerResult.EventId); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ResultsReady, emailTemplateAlias, resultReadyViewModel, customer.Id, customer.CustomerId, "Result Notification"); } else { var primaryCarePhysician = _primaryCarePhysicianRepository.Get(customer.CustomerId); if (primaryCarePhysician == null) { _logger.Error(string.Format("No primary Care Physician found for Customer Id: {0} \n", customer.CustomerId)); continue; } var resultReadyViewModel = _emailNotificationModelsFactory.GetPpCustomerResultNotificationModel(customer, primaryCarePhysician); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ResultsReady, emailTemplateAlias, resultReadyViewModel, customer.Id, customer.CustomerId, "Result Notification"); } // Commented when implemented one way password hashing //if (customer.UserLogin != null && !customer.UserLogin.UserVerified && (account == null || account.SendWelcomeEmail)) //{ // var passwordNotificationModel = _emailNotificationModelsFactory.GetWelcomeWithPasswordNotificationModel(customer.Name.ToString(), customer.UserLogin.Password); // _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.CustomerWelcomeEmailWithPassword, EmailTemplateAlias.CustomerWelcomeEmailWithPassword, passwordNotificationModel, customer.Id, customer.CustomerId, "Result Notification"); //} } } scope.Complete(); } } catch (Exception ex) { _logger.Info( String.Format("\n System failure: For EventId:{0} and CustomerId:{1} \n Message{2}", eventCustomerResult.EventId, eventCustomerResult.CustomerId, ex.Message)); } } } else { _logger.Info("No event customer result found."); } }
public void PollforResultReadyNotification() { _logger.Info("Starting the Polling Agent for Second Result Ready Notification."); bool sendNotification = Convert.ToBoolean(_configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.EnableResultDeliveryNotification)); if (!sendNotification) { return; } var eventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsForResultReadyNotification(_setting.DaysAfterResultReady); if (eventCustomerResults != null && eventCustomerResults.Any()) { foreach (var eventCustomerResult in eventCustomerResults) { try { var isResultAccessed = _digitalAssetAccessLogRepository.IsDigitalAssetAccessed(eventCustomerResult.CustomerId, eventCustomerResult.DataRecorderMetaData.DateModified.Value); if (isResultAccessed) { continue; } var shippingDetails = _shippingDetailRepository.GetShippingDetailsForEventCustomer(eventCustomerResult.EventId, eventCustomerResult.CustomerId); bool isPaperCopyPurchased = shippingDetails != null && shippingDetails.Any(); if (isPaperCopyPurchased) { continue; } var account = _corporateAccountRepository.GetbyEventId(eventCustomerResult.EventId); if (account != null && !(account.SendResultReadyMail && account.ResultReadyMailTemplateId > 0)) { continue; } var eventData = _eventRepository.GetById(eventCustomerResult.EventId); if (eventData.NotifyResultReady) { string emailTemplateAlias = EmailTemplateAlias.ResultsReady; if (account != null && account.ResultReadyMailTemplateId > 0) { var emailTemplate = ((IUniqueItemRepository <EmailTemplate>)_emailTemplateRepository).GetById(account.ResultReadyMailTemplateId); emailTemplateAlias = emailTemplate.Alias; } var customer = _customerRepository.GetCustomer(eventCustomerResult.CustomerId); _logger.Info("\n Sending Notification at " + (customer.Email != null ? customer.Email.ToString() : "")); if (emailTemplateAlias == EmailTemplateAlias.ResultsReady) { var resultReadyViewModel = _emailNotificationModelsFactory.GetResultReadyModel(customer.Name.FullName, customer.UserLogin.UserName, isPaperCopyPurchased, eventCustomerResult.EventId); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ResultsReady, emailTemplateAlias, resultReadyViewModel, customer.Id, customer.CustomerId, "Result Notification"); } else { var primaryCarePhysician = _primaryCarePhysicianRepository.Get(customer.CustomerId); if (primaryCarePhysician == null) { _logger.Error(string.Format("No primary Care Physician found for Customer Id: {0} \n", customer.CustomerId)); continue; } var resultReadyViewModel = _emailNotificationModelsFactory.GetPpCustomerResultNotificationModel(customer, primaryCarePhysician); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ResultsReady, emailTemplateAlias, resultReadyViewModel, customer.Id, customer.CustomerId, "Result Notification"); } } } catch (Exception ex) { _logger.Info(String.Format("\n System failure: For EventId:{0} and CustomerId:{1} \n Message{2}", eventCustomerResult.EventId, eventCustomerResult.CustomerId, ex.Message)); } } } else { _logger.Info("No records found result found for Second Result Ready Notification."); } }
private bool IsImageUpsellEnabled(long eventId) { var account = _corporateAccountRepository.GetbyEventId(eventId); return(account == null || account.EnableImageUpsell); }
public MobileResponseModel Save(GiftCertificateSignatureModel model) { try { var GCReasionId = model.GcNotGivenReasonId != null ? model.GcNotGivenReasonId : 0; _logger.Info("Gift Card (Save) : EventCustomerId Id :" + model.EventCustomerId); _logger.Info("Gift Card (Save) : GcNotGivenReasonId :" + GCReasionId); _logger.Info("Gift Card (Save) : GiftCardReceived :" + model.GiftCardReceived); var eventCustomer = ((IUniqueItemRepository <EventCustomer>)_eventCustomerRepository).GetById(model.EventCustomerId); var eventId = eventCustomer != null ? eventCustomer.EventId : 0; CorporateAccount account = null; if (eventId > 0) { account = _corporateAccountRepository.GetbyEventId(eventId); } if (account != null) { _logger.Info("Account Tag : " + account.Tag + " AttachGiftCard : " + account.AttachGiftCard + " ShowGiftCertificateOnEod : " + account.ShowGiftCertificateOnEod); } if ((account != null && account.AttachGiftCard) && !model.GiftCardReceived && (model.GcNotGivenReasonId == null || (model.GcNotGivenReasonId != null && model.GcNotGivenReasonId == 0))) { return(new MobileResponseModel { IsSuccess = false, Message = "Unable to save the Gift Card because GC not given reason Id is null" }); } var isSuccess = _giftCardService.Save(model, _sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId); if (isSuccess) { return(new MobileResponseModel { IsSuccess = true, Message = "Gift Card saved successfully." }); } else { return(new MobileResponseModel { IsSuccess = false, Message = "Unable to save the Gift Card." }); } } catch (Exception ex) { _logger.Error("Error while saving Gift Card."); _logger.Error("Message : " + ex.Message); _logger.Error("Stack Trace : " + ex.StackTrace); return(new MobileResponseModel { IsSuccess = false, Message = string.Format("Error while saving Gift Card. Message : {0}", ex.Message) }); } }
public OnlineSchedulingCustomerInfoEditModel SavePaymentInfo(OnlineSchedulingCustomerInfoEditModel model) { OnlineSchedulingProcessAndCartViewModel cartModel = model.ProcessAndCartViewModel; SourceCodeApplyEditModel sourceCodeModel = model.SourceCodeApplyEditModel; PaymentEditModel paymentModel = model.PaymentEditModel; var onlineRequestValidationModel = _tempcartService.ValidateOnlineRequest(cartModel.CartGuid); model.RequestValidationModel = onlineRequestValidationModel; if (onlineRequestValidationModel.RequestStatus != OnlineRequestStatus.Valid) { return(model); } var tempCart = onlineRequestValidationModel.TempCart; if (tempCart.EventId.HasValue) { var summarymodel = _eventSchedulerService.GetEventCustomerOrderSummaryModel(tempCart); var couponAmount = sourceCodeModel != null ? sourceCodeModel.DiscountApplied : 0; if ((summarymodel.TotalPrice != null && summarymodel.TotalPrice.Value != (paymentModel.Amount + couponAmount)) || (summarymodel.TotalPrice == null && paymentModel.Amount > 0)) { throw new Exception("Seems like you changed your order. Please go back to the Package screen, and confirm!"); } var result = ValidatePaymentModel(paymentModel); if (!result) { throw new Exception("Payment error - Please re-enter your payment information or contact our customer care line at " + _settings.PhoneTollFree); } var isAppointmentTemporarilyBooked = _slotService.IsSlotTemporarilyBooked(tempCart.InChainAppointmentSlotIds); if (!isAppointmentTemporarilyBooked) { //throw new Exception("The appointment time selected by you is no longer temporarliy booked for you. Please go back to appointment page to choose the time slot"); model.PaymentEditModel.IsTemporaryBookedSlotExpired = true; return(model); } var isAppointmentBooked = _slotService.IsSlotBooked(tempCart.InChainAppointmentSlotIds); if (isAppointmentBooked) { throw new Exception("The appointment slot selected by you seems to have exhausted. Please re-select another slot!"); } } bool? paymentSucceded = null; Customer customer; try { using (var scope = new TransactionScope()) { customer = tempCart.CustomerId.HasValue ? _customerRepository.GetCustomer(tempCart.CustomerId.Value) : null; var address = Mapper.Map <AddressEditModel, Address>(paymentModel.ExistingShippingAddress); address = _addressService.SaveAfterSanitizing(address, true); if (customer == null) { throw new Exception("System Failure! Data not saved. Please try again."); } var customerAddress = Mapper.Map <AddressEditModel, Address>(paymentModel.ExistingShippingAddress); customerAddress = _addressService.SaveAfterSanitizing(customerAddress, true); customer.Address = customerAddress; customer.RequestForNewsLetter = model.RequestForNewsLetter; if (paymentModel.Payments != null && paymentModel.Payments.Where(p => p.PaymentType != PaymentType.Onsite_Value && p.PaymentType != PaymentType.GiftCertificate.PersistenceLayerId).Count() > 0) { if (paymentModel.ExistingBillingAddress != null) { if (customer.BillingAddress != null && customer.BillingAddress.Id > 0) { paymentModel.ExistingBillingAddress.Id = customer.BillingAddress.Id; } var billingAddress = Mapper.Map <AddressEditModel, Address>(paymentModel.ExistingBillingAddress); billingAddress = _addressService.SaveAfterSanitizing(billingAddress, true); customer.BillingAddress = billingAddress; } } else { var billingAddress = Mapper.Map <AddressEditModel, Address>(paymentModel.ExistingShippingAddress); billingAddress = _addressService.SaveAfterSanitizing(billingAddress, true); customer.BillingAddress = billingAddress; } _customerService.SaveCustomer(customer, customer.CustomerId); tempCart.SourceCodeId = sourceCodeModel == null || sourceCodeModel.SourceCodeId < 1 ? null : (long?)sourceCodeModel.SourceCodeId; tempCart.ShippingAddressId = address.Id; tempCart.ScreenResolution = cartModel.ScreenResolution; if (paymentModel.Payments != null) { tempCart.PaymentMode = ""; if (paymentModel.Payments.Any(p => p.ChargeCard != null)) { tempCart.PaymentMode += PaymentType.CreditCard.Name + ","; } if (paymentModel.Payments.Any(p => p.ECheck != null)) { tempCart.PaymentMode += PaymentType.ElectronicCheck.Name + ","; } if (paymentModel.Payments.Any(p => p.GiftCertificate != null)) { tempCart.PaymentMode += PaymentType.GiftCertificate.Name + ","; } if (paymentModel.Payments.Any(p => p.PaymentType == (int)PaymentType.Onsite_Value)) { tempCart.PaymentMode += PaymentType.PayLater_Text + ","; } tempCart.PaymentMode = tempCart.PaymentMode.Substring(0, tempCart.PaymentMode.LastIndexOf(",")); } tempCart.PaymentAmount = paymentModel.Amount; try { _eventSchedulerService.CreateOrder(tempCart, paymentModel); paymentSucceded = true; } catch (Exception ex) { _paymentController.VoidCreditCardGatewayRequests(paymentModel); paymentSucceded = false; throw new Exception("\nOnline Payment. Message: " + ex.Message + ". \n\t Stack Trace: " + ex.StackTrace); } tempCart.IsPaymentSuccessful = true; tempCart.IsCompleted = true; _tempcartService.SaveTempCart(tempCart); UpdateProspectCustomer(tempCart, customer); scope.Complete(); } try { var account = _corporateAccountRepository.GetbyEventId(tempCart.EventId.Value); if (account == null || account.SendWelcomeEmail) { var welcomeEmailViewModel = _emailNotificationModelsFactory.GetWelcomeWithUserNameNotificationModel(customer.UserLogin.UserName, customer.Name.FullName, customer.DateCreated); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.CustomerWelcomeEmailWithUsername, EmailTemplateAlias.CustomerWelcomeEmailWithUsername, welcomeEmailViewModel, customer.Id, customer.CustomerId, Request.RequestUri.OriginalString); } var eventData = _eventRepository.GetById(tempCart.EventId.Value); _customerRegistrationService.SendAppointmentConfirmationMail(customer, eventData, customer.CustomerId, Request.RequestUri.OriginalString, account); //If somebody registered within 24 hours of the event Date then send notification. if (eventData.EventDate.AddDays(-1).Date <= DateTime.Now.Date) { var appointmentBookedInTwentyFourHoursNotificationModel = _emailNotificationModelsFactory.GetAppointmentBookedInTwentyFourHoursModel(tempCart.EventId.Value, tempCart.CustomerId.Value); _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.AppointmentBookedInTwentyFourHours, EmailTemplateAlias.AppointmentBookedInTwentyFourHours, appointmentBookedInTwentyFourHoursNotificationModel, 0, customer.CustomerId, Request.RequestUri.OriginalString); } _callQueueCustomerRepository.UpdateOtherCustomerStatus(customer.CustomerId, tempCart.ProspectCustomerId.HasValue ? tempCart.ProspectCustomerId.Value : 0, CallQueueStatus.Completed, customer.CustomerId); _eventSchedulingSlotService.SendEventFillingNotification(tempCart.EventId.Value, customer.CustomerId); } catch (Exception) { //throw new Exception("\nOnline Payment. Exception caused while sending notification. Message: " + ex.Message); } } catch (InvalidAddressException ex) { throw new Exception("Address provided by you is not a valid address. " + ex.Message); } catch (Exception) { if (paymentSucceded != null && paymentSucceded == false) { tempCart.IsPaymentSuccessful = false; tempCart.IsCompleted = false; tempCart.PaymentMode = ""; tempCart.SourceCodeId = 0; tempCart.ShippingAddressId = null; _tempcartService.SaveTempCart(tempCart); throw new Exception("OOPS! Payment could not be settled. Please try again or Call our Care Agent at " + _settings.PhoneTollFree); } throw new Exception("OOPS! Some error while generating the Order. Please try again or Call our Care Agent at " + _settings.PhoneTollFree); } return(model); }
//[HttpPost] public JsonResult SendConfirmationSms(long eventId, long customerId) { var currentSession = _sessionContext.UserSession; var eventCustomer = _eventCustomerRepository.Get(eventId, customerId); var customer = _customerRepository.GetCustomer(customerId); var message = string.Empty; if (customer.IsSubscribed == null || customer.IsSubscribed.Value == false) { _logger.Info("customer has not Subscribed for SMS customerId " + customer.CustomerId); message = "customer has not Subscribed for SMS"; _logger.Info(message); return(Json(new { message }, JsonRequestBehavior.AllowGet)); } if (eventCustomer.EnableTexting) { var account = _corporateAccountRepository.GetbyEventId(eventId); if (account != null && !account.EnableSms) { message = "SMS has been disabled for Corporate Account Tag: " + account.Tag; _logger.Info(message); return(Json(new { message }, JsonRequestBehavior.AllowGet)); } var messageAlreadySentList = _eventCustomerNotificationRepository.GetAllByEventCustomerId(eventCustomer.Id, NotificationTypeAlias.AppointmentConfirmation); var messageCount = (messageAlreadySentList != null && messageAlreadySentList.Any()) ? messageAlreadySentList.Count() : 0; if (account != null && messageCount >= account.MaximumSms) { _logger.Info("Maximum SMS has Been Sent "); _logger.Info(string.Format("Allowed SMS {0}, SMS Already Sent {0} " + account.MaximumSms, messageCount)); message = "Maximum SMS limit has been reached."; return(Json(new { message }, JsonRequestBehavior.AllowGet)); } if (account == null && messageCount > 0) { message = "Appointment confirmation SMS has already been sent."; _logger.Info(message); return(Json(new { message }, JsonRequestBehavior.AllowGet)); } var eventData = _eventRepository.GetById(eventId); var smsNotificaionModel = _phoneNotificationModelsFactory.GetScreeningReminderSmsNotificationModel(customer, eventData); var smsTemplateAlias = EmailTemplateAlias.AppointmentConfirmation; if (account != null && account.ConfirmationSmsTemplateId.HasValue && account.ConfirmationSmsTemplateId.Value > 0) { var smsTemplate = _emailTemplateRepository.GetById(account.ConfirmationSmsTemplateId.Value); smsTemplateAlias = smsTemplate.Alias; } var notification = _notifier.NotifyViaSms(NotificationTypeAlias.AppointmentConfirmation, smsTemplateAlias, smsNotificaionModel, customer.Id, currentSession.CurrentOrganizationRole.OrganizationRoleUserId, Request.Url.AbsolutePath); if (notification != null) { var eventCustomerNotification = new EventCustomerNotification { EventCustomerId = eventCustomer.Id, NotificationId = notification.Id, NotificationTypeId = notification.NotificationType.Id }; _eventCustomerNotificationRepository.Save(eventCustomerNotification); } else { message = "Queuing is disabled for Appointment Confirmation SMS."; _logger.Info(message); return(Json(new { message }, JsonRequestBehavior.AllowGet)); } } else { message = "Customer has not opted for SMS"; _logger.Info(message); return(Json(new { message }, JsonRequestBehavior.AllowGet)); } message = "Message Sent Successfully"; return(Json(new { message }, JsonRequestBehavior.AllowGet)); }
public OnlineCustomerPersonalInformationEditModel GetCustomerInfo(string guid) { var onlineRequestValidationModel = _tempcartService.ValidateOnlineRequest(guid); var model = new OnlineCustomerPersonalInformationEditModel { RequestValidationModel = onlineRequestValidationModel }; if (onlineRequestValidationModel.RequestStatus != OnlineRequestStatus.Valid) { return(model); } var shippingAddress = new AddressEditModel() { StreetAddressLine1 = OnlineAddress1, City = _onlineCity, StateId = _onlineStateId, CountryId = _onlineCountryId, ZipCode = _onlineZip }; model.CustomerEditModel = new SchedulingCustomerEditModel { EnableTexting = _enableTexting, EnableVoiceMail = _enableVoiceMail, ShippingAddress = shippingAddress }; var tempCart = onlineRequestValidationModel.TempCart; var customer = tempCart.CustomerId.HasValue ? _customerRepository.GetCustomer(tempCart.CustomerId.Value) : null; if (customer == null && tempCart.ProspectCustomerId.HasValue && tempCart.ProspectCustomerId.Value > 0) { model.CustomerEditModel = _prospectCustomerService.GetforProspectCustomerId(tempCart.ProspectCustomerId.Value); if (model.CustomerEditModel.ShippingAddress.StreetAddressLine1 == OnlineAddress1) { model.CustomerEditModel.ShippingAddress = shippingAddress; } } else if (customer != null) { model.CustomerEditModel = Mapper.Map <Customer, SchedulingCustomerEditModel>(customer); model.CustomerEditModel.ShippingAddress = Mapper.Map <Address, AddressEditModel>(customer.Address); model.CustomerEditModel.ConfirmationToEnablTexting = customer.EnableTexting; model.CustomerEditModel.ConfirmationToEnableVoiceMail = customer.EnableVoiceMail; } model.CustomerEditModel.EnableTexting = _enableTexting; model.CustomerEditModel.EnableVoiceMail = _enableVoiceMail; model.CustomerEditModel.MarketingSource = tempCart.MarketingSource; if (tempCart.Dob.HasValue && !model.CustomerEditModel.DateofBirth.HasValue) { model.CustomerEditModel.DateofBirth = tempCart.Dob.Value; } if (!string.IsNullOrEmpty(tempCart.Gender) && !(model.CustomerEditModel.Gender.HasValue && model.CustomerEditModel.Gender.Value > 0)) { model.CustomerEditModel.Gender = (int)((Gender)System.Enum.Parse(typeof(Gender), tempCart.Gender, true)); } if (tempCart.EventId.HasValue && tempCart.EventId.Value > 0) { var eventData = _eventRepository.GetById(tempCart.EventId.Value); if (eventData.AccountId.HasValue && eventData.AccountId.Value > 0) { var account = _corporateAccountRepository.GetbyEventId(tempCart.EventId.Value); model.CustomerEditModel.InsuranceIdLabel = (account != null && !string.IsNullOrEmpty(account.MemberIdLabel)) ? account.MemberIdLabel : string.Empty; } model.CustomerEditModel.InsuranceIdRequired = eventData.InsuranceIdRequired; var eventHospitalPartner = _hospitalPartnerRepository.GetEventHospitalPartnersByEventId(tempCart.EventId.Value); if (eventHospitalPartner != null) { model.CustomerEditModel.CaptureSsn = eventHospitalPartner.CaptureSsn; } } //model.ShippingOptions = _onlineShippingService.GetShippingOption(tempCart); return(model); }
private bool AddMissingTestToEvent(long eventId, IEnumerable <long> testIds, IEnumerable <EventTest> eventtests) { var existingtestIds = eventtests.Select(x => x.TestId).ToList(); var toBeAddedTests = testIds.Where(testId => !existingtestIds.Contains(testId)).ToList(); if (toBeAddedTests.Any()) { var missingTest = _testRepository.GetTestByIds(toBeAddedTests); var account = _corporateAccountRepository.GetbyEventId(eventId); var testNotReviewableIds = new List <long>(); if (account != null) { var testNotReviewable = _accountNotReviewableTestRepository.GetByAccountId(account.Id); if (!testNotReviewable.IsNullOrEmpty()) { testNotReviewableIds.AddRange(testNotReviewable.Select(x => x.TestId)); } } foreach (var test in missingTest) { var isTestNotReviewable = testNotReviewableIds.Any(x => x == test.Id); _eventTestRepository.Save(new EventTest { TestId = test.Id, EventId = eventId, WithPackagePrice = 0, Price = 0, RefundPrice = 0, ReimbursementRate = 0, ShowInAlaCarte = true, Gender = (long)Gender.Unspecified, GroupId = (long)TestGroupType.None, DateCreated = DateTime.Now, DateModified = DateTime.Now, IsTestReviewableByPhysician = isTestNotReviewable ? (bool?)true : null }); } var theEvent = _eventRepository.GetById(eventId); if (theEvent.IsDynamicScheduling) { var podRoomTests = _eventPodRoomRepository.GetEventPodRoomTestsByEventId(eventId); var eventPodRooms = podRoomTests.Select(x => x.EventPodRoomId).Distinct(); foreach (var eventPodRoom in eventPodRooms) { var testAlreadInRoom = podRoomTests.Where(x => x.EventPodRoomId == eventPodRoom).Select(x => x.TestId); if (!testAlreadInRoom.IsNullOrEmpty()) { toBeAddedTests.AddRange(testAlreadInRoom); } toBeAddedTests = toBeAddedTests.Distinct().ToList(); _eventPodRoomRepository.SaveEventPodRoomTests(toBeAddedTests, eventPodRoom); } } return(true); } return(false); }
public void PollforSurveyEmails() { var filter = new EventBasicInfoViewModelFilter { DateFrom = DateTime.Now.Date.AddDays(-1), DateTo = DateTime.Now.Date.AddDays(-1) }; int totalRecords; var events = _eventRepository.GetEventsbyFilters(filter, 1, 100, out totalRecords); // Assuming there will be no mre than 100 events in one single day _logger.Info("\n\n"); _logger.Info("---------------------------- Survey Emails -------------------------------------"); if (events == null || !events.Any()) { _logger.Info("No Events found!"); return; } try { foreach (var @event in events) { if (@event.Status != EventStatus.Active) { continue; //|| @event.AccountId.HasValue } var account = _corporateAccountRepository.GetbyEventId(@event.Id); if (account != null && !(account.SendSurveyMail && account.SurveyMailTemplateId > 0)) { continue; } _logger.Info(string.Format("Starting for {0} dated {1}", @event.Name, @event.EventDate.ToShortDateString())); var pods = _podRepository.GetPodsForEvent(@event.Id); var eventCustomers = _eventCustomerRepository.GetbyEventId(@event.Id); eventCustomers = eventCustomers.Where(ec => ec.AppointmentId.HasValue && !ec.NoShow && !ec.LeftWithoutScreeningReasonId.HasValue).ToArray(); var customerIds = eventCustomers.Select(ec => ec.CustomerId).Distinct().ToArray(); var customers = _customerRepository.GetCustomers(customerIds); string emailTemplateAlias = EmailTemplateAlias.SurveyEmailNotification; if (account != null && account.SurveyMailTemplateId > 0) { var emailTemplate = ((IUniqueItemRepository <EmailTemplate>)_emailTemplateRepository).GetById(account.SurveyMailTemplateId); emailTemplateAlias = emailTemplate.Alias; } foreach (var customer in customers) { if ((customer.DoNotContactTypeId.HasValue && (customer.DoNotContactTypeId.Value == (long)DoNotContactType.DoNotContact || customer.DoNotContactTypeId.Value == (long)DoNotContactType.DoNotMail)) || !customer.EnableEmail) //(customer.DoNotContactReasonId.HasValue && customer.DoNotContactReasonId.Value > 0) { continue; } if (customer.Email == null) { _logger.Info(string.Format("{0} has no Email!", customer.NameAsString)); continue; } ServiceNotification(customer, @event, pods, emailTemplateAlias); } } } catch (Exception ex) { _logger.Error(string.Format("Message:{0} \nStackTrace: {1}", ex.Message, ex.StackTrace)); } }
public void GenerateHafAssessment(long eventId) { try { var eventLogger = _logManager.GetLogger("HealthAssessmentFormGenerator_" + eventId); eventLogger.Info("Generating HAF for Event Id: " + eventId); _pdfGenerator.PaperSize = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PaperSize); try { var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId); if (eventCustomers != null && eventCustomers.Any()) { eventCustomers = eventCustomers.Where(ec => ec.AppointmentId.HasValue).ToArray(); if (eventCustomers != null && eventCustomers.Any()) { eventLogger.Info("found EventCustomers Count: " + eventCustomers.Count()); var mediaLocation = _mediaRepository.GetMedicalHistoryMediaLocation(eventId); DirectoryOperationsHelper.CreateDirectoryIfNotExist(mediaLocation.PhysicalPath); DirectoryOperationsHelper.DeleteFiles(mediaLocation.PhysicalPath); var eventData = _eventRepository.GetById(eventId); var account = _corporateAccountRepository.GetbyEventId(eventId); var corporateSurveyPdf = ""; if (account != null && account.CaptureSurvey) { if (account.SurveyPdfFileId > 0) { var surveyPdf = _fileRepository.GetById(account.SurveyPdfFileId); if (surveyPdf != null) { corporateSurveyPdf = _mediaRepository.GetCorporateSurveyPdfFolderLocation().PhysicalPath + surveyPdf.Path; } } } var corporateCheckListPdf = ""; if (account != null && account.PrintCheckList && account.CheckListFileId > 0 && eventData.EventDate >= _settings.ChecklistChangeDate) { var checkListFilePdf = _fileRepository.GetById(account.CheckListFileId); if (checkListFilePdf != null) { corporateCheckListPdf = _mediaRepository.GetCorporateCheckListPdfFolderLocation().PhysicalPath + checkListFilePdf.Path; } } var filesFocAttestation = new[] { "" }; var mediaLocFocAttestation = _mediaRepository.GetUnlockEventsParseLocation(eventId); if (account != null && account.Id == _settings.HcpNvAccountId) { if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath)) { filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.*"); filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray(); } } else { if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath)) { filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.pdf"); filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray(); } } var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation(); var customers = _customerRepository.GetCustomers(eventCustomers.Select(ec => ec.CustomerId).ToArray()); int index = 0; foreach (var eventCustomer in eventCustomers) { eventLogger.Info(string.Format("Generating HAF for Event Id: {0} and Customer Id : {1} ", eventId, eventCustomer.CustomerId)); string url = _settings.HealthAssessmentFormUrl + string.Format("?eventId={0}&customerId={1}&LoadLayout=false&showKynEditModel=true&bulkPrint=true&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid()); var customer = customers.First(c => c.CustomerId == eventCustomer.CustomerId); var focAttestationFile = string.Empty; if (account != null) { var questFile = Path.Combine(_mediaRepository.GetQuestUploadMediaFileLocation().PhysicalPath, account.Tag + "_Quest.pdf"); if (account.Id == _settings.WellmedAccountId || account.Id == _settings.WellmedTxAccountId) { var memberId = string.IsNullOrEmpty(customer.InsuranceId) ? "" : customer.InsuranceId.ToLower().Trim(); focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == memberId); eventLogger.Info(string.Format("focAttestationFile : {0}", focAttestationFile)); var _files = new List <string>(); if (!string.IsNullOrEmpty(focAttestationFile) && DirectoryOperationsHelper.IsFileExist(focAttestationFile)) { eventLogger.Info(string.Format("focAttestationFile : First if {0}", focAttestationFile)); _files.Add(focAttestationFile); } if (DirectoryOperationsHelper.IsFileExist(questFile)) { eventLogger.Info(string.Format("focAttestationFile : 2nd if {0}", questFile)); _files.Add(questFile); } if (!_files.IsNullOrEmpty()) { if (_files.Count() > 1) { eventLogger.Info(string.Format("focAttestationFile : File Count {0}", _files.Count())); focAttestationFile = GetFocAttestationFileMerge(_files, focAttestationFile, eventLogger); } else { eventLogger.Info(string.Format("focAttestationFile : File[0] {0}", _files[0])); focAttestationFile = _files[0]; eventLogger.Info(string.Format("focAttestationFile : Last {0}", focAttestationFile)); } } } else { focAttestationFile = GetFocAttestationFileForMht(filesFocAttestation, customer.CustomerId.ToString(), eventLogger); } //else if (account.Id == _settings.MolinaAccountId) //{ // var hicn = string.IsNullOrEmpty(customer.Hicn) ? "" : customer.Hicn.ToLower().Trim(); // focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == hicn); //} //else if (account.Id == _settings.HcpNvAccountId) //{ //} //else if (_settings.MonarchAccountIds.Contains(account.Id)) //{ // var gmpi = string.IsNullOrEmpty(customer.AdditionalField4) ? "" : customer.AdditionalField4.ToLower().Trim(); // if (!string.IsNullOrEmpty(gmpi)) // { // focAttestationFile = GetFocAttestationFile(filesFocAttestation, "_" + gmpi.ToLower(), focAttestationFile, eventLogger); // } //} //else if (account.Id == _settings.AppleCareAccountId) //{ // focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger); //} //else if (account.Id == _settings.NammAccountId) //{ // focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger); //} } var focAttestationFilePath = string.Empty; eventLogger.Info("focAttestationFile: " + focAttestationFile); if (!string.IsNullOrEmpty(focAttestationFile)) { focAttestationFilePath = focAttestationFile; } var annualComprehensiveExamPdf = string.Empty; var memberInformationProfilePdf = string.Empty; if (!string.IsNullOrEmpty(customer.Hicn)) { var fileNamePattern = customer.Hicn + (customer.Name != null ? "_" + customer.Name.LastName + "_" + customer.Name.FirstName : ""); if (account != null && account.PrintAceForm) { try { var mediaLocationForAce = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "ACE"); var aceFiles = DirectoryOperationsHelper.GetFiles(mediaLocationForAce.PhysicalPath, fileNamePattern + "*_ACE.pdf"); if (aceFiles.Any()) { annualComprehensiveExamPdf = _pdfGenerator.ExtractPdfPagesFromEnd(aceFiles.First(), tempMediaLocation.PhysicalPath + "Ripped_" + customer.Hicn + "_ACE.pdf", NumberOfPagesToExtractFromAcePdf); } } catch (Exception ex) { eventLogger.Error(string.Format("Unable to attach ACE form to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message)); } } if (account != null && account.PrintMipForm) { try { var mediaLocationForMip = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "MIP"); var mipFiles = DirectoryOperationsHelper.GetFiles(mediaLocationForMip.PhysicalPath, fileNamePattern + "*_MIP.pdf"); if (mipFiles.Any()) { memberInformationProfilePdf = mipFiles.First(); } } catch (Exception ex) { eventLogger.Error(string.Format("Unable to attach MIP to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message)); } } } var consentHeaderWithChecklistpdf = string.Empty; if (!string.IsNullOrWhiteSpace(corporateCheckListPdf) && DirectoryOperationsHelper.IsFileExist(corporateCheckListPdf)) { var tempPath = _mediaRepository.GetTempMediaFileLocation(); var consentHeader = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf"); string consentHeaderUrl = _settings.ConsentHeaderFormUrl + string.Format("?eventId={0}&customerId={1}&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid()); _pdfGenerator.GeneratePdf(consentHeaderUrl, consentHeader); consentHeaderWithChecklistpdf = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf"); var consentHeaderWithChecklistpdfArray = new string[] { consentHeader, corporateCheckListPdf }; _pdfGenerator.Merge(consentHeaderWithChecklistpdf, consentHeaderWithChecklistpdfArray); } _pdfGenerator.GeneratePdfForHaf(url, mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf", corporateSurveyPdf, "", focAttestationFilePath, consentHeaderWithChecklistpdf, annualComprehensiveExamPdf, memberInformationProfilePdf); } eventLogger.Info("Merging HAF for Event Id: " + eventId); _pdfGenerator.GetPdffilesfromLocationandMergeintoOne(mediaLocation.PhysicalPath, mediaLocation.PhysicalPath + "Event_" + eventId + ".pdf"); _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed); index = 0; foreach (var eventCustomer in eventCustomers) { DirectoryOperationsHelper.Delete(mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf"); } } else { eventLogger.Info("No customer found with appointment attached with this event. Merging HAF for Event Id: " + eventId); _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed); } } else { eventLogger.Info("No customer found attached with this event. Merging HAF for Event Id: " + eventId); _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed); } } catch (Exception ex) { _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending); eventLogger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace); } } catch (Exception ex) { _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending); _logger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace); } }
public void GenerateJsonforEventCustomers(Event eventData, ILogger logger) { int totalrecords; logger.Info("Getting event customers......"); var eventCusomters = _eventCustomerRepository.GetMyBioCheckEventCustomers(1, 400, new MyBioCheckCustomerModelFilter { EventId = eventData.Id }, out totalrecords); if (eventCusomters == null || !eventCusomters.Any()) { logger.Info(string.Format("No event customers found for Event Id {0} EventDate {1}", eventData.Id, eventData.EventDate)); return; } logger.Info(string.Format("{0} event customers found.", eventCusomters.Count())); var eventCustomerIds = eventCusomters.Select(x => x.Id).ToArray(); var customerIds = eventCusomters.Select(x => x.CustomerId).ToArray(); var customers = _customerRepository.GetCustomers(customerIds); var healthAssessmentAnswer = _healthAssessmentRepository.GetCustomerHealthInfoByEventCustomerIds(eventCustomerIds); var account = _corporateAccountRepository.GetbyEventId(eventData.Id); Organization organization = null; if (account != null) { organization = _organizationRepository.GetOrganizationbyId(account.Id); account.Name = organization.Name; } DirectoryOperationsHelper.CreateDirectoryIfNotExist(_bioCheckAssessmentFailedListPath); var fileName = Path.Combine(_bioCheckAssessmentFailedListPath, string.Format("failedCustomerRecord_{0}.xml", DateTime.Now.Ticks)); var failedCustomerList = new BioCheckAssessmentFailedList { EventCustomers = new List <BioCheckAssessmentFailed>() }; var eventCustomerResultTrales = _eventCustomerResultTraleRepository.GetByEventCustomerResultIds(eventCustomerIds); var customerTrales = _customerTraleRepository.GetByCustomerIds(customerIds); eventCustomerResultTrales = eventCustomerResultTrales.IsNullOrEmpty() ? new List <EventCustomerResultTrale>() : eventCustomerResultTrales.ToList(); customerTrales = customerTrales.IsNullOrEmpty() ? new List <CustomerTrale>() : customerTrales; foreach (var ec in eventCusomters) { try { var customer = customers.Single(c => c.CustomerId == ec.CustomerId); var hafAnswer = healthAssessmentAnswer.Where(c => c.EventCustomerId == ec.Id); logger.Info("Started For EventId: " + ec.EventId + " customerId: " + ec.CustomerId); var bioCheckJsonViewModel = GenerateBioCheckResponseModel(ec, customer, hafAnswer, eventData, logger, eventCustomerResultTrales, customerTrales, account); if (bioCheckJsonViewModel != null) { bioCheckJsonViewModel.ProfileId = _profileId; logger.Info("Saving Request JSON For eventId: " + ec.EventId + " customerId: " + ec.CustomerId); SaveRequestJson(bioCheckJsonViewModel, ec.EventId, ec.CustomerId); logger.Info("Submitting Post Request For eventId: " + ec.EventId + " customerId: " + ec.CustomerId); var response = _trailApiService.Post <BioCheckJsonViewModel>(bioCheckJsonViewModel); var isNewResultFlow = eventData.EventDate >= _settings.ResultFlowChangeDate; if (response != null) { logger.Info("Saving response For EventId: " + ec.EventId + " customerId: " + ec.CustomerId); SaveReports(response, ec.EventId, ec.CustomerId, logger, isNewResultFlow); } else { logger.Info("No Response found for EventId: " + ec.EventId + " customerId: " + ec.CustomerId); } } logger.Info("Complete For EventId: " + ec.EventId + " customerId: " + ec.CustomerId); } catch (Exception exception) { failedCustomerList.EventCustomers.Add(new BioCheckAssessmentFailed { CustomerId = ec.CustomerId, EventId = ec.EventId }); logger.Error(string.Format("Error while generating My Bio-Check Assessment Data for customer Id: {0} and EventId {1} Message: {2}, StackTrace {3}", ec.CustomerId, ec.EventId, exception.Message, exception.StackTrace)); } } if (!failedCustomerList.EventCustomers.IsNullOrEmpty()) { _bioCheckAssessmentFailedListXmlSerializer.SerializeandSave(fileName, failedCustomerList); } }
public IEnumerable <EventCustomerScreeningAggregate> Parse() { var eventCustomerAggregates = new List <EventCustomerScreeningAggregate>(); var mediaLocation = _mediaRepository.GetEawvHraResultMediaLocation(); var mediaArchiveLocation = _mediaRepository.GetEawvHraResultArchiveMediaLocation(); try { var xmlFilePaths = Directory.GetFiles(mediaLocation.PhysicalPath, "*.xml"); foreach (var xmlfile in xmlFilePaths) { _logger.Info("reading xml File: " + xmlfile); HraResultTags eawvHraResult = null; try { eawvHraResult = _eawvHraSerializer.Deserialize(xmlfile); } catch (Exception ex) { _logger.Error("Some error occurred while reading xml. Message: " + ex.Message); _logger.Error("Stack Trace: " + ex.StackTrace); File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile))); } if (eawvHraResult == null) { _logger.Info("Some error occurred while reading xml."); File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile))); } if (eawvHraResult.Events.IsNullOrEmpty()) { _logger.Info("No Event Data found for Tag: " + eawvHraResult.Name); File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile))); continue; } var eventid = eawvHraResult.Events.First().EventId; var account = _corporateAccountRepository.GetbyEventId(eventid); if (account == null) { _logger.Info("No Corporate Account For Event Id: " + eventid); File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile))); continue; } _logger.Info("Running for corporate Account " + account.Tag); var theEvent = _eventRepository.GetById(eventid); QuestionnaireType questionnaireType = QuestionnaireType.None; if (account != null && account.IsHealthPlan && theEvent != null) { questionnaireType = _accountHraChatQuestionnaireHistoryServices.QuestionnaireTypeByAccountIdandEventDate(account.Id, theEvent.EventDate); } if (questionnaireType != QuestionnaireType.HraQuestionnaire) { _logger.Info("HRA Questionnaire is not started"); continue; } var eawvTestNotPurchsed = new HraResultTags { Name = eawvHraResult.Name, Events = new List <HraResultEvent>() }; foreach (var hraResultEvent in eawvHraResult.Events) { var eventCustomers = _eventCustomerRepository.GetbyEventId(hraResultEvent.EventId); if (eventCustomers.IsNullOrEmpty()) { _logger.Info("No Event Cusotmer found"); continue; } var customeridNotToParse = eventCustomers.Where(x => x.NoShow || x.LeftWithoutScreeningReasonId.HasValue).Select(x => x.CustomerId); var snapshotFolderPath = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderSnapshot); var preventionFolderPlan = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderPreventionPlan); var resultReportFolderPath = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderResultReport); var snapShotCustomerIds = (hraResultEvent.Snapshot != null && !hraResultEvent.Snapshot.CustomerId.IsNullOrEmpty()) ? hraResultEvent.Snapshot.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>(); var preventionPlanCustomerIds = (hraResultEvent.PreventionPlan != null && !hraResultEvent.PreventionPlan.CustomerId.IsNullOrEmpty()) ? hraResultEvent.PreventionPlan.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>(); var resultReportCustomerIds = (hraResultEvent.ResultReport != null && !hraResultEvent.ResultReport.CustomerId.IsNullOrEmpty()) ? hraResultEvent.ResultReport.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>(); _logger.Info(string.Format("============================Reading Snapshot for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId)); _logger.Info(string.Format("snapshot folder Path: {0}", snapshotFolderPath)); var customerTestNotPurchased = new List <long>(); if (Directory.Exists(snapshotFolderPath)) { _logger.Info("Count: " + snapShotCustomerIds.Count()); foreach (var customerId in snapShotCustomerIds) { var snapShotFilePath = Path.Combine(snapshotFolderPath, customerId + ".pdf"); if (!File.Exists(snapShotFilePath)) { _logger.Info("SnapShot File does not exist at following location: " + snapShotFilePath); continue; } _logger.Info("SnapShot File exists at location: " + snapShotFilePath); var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV); if (!isEAwvTestPurchasedByCustomer) { customerTestNotPurchased.Add(customerId); _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n"); continue; } try { var mediaFiles = new List <ResultMedia>(); string folderToSavePdf = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath; _logger.Info("Get Snapshot Media"); var snapShotResultMedia = GetMediaFromPdfFile(snapShotFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.SnapShot); if (snapShotResultMedia != null) { _logger.Info("Inside SpanShot Result Media"); snapShotResultMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(snapShotResultMedia); if (preventionPlanCustomerIds.Any(c => c == customerId)) { var preventionPlanFile = Path.Combine(preventionFolderPlan, customerId + ".pdf"); if (File.Exists(preventionPlanFile)) { var preventionPlanMedia = GetMediaFromPdfFile(preventionPlanFile, folderToSavePdf, TestType.eAWV, AwvFileTypes.PreventionPlan); if (preventionFolderPlan != null) { preventionPlanMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(preventionPlanMedia); preventionPlanCustomerIds = preventionPlanCustomerIds.Where(c => c != customerId).ToList(); } } else { _logger.Info( "Prevention Plan File does not exist at following location: " + preventionPlanFile); } } if (resultReportCustomerIds.Any(c => c == customerId)) { var resultReportFile = Path.Combine(resultReportFolderPath, customerId + ".pdf"); if (File.Exists(resultReportFile)) { var resultExportMedia = GetMediaFromPdfFile(resultReportFile, folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport); if (resultExportMedia != null) { resultExportMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(resultExportMedia); resultReportCustomerIds = resultReportCustomerIds.Where(c => c != customerId).ToList(); } } else { _logger.Info( "Result Report File does not exist at following location: " + resultReportFile); } } var testResult = new EAwvTestResult { ResultImages = mediaFiles }; _logger.Info("Inside SnapShot for adding Customer Aggregate"); _resultParserHelper.AddTestResulttoEventCustomerAggregate( eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult); _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } else { _logger.Info("SpanShot Result Media Not Found"); } } catch (Exception ex) { _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace); _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } } } else { _logger.Info("Snapshot Directory does not exit for EventId " + hraResultEvent.EventId); _logger.Info("Snapshot Directory Path " + hraResultEvent.EventId); } _logger.Info(string.Format("============================Reading Prevention Plan for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId)); _logger.Info(string.Format("Prevention Plan folder Path: {0}", preventionFolderPlan)); if (Directory.Exists(preventionFolderPlan)) { foreach (var customerId in preventionPlanCustomerIds) { var preventionFilePath = Path.Combine(preventionFolderPlan, customerId + ".pdf"); if (!File.Exists(preventionFilePath)) { _logger.Info("Prevention Plan File does not exist at following location: " + preventionFilePath); continue; } var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV); if (!isEAwvTestPurchasedByCustomer) { customerTestNotPurchased.Add(customerId); _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n"); continue; } try { var mediaFiles = new List <ResultMedia>(); string folderToSavePdf = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath; var preventionPlanResultMedia = GetMediaFromPdfFile(preventionFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.PreventionPlan); if (preventionPlanResultMedia != null) { preventionPlanResultMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(preventionPlanResultMedia); if (resultReportCustomerIds.Any(c => c == customerId)) { var resultReportFile = Path.Combine(resultReportFolderPath, customerId + ".pdf"); if (File.Exists(resultReportFile)) { var resultExportaMedia = GetMediaFromPdfFile(resultReportFile, folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport); if (resultExportaMedia != null) { resultExportaMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(resultExportaMedia); resultReportCustomerIds = resultReportCustomerIds.Where(c => c != customerId).ToList(); } } else { _logger.Info("Result Report File does not exist at following location: " + resultReportFile); } } var testResult = new EAwvTestResult { ResultImages = mediaFiles }; _logger.Info("Inside PreventionPLan for adding Customer Aggregate"); _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult); _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } } catch (Exception ex) { _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace); _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } } } else { _logger.Info("Prevention Plan Directory does not exit for EventId " + hraResultEvent.EventId); _logger.Info("Prevention Plan Directory Path " + hraResultEvent.EventId); } _logger.Info(string.Format("============================Reading Result Report for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId)); _logger.Info(string.Format("Result Report folder Path: {0}", resultReportFolderPath)); if (Directory.Exists(resultReportFolderPath)) { foreach (var customerId in resultReportCustomerIds) { var resultReportFilePath = Path.Combine(resultReportFolderPath, customerId + ".pdf"); if (!File.Exists(resultReportFilePath)) { _logger.Info("Result Report File does not exist at following location: " + resultReportFilePath); continue; } var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV); if (!isEAwvTestPurchasedByCustomer) { customerTestNotPurchased.Add(customerId); _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n"); continue; } try { var mediaFiles = new List <ResultMedia>(); string folderToSavePdf = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath; var resultExportMedia = GetMediaFromPdfFile(resultReportFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport); if (resultExportMedia != null) { resultExportMedia.ReadingSource = ReadingSource.Automatic; mediaFiles.Add(resultExportMedia); var testResult = new EAwvTestResult { ResultImages = mediaFiles }; _logger.Info("Inside Result Report for adding Customer Aggregate"); _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult); _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } } catch (Exception ex) { _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace); _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA); } } } else { _logger.Info("Result Report Directory does not exit for EventId " + hraResultEvent.EventId); _logger.Info("Result Report Directory Path " + hraResultEvent.EventId); } if (!customerTestNotPurchased.IsNullOrEmpty()) { eawvTestNotPurchsed.Events.Add(new HraResultEvent { EventId = hraResultEvent.EventId, PreventionPlan = new HraResultPreventionPlan { CustomerId = customerTestNotPurchased.ToList() }, Snapshot = new HraResultSnapshot { CustomerId = customerTestNotPurchased.ToList() }, ResultReport = new HraResultReport() { CustomerId = customerTestNotPurchased.ToList() } }); } } if (!eawvTestNotPurchsed.Events.IsNullOrEmpty()) { _eawvHraSerializer.SerializeandSave(Path.Combine(mediaLocation.PhysicalPath, "customerNotPurchaseTest_" + DateTime.Now.ToFileTime() + ".xml"), eawvTestNotPurchsed); } try { var archiveFileName = Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile)); if (File.Exists(archiveFileName)) { File.Delete(archiveFileName); } File.Move(xmlfile, archiveFileName); } catch (Exception ex) { _logger.Error("Error while moving XML File in Archive folder"); _logger.Info(string.Format("Message: {0}", ex.Message)); _logger.Info(string.Format("stackTrace: {0}", ex.StackTrace)); } } } catch (Exception ex) { _logger.Error("Some Error occurred while parsing Eawv Result"); _logger.Error("Message: " + ex.Message); _logger.Error("Stack Trace: " + ex.StackTrace); } _logger.Info("EAWVParser eventCustomerAggregates count " + eventCustomerAggregates.Count); return(eventCustomerAggregates); }
public void PollforEventResultReadyNotification() { var notificationTypes = _notificationTypeRepository.GetAll(); var notificationIsActive = notificationTypes.Any(nt => (nt.NotificationTypeAlias == NotificationTypeAlias.EventResultReadyNotification) && nt.IsActive); if (!notificationIsActive) { return; } if (!_cutofDate.HasValue) { _logger.Info("Please provide cut of date to sent Corporate Event Result Ready Notification"); return; } var eventIds = _eventCustomerResultRepository.GetEventIdsForCorporateAccountEventResultReadyNotiFication(_cutofDate.Value).ToArray(); if (eventIds.Count() == 0) { _logger.Info("No Corporate Event found for sending Result Ready notification"); return; } var createdByOrgRoleUserId = _organizationRoleUserRepository.GetOrganizationRoleUserIdsForRole((long)Roles.FranchisorAdmin).First(); foreach (var eventId in eventIds) { try { var notificationSent = _eventNotificationRepository.GetByEventId(eventId, NotificationTypeAlias.EventResultReadyNotification); if (notificationSent != null && notificationSent.IsForCorporateAccount) { continue; } var account = _corporateAccountRepository.GetbyEventId(eventId); if (account != null && account.SendEventResultReadyNotification) { var orgRoleUsers = _organizationRoleUserRepository.GetOrganizationRoleUsersByOrganizationIdAndRoleId(account.Id, (long)Roles.CorporateAccountCoordinator); if (!orgRoleUsers.IsNullOrEmpty()) { var userIds = orgRoleUsers.Select(oru => oru.UserId).ToList(); var users = _userRepository.GetUsers(userIds); var eventHostViewData = _eventService.GetById(eventId); foreach (var user in users) { if (user.Email == null || string.IsNullOrEmpty(user.Email.ToString())) { continue; } var model = _emailNotificationModelsFactory.GetEventResultReadyNotificationViewModel(user, eventHostViewData); var notifications = _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.EventResultReadyNotification, EmailTemplateAlias.EventResultReadyNotification, model, new string[] { user.Email.ToString() }, user.Id, createdByOrgRoleUserId, "Event Result Ready Notification"); if (notifications != null && notifications.Any()) { var eventNotification = new EventNotification { EventId = eventId, NotificationId = notifications.First().Id, IsForCorporateAccount = true }; _eventNotificationRepository.SaveForCorporateAccount(eventNotification); } } } else { _logger.Info(string.Format("No coordinator Attached to Event For Account {0} is Off", account.Id)); } } else { _logger.Info(string.Format("Send Event Result Ready Notification For Account {0} is Off", account.Id)); } } catch (Exception ex) { _logger.Error(string.Format("Corporat Event Result Ready Notification Error For Event Id {0} \nMessage:{1} \nStackTrace: {2}", eventId, ex.Message, ex.StackTrace)); } } }