Esempio n. 1
0
        public PrimaryCarePhysicianEditModel GetPrimaryCarePhysicianEditModel(long customerId)
        {
            PrimaryCarePhysicianEditModel pcpEditModel = null;
            var pcp = _primaryCarePhysicianRepository.Get(customerId);

            if (pcp != null)
            {
                pcpEditModel                = Mapper.Map <PrimaryCarePhysician, PrimaryCarePhysicianEditModel>(pcp);
                pcpEditModel.Address        = Mapper.Map <Address, AddressEditModel>(pcp.Address);
                pcpEditModel.MailingAddress = pcp.MailingAddress != null?Mapper.Map <Address, AddressEditModel>(pcp.MailingAddress) : pcpEditModel.Address;

                if (pcpEditModel.IsPcpAddressVerified.HasValue)
                {
                    pcpEditModel.IsPcpAddressVerified = pcp.IsPcpAddressVerified;
                    pcpEditModel.PcpAddressVerifiedOn = pcp.PcpAddressVerifiedOn;
                    if (pcp.PcpAddressVerifiedBy.HasValue)
                    {
                        var orgRoleUser = _organizationRoleUserRepository.GetOrganizationRoleUser(pcp.PcpAddressVerifiedBy.Value);
                        if (orgRoleUser != null)
                        {
                            if (orgRoleUser.RoleId > 0)
                            {
                                var role = _roleRepository.GetByRoleId(orgRoleUser.RoleId);
                                if (role != null)
                                {
                                    pcpEditModel.PcpAddresVarifiedByRole = role.DisplayName;
                                }
                            }
                            if (orgRoleUser.UserId > 0)
                            {
                                var user = _userRepository.GetUser(orgRoleUser.UserId);
                                if (user != null)
                                {
                                    pcpEditModel.PcpAddresVarifiedByUserName = user.Name.ToString();
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                pcpEditModel = new PrimaryCarePhysicianEditModel {
                    Address = new AddressEditModel(), PhoneNumber = new PhoneNumber {
                        CountryCode = CountryCode.UnitedStatesAndCanada
                    }, MailingAddress = new AddressEditModel(), HasSameAddress = true
                };
            }

            pcpEditModel.HasSameAddress = IsMailingAddressSame(pcpEditModel);

            return(pcpEditModel);
        }
Esempio n. 2
0
        private void QueueNotificationToCustomerForResutlReady(NotificationPhone phoneNotification)
        {
            var eventCustomerNotification = _eventCustomerNotificationRepository.GetById(phoneNotification.Id);

            if (eventCustomerNotification == null)
            {
                _logger.Error(string.Format("No EventCustomer found for notification Id {0} \n", phoneNotification.Id));
                return;
            }

            var eventCustomer = _eventCustomerRepository.GetById(eventCustomerNotification.EventCustomerId);
            var eventData     = _eventRepository.GetById(eventCustomer.EventId);
            var customer      = _customerRepository.GetCustomer(eventCustomer.CustomerId);

            if (eventData.NotifyResultReady)
            {
                var primaryCarePhysician = _primaryCarePhysicianRepository.Get(customer.CustomerId);

                if (primaryCarePhysician == null)
                {
                    _logger.Error("No primary Care Physician found \n");
                }
                var resultReadyNotification = _emailNotificationModelsFactory.GetPpCustomerResultNotificationModel(customer, primaryCarePhysician);

                _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.PhysicianPartnersCustomerResultReady, EmailTemplateAlias.PhysicianPartnersCustomerResultReady, resultReadyNotification, customer.Id, customer.CustomerId, "EFax System");
            }
        }
Esempio n. 3
0
        public bool AddPcpProductShipping(long customerId, long eventId)
        {
            var pcp = _primaryCarePhysicianRepository.Get(customerId);

            if (pcp == null || pcp.Address == null)
            {
                return(false);
            }

            var shippingOption = _shippingOptionRepository.GetShippingOptionByProductId((long)Product.UltraSoundImages);

            if (shippingOption == null)
            {
                return(false);
            }

            var order = _orderRepository.GetOrder(customerId, eventId);

            //added As Admin User Role
            var organizationRoleUser = new OrganizationRoleUser {
                Id = customerId
            };

            AddProduct(customerId, order, organizationRoleUser);

            AddPcpShipping(order, shippingOption, pcp, organizationRoleUser);

            return(true);
        }
        public ActionResult EditHospitalPartnerCustomer(long eventId, long customerId)
        {
            var customerName = _organizationRoleUserRepository.GetNameIdPairofUsers(new[] { customerId }).First().SecondValue;

            var model = new HospitalPartnerCustomerEditModel {
                CustomerName = customerName, CustomerId = customerId, EventId = eventId
            };

            var pcp = _primaryCarePhysicianRepository.Get(customerId);

            if (pcp != null)
            {
                model.PrimaryCarePhysicianName = pcp.Name.FullName;
            }

            return(View(model));
        }
        public EventCustomerPcpAppointmentViewModel GetEventCustomerPcpAppointmentViewModel(long eventId, long customerId)
        {

            var account = _corporateAccountRepository.GetbyEventId(eventId);
            var customer = _customerRepository.GetCustomer(customerId);
            var theEventData = _eventRepository.GetById(eventId);
            var pcp = _primaryCarePhysicianRepository.Get(customerId);
            var eventCustomer = _eventCustomerRepository.Get(eventId, customerId);


            return GetEventCustomerPcpAppointmentViewModel(theEventData, customer, account, pcp, eventCustomer);
        }
Esempio n. 6
0
        public HealthAssessmentHeaderEditModel GetModel(long eventId, long customerId)
        {
            var eventData     = _eventRepository.GetById(eventId);
            var customer      = _customerRepository.GetCustomer(customerId);
            var eventCustomer = _eventCustomerRepository.Get(eventId, customerId);
            var pcp           = _primaryCarePhysicianRepository.Get(customerId);
            var physicianName = string.Empty;

            if (pcp != null && pcp.Name != null)
            {
                physicianName = pcp.Name.FullName;
            }

            var participationConsent = new ParticipationConsentModel();
            var participationConsentMediaLocation = _mediaRepository.GetParticipationConsentSignatureLocation(eventId, customerId);
            var participationConsentSignature     = _participationConsentSignatureRepository.GetByEventCustomerId(eventCustomer.Id);

            if (participationConsentSignature != null)
            {
                var signatureFileIds = new[] { participationConsentSignature.SignatureFileId, participationConsentSignature.InsuranceSignatureFileId };
                var signatureFiles   = _fileRepository.GetByIds(signatureFileIds);

                var participationSignatreFile = signatureFiles.First(x => x.Id == participationConsentSignature.SignatureFileId);
                participationConsent.SignatureImageUrl = participationConsentMediaLocation.Url + participationSignatreFile.Path;
                participationConsent.ConsentSignedDate = participationConsentSignature.ConsentSignedDate.ToString("MM/dd/yyyy");

                var insuranceSignatureFile = signatureFiles.First(x => x.Id == participationConsentSignature.InsuranceSignatureFileId);
                participationConsent.InsuranceSignatureImageUrl = participationConsentMediaLocation.Url + insuranceSignatureFile.Path;
                participationConsent.InsuranceConsentSignedDate = participationConsentSignature.InsuranceConsentSignedDate.ToString("MM/dd/yyyy");
            }

            return(new HealthAssessmentHeaderEditModel
            {
                CustomerId = customer.CustomerId,
                CustomerName = customer.Name,
                DateofBirth = customer.DateOfBirth,
                EventDate = eventData.EventDate,
                EventId = eventData.Id,
                PhysicianName = physicianName,
                ParticipationConsent = participationConsent
            });
        }
Esempio n. 7
0
        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.");
            }
        }
        private void UpdateCustomerPrimaryCarePhysician(CorporateCustomerEditModel model, OrganizationRoleUser createdByOrgRoleUser, Customer customer, IEnumerable <EventCustomer> eventCustomers)
        {
            if (!string.IsNullOrEmpty(model.PcpFirstName) || !string.IsNullOrEmpty(model.PcpLastName))
            {
                var pcp = _primaryCarePhysicianRepository.Get(customer.CustomerId);

                var ispcpUpdated = pcp != null && IsPcpUpdated(pcp, model);

                pcp = ispcpUpdated ? null : pcp;

                if (pcp == null)
                {
                    pcp = new PrimaryCarePhysician
                    {
                        CustomerId           = customer.CustomerId,
                        DataRecorderMetaData = new DataRecorderMetaData(createdByOrgRoleUser.Id, DateTime.Now, null)
                    };
                }
                else
                {
                    pcp.DataRecorderMetaData.DataRecorderModifier = new OrganizationRoleUser(createdByOrgRoleUser.Id);
                    pcp.DataRecorderMetaData.DateModified         = DateTime.Now;
                }

                pcp.IsPcpAddressVerified = null;
                pcp.PcpAddressVerifiedBy = null;
                pcp.PcpAddressVerifiedOn = null;
                pcp.Source = (long)CustomerPcpUpdateSource.CorporateUpload;

                pcp.Name    = new Name(model.PcpFirstName, "", model.PcpLastName);
                pcp.Fax     = PhoneNumber.Create(PhoneNumber.ToNumber(model.PcpFax), PhoneNumberType.Unknown);
                pcp.Primary = PhoneNumber.Create(PhoneNumber.ToNumber(model.PcpPhone), PhoneNumberType.Office);
                if (!string.IsNullOrEmpty(model.PcpEmail))
                {
                    pcp.Email = new Email(model.PcpEmail);
                }

                pcp.Npi = model.PcpNpi;
                pcp.PhysicianMasterId = null;

                SetPcpPracticeAddress(pcp, model);
                SetPcpMailingAddress(pcp, model);

                if (IsPcpAddressSame(pcp))
                {
                    pcp.MailingAddress = null;
                }

                pcp.IsActive = true;

                pcp = _primaryCarePhysicianRepository.Save(pcp);

                if (pcp != null)
                {
                    model.CustomerAddressId   = customer.Address != null ? customer.Address.Id : 0;
                    model.PCPAddressId        = pcp.Address != null ? pcp.Address.Id : 0;
                    model.PCPMailingAddressId = pcp.MailingAddress != null ? pcp.MailingAddress.Id : 0;
                }

                if (ispcpUpdated)
                {
                    foreach (var eventCustomer in eventCustomers)
                    {
                        _eventCustomerPrimaryCarePhysicianRepository.Save(new EventCustomerPrimaryCarePhysician
                        {
                            EventCustomerId        = eventCustomer.Id,
                            IsPcpAddressVerified   = false,
                            PcpAddressVerifiedBy   = createdByOrgRoleUser.Id,
                            PcpAddressVerifiedOn   = DateTime.Now,
                            PrimaryCarePhysicianId = pcp.Id
                        });
                    }
                }
            }
        }
        private void SetReusltPdfNameing(EventCustomerResult ecr, CorporateAccount corporateAccount, string destinationFolderPdfPath, string sourcePath, ResultPdfPostedXml resultPosted, List <long> newCustomersWithNoMrn)
        {
            var eventDirectoryPdf   = destinationFolderPdfPath + "\\" + ecr.EventId;
            var destinationFilename = ecr.CustomerId.ToString();
            var customer            = _customerRepository.GetCustomer(ecr.CustomerId);
            var eventData           = _eventRepository.GetById(ecr.EventId);

            if (_optumAccountIds.Contains(corporateAccount.Id))
            {
                eventDirectoryPdf = destinationFolderPdfPath;
            }

            if (corporateAccount.Id == _settings.OptumNvAccountId || corporateAccount.Id == _settings.OptumNvMedicareAccountId)
            {
                if (!string.IsNullOrEmpty(customer.Mrn))
                {
                    destinationFilename = customer.Mrn + "_" + eventData.EventDate.ToString("yyyyMMdd");
                    var customerPcp = _primaryCarePhysicianRepository.Get(ecr.CustomerId);
                    destinationFilename += (customerPcp != null ? "_" + customerPcp.Name.LastName : "");
                }
                else
                {
                    newCustomersWithNoMrn.Add(ecr.CustomerId);
                    _logger.Info("MRN not available for Customer ID : " + ecr.CustomerId);
                    return;
                }
            }

            if (_monarchAccountIds.Contains(corporateAccount.Id))
            {
                destinationFilename = ResultFileName(customer);
            }

            if (corporateAccount.MarkPennedBack && ecr.IsPennedBack)
            {
                destinationFilename += "_" + corporateAccount.PennedBackText;
            }

            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
            {
                var fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.PDF);

                var resultPdfFile = eventDirectoryPdf + "/" + fileName + ".pdf";
                _resultPdfDownloadHelper.ExportResultInPdfFormat(fileName + ".pdf", sourcePath, eventDirectoryPdf);

                _logger.Info("source Url: " + sourcePath);
                _logger.Info("destination Url: " + eventDirectoryPdf + "/" + fileName + ".pdf");

                if (File.Exists(resultPdfFile))
                {
                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultPdfFile);

                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                }
                else
                {
                    _logger.Info("File Not Found : " + resultPdfFile);
                }
            }

            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
            {
                var fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.TIF);

                var resultTifFile = eventDirectoryPdf + "/" + fileName + ".tif";
                _resultPdfDownloadHelper.ExportResultInTiffFormat(fileName + ".tif", sourcePath, eventDirectoryPdf);

                _logger.Info("source Url: " + sourcePath);
                _logger.Info("destination Url: " + eventDirectoryPdf + "/" + fileName + ".tif");

                if (File.Exists(resultTifFile))
                {
                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultTifFile);
                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                }
                else
                {
                    _logger.Info(string.Format("File {0} not Exist for pgp Encryption ", resultTifFile));
                }
            }
        }
Esempio n. 10
0
        public void SavePrimaryCarePhysician(PrimaryCarePhysicianEditModel pcpEditModel, long customerId, long orgRoleUserId = 0)
        {
            var pcp = _primaryCarePhysicianRepository.Get(customerId);

            if (pcp == null && pcpEditModel == null)
            {
                return;
            }

            if (pcp != null && pcpEditModel == null)
            {
                _primaryCarePhysicianRepository.DecativatePhysician(customerId, orgRoleUserId > 0 ? orgRoleUserId : customerId);
            }
            else
            {
                if (pcp == null)
                {
                    pcp = new PrimaryCarePhysician
                    {
                        Name                 = pcpEditModel.FullName,
                        Primary              = !string.IsNullOrEmpty(pcpEditModel.Phone) ? PhoneNumber.Create(pcpEditModel.Phone, PhoneNumberType.Unknown) : pcpEditModel.PhoneNumber,
                        Email                = string.IsNullOrEmpty(pcpEditModel.Email) ? new Email(string.Empty, string.Empty) : new Email(pcpEditModel.Email),
                        CustomerId           = customerId,
                        DataRecorderMetaData = new DataRecorderMetaData(orgRoleUserId > 0 ? orgRoleUserId : customerId, DateTime.Now, null)
                    };
                }
                else
                {
                    pcp.Name    = pcpEditModel.FullName;
                    pcp.Primary = !string.IsNullOrEmpty(pcpEditModel.Phone) ? PhoneNumber.Create(pcpEditModel.Phone, PhoneNumberType.Unknown) : pcpEditModel.PhoneNumber;
                    pcp.Email   = string.IsNullOrEmpty(pcpEditModel.Email) ? new Email(string.Empty, string.Empty) : new Email(pcpEditModel.Email);
                    pcp.DataRecorderMetaData.DataRecorderModifier = new OrganizationRoleUser(orgRoleUserId > 0 ? orgRoleUserId : customerId);
                    pcp.DataRecorderMetaData.DateModified         = DateTime.Now;
                }

                if (pcpEditModel.Address != null && !pcpEditModel.Address.IsEmpty())
                {
                    long addressId = 0;
                    if (pcp.Address != null)
                    {
                        addressId = pcp.Address.Id;
                    }
                    pcp.Address    = Mapper.Map <AddressEditModel, Address>(pcpEditModel.Address);
                    pcp.Address.Id = addressId;
                }
                else
                {
                    pcp.Address = null;
                }

                if (pcpEditModel.MailingAddress != null && !pcpEditModel.MailingAddress.IsEmpty() && !IsAddressSame(pcpEditModel))
                {
                    long addressId = 0;
                    if (pcp.MailingAddress != null && pcp.Address != null && pcp.MailingAddress.Id != pcp.Address.Id)
                    {
                        addressId = pcp.MailingAddress.Id;
                    }

                    pcp.MailingAddress    = Mapper.Map <AddressEditModel, Address>(pcpEditModel.MailingAddress);
                    pcp.MailingAddress.Id = addressId;
                }
                else
                {
                    pcp.MailingAddress = null;
                }

                _primaryCarePhysicianRepository.Save(pcp);
            }
        }
Esempio n. 11
0
        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.");
            }
        }
        public void PollForClinicalDocument()
        {
            if (_accountIds.IsNullOrEmpty())
            {
                return;
            }
            var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

            _logger.Info("Starting CCD Service...");

            foreach (var account in corporateAccounts)
            {
                try
                {
                    _logger.Info("running For Account Id..... " + account.Id);

                    var customSettingFilePath = string.Format(_settings.ClinicalDoumentSettingPath, account.Tag);
                    var customSettings        = _customSettingManager.Deserialize(customSettingFilePath);

                    var fromDate = customSettings.LastTransactionDate ?? _settings.PcpDownloadCutOfDate;
                    var toDate   = DateTime.Now;

                    var eventCustomers = _eventCustomerResultRepository.GetEventCustomerResultsToFax((int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false, toDate, fromDate, account.Id, account.Tag);

                    if (eventCustomers.IsNullOrEmpty())
                    {
                        return;
                    }

                    var directoryPath = string.Format(_settings.ClinicalDoumentPath, account.FolderName);

                    foreach (var ecr in eventCustomers)
                    {
                        try
                        {
                            _logger.Info("Generating CCD Report for Customer Id " + ecr.CustomerId + " eventid: " + ecr.EventId);
                            var customer = _customerRepository.GetCustomer(ecr.CustomerId);
                            var pcp      = _primaryCarePhysicianRepository.Get(customer.CustomerId);
                            var theEvent = _eventRepository.GetById(ecr.EventId);
                            var model    = _clinicalDocumentFactory.Create(ecr, customer, pcp, theEvent);

                            var fileName = customer.Name.FirstName + customer.Name.LastName + ".xml";

                            var filePath = Path.Combine(directoryPath, fileName);

                            DirectoryOperationsHelper.DeleteFileIfExist(filePath);

                            _clinicalDocumentSerializer.SerializeandSave(filePath, model);
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some Exception occured while generating CCD Xml for customerId: " + ecr.CustomerId + " Eventid: " + ecr.EventId + " for Tag" + account.Tag);
                            _logger.Error("Message: " + exception.Message);
                            _logger.Error("Stack Trace: " + exception.StackTrace);
                        }
                    }

                    _logger.Info("compeletd  For Account Id..... " + account.Id);
                }
                catch (Exception exception)
                {
                    _logger.Error("some Exception occured while generating CCD Xml for account Tag " + account.Tag);
                    _logger.Error("Message: " + exception.Message);
                    _logger.Error("Stack Trace: " + exception.StackTrace);
                }
            }
        }
Esempio n. 13
0
        public void PollforInsuranceEncounter()
        {
            const int pageSize   = 50;
            int       pageNumber = 1;

            _logger.Info("\n");
            _logger.Info(string.Format("Creating Patients and Encounter. Date: {0:MM/dd/yyyy}", DateTime.Now));
            _logger.Info("\n");

            var filter = new InsurancePaymentListModelFilter
            {
                EventFrom = DateTime.Now.Date.AddDays(-1),
                EventTo   = DateTime.Now.Date.AddDays(-1)
            };

            while (true)
            {
                try
                {
                    int totalRecords;

                    var eventCustomers = _eventCustomerRepository.GetInsurancePayment(pageNumber, pageSize, filter, out totalRecords);

                    if (eventCustomers == null || !eventCustomers.Any())
                    {
                        _logger.Info("No Records Found!");
                        break;
                    }

                    var insuranceCompanies  = _insuranceCompanyRepository.GetAll();
                    var billingAccounts     = _billingAccountRepository.GetAll();
                    var billingAccountTests = _billingAccountRepository.GetAllBillingAccountTests();

                    if (billingAccounts == null || !billingAccounts.Any())
                    {
                        _logger.Info("No billing account has been setup");
                        break;
                    }

                    if (billingAccountTests == null || !billingAccountTests.Any())
                    {
                        _logger.Info("No billing account test has been setup");
                        break;
                    }
                    //var response = _kareoApi.GetPatient(4, billingAccounts.First());
                    foreach (var eventCustomer in eventCustomers)
                    {
                        if (eventCustomer.NoShow || !eventCustomer.AppointmentId.HasValue || !eventCustomer.LeftWithoutScreeningReasonId.HasValue)
                        {
                            continue;
                        }

                        var appointment = _appointmentRepository.GetById(eventCustomer.AppointmentId.Value);

                        if (!appointment.CheckInTime.HasValue)
                        {
                            continue;
                        }

                        _logger.Info(string.Format("Creating Patient and Encounter for Event (Id: {0}) and Customer (Id: {1})", eventCustomer.EventId, eventCustomer.CustomerId));
                        _logger.Info("\n");

                        var customer    = _customerRepository.GetCustomer(eventCustomer.CustomerId);
                        var eventData   = _eventRepository.GetById(eventCustomer.EventId);
                        var eligibility = _eligibilityRepository.GetByEventCustomerId(eventCustomer.Id);
                        var pcp         = _primaryCarePhysicianRepository.Get(eventCustomer.CustomerId);

                        var eventTests = new List <EventTest>();

                        var orderId       = _orderRepository.GetOrderIdByEventCustomerId(eventCustomer.Id);
                        var eventPackage  = _eventPackageRepository.GetPackageForOrder(orderId);
                        var alaCarteTests = _eventTestRepository.GetTestsForOrder(orderId);

                        if (eventPackage != null)
                        {
                            foreach (var test in eventPackage.Tests)
                            {
                                test.Price = test.Test.PackagePrice;
                            }
                            eventTests.AddRange(eventPackage.Tests);
                        }

                        if (alaCarteTests != null && alaCarteTests.Any())
                        {
                            eventTests.AddRange(alaCarteTests);
                        }

                        foreach (var billingAccount in billingAccounts)
                        {
                            var billingAccountTestIds = billingAccountTests.Where(bat => bat.BillingAccountId == billingAccount.Id).Select(bat => bat.TestId).ToArray();

                            var insuranceTests = eventTests.Where(et => billingAccountTestIds.Contains(et.TestId)).Select(et => et).ToArray();
                            if (insuranceTests == null || !insuranceTests.Any())
                            {
                                continue;
                            }

                            long patientId;
                            var  customerBillingAccount = _customerBillingAccountRepository.GetByCustomerIdBillingAccountId(eventCustomer.CustomerId, billingAccount.Id);
                            if (customerBillingAccount != null)
                            {
                                patientId = customerBillingAccount.BillingPatientId;
                            }
                            else
                            {
                                var patientResponse = _kareoApi.CreatePatient(customer, eligibility, insuranceCompanies, pcp, billingAccount);
                                if (!patientResponse.PatientID.HasValue)
                                {
                                    _logger.Info(string.Format("Patient not created for Event (Id: {0}) and Customer (Id: {1}) and Billing Account {2}", eventCustomer.EventId, eventCustomer.CustomerId, billingAccount.Name));
                                    _logger.Info("\n");
                                    continue;
                                }

                                customerBillingAccount = new CustomerBillingAccount()
                                {
                                    BillingAccountId = billingAccount.Id,
                                    BillingPatientId = patientResponse.PatientID.Value,
                                    CustomerId       = customer.CustomerId,
                                    DateCreated      = DateTime.Now
                                };
                                _customerBillingAccountRepository.Save(customerBillingAccount);

                                patientId = patientResponse.PatientID.Value;

                                _logger.Info(string.Format("Patient created for Event (Id: {0}) and Customer (Id: {1}) and Billing Account {2}", eventCustomer.EventId, eventCustomer.CustomerId, billingAccount.Name));
                            }

                            if (patientId > 0)
                            {
                                var encounterResponse = _kareoApi.CreateEncounter(patientId, eventData, insuranceTests, billingAccount);
                                if (encounterResponse.EncounterID > 0)
                                {
                                    var encounter = new Encounter
                                    {
                                        Id = encounterResponse.EncounterID,
                                        BillingAccountId = billingAccount.Id,
                                        DateCreated      = DateTime.Now
                                    };
                                    encounter = _encounterRepository.Save(encounter);
                                    _encounterRepository.SaveEventCustomerEncounter(eventCustomer.Id, encounter.Id);

                                    _logger.Info(string.Format("Encounter created for Event (Id: {0}) and Customer (Id: {1}) and Billing Account {2}", eventCustomer.EventId, eventCustomer.CustomerId, billingAccount.Name));
                                }
                                else
                                {
                                    _logger.Info(string.Format("Encounter not created for Event (Id: {0}) and Customer (Id: {1}) and Billing Account {2}", eventCustomer.EventId, eventCustomer.CustomerId, billingAccount.Name));
                                    _logger.Info("\n");
                                }
                            }
                        }
                    }

                    if ((pageNumber * pageSize) >= totalRecords)
                    {
                        break;
                    }

                    pageNumber++;
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("Error while fetching event customers Message:{0} \nStackTrace: {1}", ex.Message, ex.StackTrace));
                    _logger.Info("\n");
                    break;
                }
            }
        }
        public CustomerAppointmentViewModel GetPatientDetail(long eventCustomerId)
        {
            var eventCustomer = _eventCustomerRepository.GetById(eventCustomerId);

            if (eventCustomer == null)
            {
                return(null);
            }

            var customer = _customerRepository.GetCustomer(eventCustomer.CustomerId);

            var account = !string.IsNullOrWhiteSpace(customer.Tag) ? _corporateAccountRepository.GetByTagWithOrganization(customer.Tag) : null;

            var appointment = eventCustomer.AppointmentId.HasValue ? _appointmentRepository.GetById(eventCustomer.AppointmentId.Value) : null;

            var order = _orderRepository.GetOrderByEventCustomerId(eventCustomerId);

            var eventPackages = _eventPackageRepository.GetPackagesForEvent(eventCustomer.EventId);

            var eventTests = _eventTestRepository.GetTestsForEvent(eventCustomer.EventId);

            var eventpackageId = order.OrderDetails.Where(od => od.OrderItemStatus.OrderStatusState == OrderStatusState.FinalSuccess && od.OrderItem.OrderItemType == OrderItemType.EventPackageItem)
                                 .Select(od => od.OrderItem.ItemId).SingleOrDefault();
            var eventPackage = eventPackages.SingleOrDefault(ep => eventpackageId == ep.Id);

            var eventTestIds      = order.OrderDetails.Where(od => od.OrderItemStatus.OrderStatusState == OrderStatusState.FinalSuccess && od.OrderItem.OrderItemType == OrderItemType.EventTestItem).Select(od => od.OrderItem.ItemId).ToArray();
            var eventTestsonOrder = eventTests.Where(et => eventTestIds.Contains(et.Id)).ToArray();

            var address = Mapper.Map <Address, AddressViewModel>(customer.Address);

            var pcp = _primaryCarePhysicianRepository.Get(eventCustomer.CustomerId);

            var isParticipationConsentSaved   = _participationConsentSignatureRepository.IsSaved(eventCustomerId);
            var isGiftCardSaved               = _eventCustomerGiftCardRepository.IsSaved(eventCustomerId);
            var isFluConsentSaved             = _fluConsentSignatureRepository.IsSaved(eventCustomerId);
            var isPhysicianRecordRequestSaved = _physicianRecordRequestSignatureRepository.IsSaved(eventCustomerId);
            var chaperoneSignature            = _chaperoneSignatureRepository.GetByEventCustomerId(eventCustomer.Id);

            var model = new CustomerAppointmentViewModel
            {
                CustomerId             = customer.CustomerId,
                EventCustomerId        = eventCustomer.Id,
                FirstName              = customer.Name.FirstName,
                MiddleName             = customer.Name.MiddleName,
                LastName               = customer.Name.LastName,
                Email                  = customer.Email.ToString(),
                Address                = address,
                HomePhone              = customer.HomePhoneNumber.FormatPhoneNumber,
                MobileNumber           = customer.MobilePhoneNumber.FormatPhoneNumber,
                MemberId               = customer.InsuranceId,
                Dob                    = customer.DateOfBirth,
                Gender                 = customer.Gender.GetDescription(),
                HealthPlan             = account != null ? account.Name : "",
                EventId                = eventCustomer.EventId,
                AppointmentId          = appointment != null ? appointment.Id : (long?)null,
                AppointmentTime        = appointment != null ? appointment.StartTime : (DateTime?)null,
                CheckInTime            = appointment != null ? appointment.CheckInTime : null,
                CheckOutTime           = appointment != null ? appointment.CheckOutTime : null,
                Packages               = eventPackage != null ? eventPackage.Package.Name : "",
                Tests                  = !eventTestsonOrder.IsNullOrEmpty() ? string.Join(", ", eventTestsonOrder.Select(t => t.Test.Name)) : "",
                HipaaConsent           = eventCustomer.HIPAAStatus,
                PcpConsent             = eventCustomer.PcpConsentStatus,
                MatrixConsent          = isParticipationConsentSaved,
                PhysicianRecordRequest = isPhysicianRecordRequestSaved,
                GiftCard               = isGiftCardSaved,
                FluVaccine             = isFluConsentSaved,
                Survey                 = false,
                ExitInterview          = false,
                NoShow                 = eventCustomer.AppointmentId.HasValue && eventCustomer.NoShow,
                LeftWithoutScreening   = eventCustomer.AppointmentId.HasValue && eventCustomer.LeftWithoutScreeningReasonId.HasValue,
                ChaperoneConsent       = chaperoneSignature != null ? true : false
            };

            if (pcp != null)
            {
                var pcpAddress = pcp.Address != null?Mapper.Map <Address, AddressViewModel>(pcp.Address) : null;

                model.PrimaryCarePhysician = new PcpInfoViewModel
                {
                    Name        = pcp.Name.FullName,
                    Address     = pcpAddress,
                    PhoneNumber = pcp.Primary != null ? pcp.Primary.FormatPhoneNumber : pcp.Secondary != null ? pcp.Secondary.FormatPhoneNumber : "",
                    Fax         = pcp.Fax != null ? pcp.Fax.FormatPhoneNumber : ""
                };
            }

            return(model);
        }