Example #1
0
        // Belongs to Finance Domain
        public CustomerItemizedReceiptModel GetItemizedRecieptModel(long customerId, long eventId)
        {
            var customer = _customerRepository.GetCustomer(customerId);
            var host     = _hostRepository.GetHostForEvent(eventId);
            var order    = _orderRepository.GetOrder(customerId, eventId);

            var package = _eventPackageRepository.GetPackageForOrder(order.Id);
            var tests   = _eventTestRepository.GetTestsForOrder(order.Id);

            IEnumerable <OrderedPair <long, long> > orderItemIdTestIdPair = null;

            //var orderitemIdsforTestitem =
            //    order.OrderDetails.Where(
            //        od =>
            //        od.DetailType == OrderItemType.EventTestItem &&
            //        od.OrderItemStatus.OrderStatusState == OrderStatusState.FinalSuccess).Select(od => od.OrderItemId).
            //        ToArray();

            //if (orderitemIdsforTestitem.Count() > 0)
            //    orderItemIdTestIdPair = _eventTestRepository.GetOrderItemIdandTestIdpair(orderitemIdsforTestitem);

            var products = _productRepository.GetProductNameForOrderItems(order.OrderDetails.Where(od => od.DetailType == OrderItemType.ProductItem &&
                                                                                                   od.OrderItemStatus.OrderStatusState == OrderStatusState.FinalSuccess).Select(od => od.OrderItemId).ToArray());

            return(_itemizedRecieptModelFactory.Create(customer, host, order, package, tests, orderItemIdTestIdPair, products));
        }
        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 void GetTestForOrder_ValidId_Tester()
        {
            var eventTests = _eventTestRepository.GetTestsForOrder(505275);

            Assert.IsNotNull(eventTests);
            Assert.IsNotEmpty(eventTests.ToArray());
            Assert.IsTrue(eventTests.Select(et => et.EventId).Contains(24671));
            Assert.IsTrue(eventTests.Select(et => et.Id).Contains(195296));
            Assert.IsTrue(eventTests.Select(et => et.TestId).Contains(20));
        }
        public EventCustomerPackageTestDetailViewData GetEventPackageDetails(long eventId, long customerId)
        {
            var orderId      = _orderRepository.GetOrderIdByEventIdCustomerId(eventId, customerId);
            var eventTests   = _eventTestRepository.GetTestsForOrder(orderId);
            var eventPackage = _eventPackageRepository.GetPackageForOrder(orderId);

            var eventCustomerPackageTestDetailViewData = new EventCustomerPackageTestDetailViewData
            {
                Tests = eventTests != null?eventTests.Select(et => et.Test).ToList() : null,
                            Package           = eventPackage != null ? eventPackage.Package : null,
                            ElectronicProduct = _electronicProductRepository.GetElectronicProductByOrderId(orderId)
            };

            return(eventCustomerPackageTestDetailViewData);
        }
Example #5
0
        public void PollForTestUpsell()
        {
            var notificationTypes = _notificationTypeRepository.GetAll();

            var notificationIsActive = notificationTypes.Any(nt => (nt.NotificationTypeAlias == NotificationTypeAlias.TestUpsellNotification) && nt.IsActive);

            if (!notificationIsActive)
            {
                return;
            }

            var eventCustomers = _eventCustomerRepository.GetEventCustomersForTestUpsellNotification(1).ToArray();

            if (!eventCustomers.Any())
            {
                return;
            }
            eventCustomers = eventCustomers.OrderBy(ec => ec.EventId).ToArray();

            long eventId = 0;
            IEnumerable <EventTest> eventTests = null;

            foreach (var eventCustomer in eventCustomers)
            {
                try
                {
                    if (eventId != eventCustomer.EventId)
                    {
                        eventId    = eventCustomer.EventId;
                        eventTests = _eventTestRepository.GetTestsForEvent(eventId);
                        if (eventTests != null && eventTests.Any())
                        {
                            eventTests = eventTests.Where(et => et.Test.ShowInAlaCarte).Select(et => et).ToArray();
                        }
                    }

                    if (!eventTests.Any())
                    {
                        return;
                    }
                    var order = _orderRepository.GetOrder(eventCustomer.CustomerId, eventId);

                    var purchasedEventTestIds = new List <long>();
                    var packagePurchased      = _eventPackageRepository.GetPackageForOrder(order.Id);
                    if (packagePurchased != null)
                    {
                        purchasedEventTestIds.AddRange(packagePurchased.Tests.Select(t => t.Id).ToList());
                    }

                    var testPurchased = _eventTestRepository.GetTestsForOrder(order.Id);
                    if (testPurchased != null && testPurchased.Any())
                    {
                        purchasedEventTestIds.AddRange(testPurchased.Select(t => t.Id));
                    }

                    var sendNotification = false;
                    IEnumerable <EventTest> notpurchasedEventTests = null;
                    if (purchasedEventTestIds == null || !purchasedEventTestIds.Any())
                    {
                        notpurchasedEventTests = eventTests;
                        sendNotification       = true;
                    }
                    else
                    {
                        notpurchasedEventTests = eventTests.Where(et => !purchasedEventTestIds.Contains(et.Id)).Select(et => et).ToArray();
                        if (notpurchasedEventTests != null && notpurchasedEventTests.Any())
                        {
                            sendNotification = true;
                        }
                    }

                    if (sendNotification)
                    {
                        var customer = _customerRepository.GetCustomer(eventCustomer.CustomerId);
                        var tests    = notpurchasedEventTests.Select(et => et.Test).ToArray();
                        var testUpsellNotificationModel = _emailNotificationModelsFactory.GetTestUpsellNotificationModel(customer, tests);
                        _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.TestUpsellNotification, EmailTemplateAlias.TestUpsellNotification, testUpsellNotificationModel, customer.Id, customer.CustomerId, "TestUpsellNotification");
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("Test Upsell Notification Error For Customer Id : {0} and Event Id {1} \nMessage:{2} \nStackTrace: {3}", eventCustomer.CustomerId, eventCustomer.EventId, ex.Message, ex.StackTrace));
                }
            }
        }
        public ClinicalDocument Create(EventCustomerResult eventCustomerResult, Customer customer, PrimaryCarePhysician pcp, Event theEventData)
        {
            var patientIds = GetClinicalRoots(null, customer.CustomerId.ToString(), ClinicalDocumentRoots.PatinetMedicalRecordNumber);

            if (!string.IsNullOrWhiteSpace(customer.Hicn))
            {
                patientIds = GetClinicalRoots(patientIds, customer.Hicn.Trim(), ClinicalDocumentRoots.PatientAdditionalIds);
            }

            if (!string.IsNullOrWhiteSpace(customer.InsuranceId))
            {
                patientIds = GetClinicalRoots(patientIds, customer.InsuranceId.Trim(), ClinicalDocumentRoots.PatientAdditionalIds);
            }
            var telecom = new List <ClinicalTeleCom>();

            if (customer.HomePhoneNumber != null && !customer.HomePhoneNumber.IsEmpty())
            {
                telecom.Add(new ClinicalTeleCom(TelecomType.PrimaryHome, customer.HomePhoneNumber.GlobalPhoneNumberFormat));
            }

            if (customer.MobilePhoneNumber != null && !customer.MobilePhoneNumber.IsEmpty())
            {
                telecom.Add(new ClinicalTeleCom(TelecomType.MobileContact, customer.MobilePhoneNumber.GlobalPhoneNumberFormat));
            }


            if (customer.OfficePhoneNumber != null && !customer.OfficePhoneNumber.IsEmpty())
            {
                telecom.Add(new ClinicalTeleCom(TelecomType.Workplace, customer.OfficePhoneNumber.GlobalPhoneNumberFormat));
            }

            var orderId    = _orderRepository.GetOrderIdByEventIdCustomerId(theEventData.Id, customer.CustomerId);
            var package    = _eventPackageRepository.GetPackageForOrder(orderId);
            var eventTests = _eventTestRepository.GetTestsForOrder(orderId);

            if (package != null)
            {
                eventTests = eventTests.Concat(package.Tests.ToArray());
            }

            var tests = eventTests.Select(et => et.Test).ToArray();


            var structureBodySection = new List <StructuredBodyComponent>()
            {
                new StructuredBodyComponent()
                {
                    Section = _ccdVitalSectionFactory.GetVitalSection(customer, theEventData, tests, _settings)
                },
                GetResultSection(customer, theEventData, tests),
            };

            return(new ClinicalDocument
            {
                Realm = new RealmCode("US"),
                Title = "Summary of Patient Chart",
                EffectiveTime = new DocumentGenerationtime(DateTime.Now),
                // LanguageCode = new LanguageCode("en-US"),
                RecordTarget = new RecordTarget
                {
                    PatientRole = new PatientRole
                    {
                        PatientIds = patientIds,
                        PatinetAddress = GetClinicalAddress(customer.BillingAddress, AddressType.HomeAddress),
                        Patient = GetPatient(customer),
                        TeleCom = telecom.IsNullOrEmpty() ? null : telecom.ToArray(),
                        ProviderOrganization = GetProviderOrganization()
                    }
                },
                DocumentationOfCcd = GetDocumentationOf(pcp, theEventData),
                CdaBodyComponent = new CdaBodyComponent()
                {
                    StructuredBody = new StructuredBody {
                        VitalSigns = structureBodySection.ToArray()
                    }
                }
            });
        }
        public PatientWorksheet GetPatientWorksheetModel(Customer customer, Event theEvent, EventCustomer eventCustomer)
        {
            var customerId = customer.Id;
            var eventId    = theEvent.Id;

            var order                = _orderRepository.GetOrderByEventCustomerId(eventCustomer.Id);
            var eventPackage         = _eventPackageRepository.GetPackageForOrder(order.Id);
            var eventTest            = _eventTestRepository.GetTestsForOrder(order.Id);
            var products             = _electronicProductRepository.GetAllProductsForEvent(eventId);
            var purchasedProduct     = _electronicProductRepository.GetElectronicProductByOrderId(order.Id);
            var customerIcdCodes     = _customerIcdCodesRepository.GetIcdByCustomerId(customerId);
            var customerTags         = _corporateCustomerCustomTagRepository.GetByCustomerId(customerId);
            var preApporvedTestNames = _preApprovedTestRepository.GetPreApprovedTestNameByEventCustomerId(eventCustomer.Id);
            var testForTechnician    = _eventTestRepository.GetTestsForEventByRole(eventId, (long)Roles.Technician);

            string[] customerRecentTags = null;

            var isCorporateEvent = theEvent.EventType == EventType.Corporate;

            if (customerTags != null && customerTags.Any() && isCorporateEvent)
            {
                customerTags       = customerTags.OrderByDescending(x => x.DataRecorderMetaData.DateCreated).Take(4);
                customerRecentTags = customerTags.Select(x => x.Tag).ToArray();
            }

            var icdCodes = new List <string>();

            if (!customerIcdCodes.IsNullOrEmpty())
            {
                icdCodes = _icdCodesRepository.GetIcdByIds(customerIcdCodes.Select(x => x.IcdCodeId)).Select(x => x.CodeName.ToUpper()).ToList();
            }

            var labName = string.Empty;

            if (customer.LabId.HasValue)
            {
                var lab = _labRepository.GetById(customer.LabId.Value);
                labName = lab.Name;
            }

            return(new PatientWorksheet
            {
                Name = customer.Name,
                CustomerId = customer.CustomerId,
                Dob = customer.DateOfBirth,
                Height = customer.Height,
                Weight = customer.Weight,
                Gender = customer.Gender,
                Package = eventPackage,
                Tests = eventTest,
                Lab = labName,
                AlaCarteTest = testForTechnician,
                AllProducts = products,
                ProductId = purchasedProduct != null ? purchasedProduct.Id : 0,
                IcdCodes = icdCodes,
                PreApporvedTestNames = preApporvedTestNames,
                EventDate = theEvent.EventDate,
                CustomTags = customerRecentTags,
                IsCorporateEvent = theEvent.EventType == EventType.Corporate
            });
        }
Example #8
0
        public IEnumerable <EventAppointmentAggregate> GetEventAppointmentAggregates(IEnumerable <long> appointmentsIds)
        {
            var appointmentAggregates = new List <EventAppointmentAggregate>();

            using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
            {
                var linqMetaData = new LinqMetaData(myAdapter);

                var ecustomers =
                    linqMetaData.EventCustomers.WithPath(
                        path => path.Prefetch(ec => ec.Events).Prefetch(ec => ec.EventAppointment))
                    .Where(ec => ec.AppointmentId.HasValue && appointmentsIds.Contains(ec.AppointmentId.Value)).
                    ToArray();

                foreach (var record in ecustomers)
                {
                    var orderId = _orderRepository.GetOrderIdByEventIdCustomerId(record.EventId, record.CustomerId);
                    var package = _packageRepository.GetPackageForOrder(orderId);
                    var tests   = _testRepository.GetTestsForOrder(orderId);

                    var packageAndTests = package != null ? package.Package.Name : string.Empty;
                    packageAndTests += tests.IsNullOrEmpty()
                                           ? string.Empty
                                           : !string.IsNullOrEmpty(packageAndTests)
                                                 ? ", " + string.Join(", ", tests.Select(t => t.Test.Name).ToArray())
                                                 : string.Join(", ", tests.Select(t => t.Test.Name).ToArray());


                    appointmentAggregates.Add(new EventAppointmentAggregate
                    {
                        Appointment =
                            _appointmentMapper.Map(record.EventAppointment),
                        AppointmentBookedFor =
                            _customerRepository.GetCustomer(record.CustomerId),
                        Event           = _eventMapper.Map(record.Events),
                        PackageAndTests = packageAndTests
                    });
                }

                return(appointmentAggregates);

                #region "Dead Code"


                //var eventCustomers =
                //    linqMetaData.EventCustomers.Where(
                //        ec => ec.AppointmentId.HasValue && appointmentsIds.Contains(ec.AppointmentId.Value)).ToArray();

                //// TODO: This query has to be fixed.
                //var eventCustomerPackageDetails =
                //    eventCustomers.Select(ec => new
                //                                    {
                //                                        EventCustomerAppointmentId = ec.AppointmentId,
                //                                        EventCustomerEventId = ec.EventId,
                //                                        EventCustomerCustomerId = ec.CustomerId,
                //                                    }).ToList();

                //var eventAppointmentPackageDetails =
                //    eventCustomerPackageDetails.Join(linqMetaData.Events, @t => @t.EventCustomerEventId, e => e.EventId,
                //                                     (@t, e) =>
                //                                     new
                //                                         {
                //                                             @t.EventCustomerAppointmentId,
                //                                             @t.EventCustomerCustomerId,
                //                                             e
                //                                         }).Join(linqMetaData.EventAppointment,
                //                                                 @t => @t.EventCustomerAppointmentId,
                //                                                 ea => ea.AppointmentId,
                //                                                 (@t, ea) =>
                //                                                 new
                //                                                     {
                //                                                         @t.EventCustomerAppointmentId,
                //                                                         @t.EventCustomerCustomerId,
                //                                                         @t.e,
                //                                                         ea
                //                                                     }).ToList();

                //var eventAppointmentPackageForCustomer =
                //    eventAppointmentPackageDetails.Join(linqMetaData.CustomerProfile, @t => @t.EventCustomerCustomerId,
                //                                        c => c.CustomerId, (@t, c) => new { @t, c }).Select(
                //        @t =>
                //        new
                //            {
                //                Appointments = @t.t.ea,
                //                Events = @t.t.e,
                //                Customers = @t.c,
                //                @t.t.EventCustomerAppointmentId
                //            }).ToList();

                //eventAppointmentPackageForCustomer =
                //    eventAppointmentPackageForCustomer.Where(
                //        @t => appointmentsIds.Contains(@t.Appointments.AppointmentId)).ToList();

                //foreach (var appointmentPackageForCustomer in eventAppointmentPackageForCustomer)
                //{
                //    var package = _packageRepository.GetPackageForOrder(appointmentPackageForCustomer.Events.EventId,
                //                                                        appointmentPackageForCustomer.Customers.
                //                                                            CustomerId);
                //    var tests = _testRepository.GetTestsForOrder(appointmentPackageForCustomer.Events.EventId,
                //                                                 appointmentPackageForCustomer.Customers.
                //                                                     CustomerId);
                //    var packageAndTests = package != null ? package.Name : string.Empty;

                //    packageAndTests += tests.IsNullOrEmpty()
                //                           ? string.Empty
                //                           : !string.IsNullOrEmpty(packageAndTests)
                //                                 ? ", " + string.Join(", ", tests.Select(t => t.Name).ToArray())
                //                                 : string.Join(", ", tests.Select(t => t.Name).ToArray());


                //    appointmentAggregates.Add(new EventAppointmentAggregate
                //                                  {
                //                                      Appointment =
                //                                          _appointmentMapper.Map(
                //                                          appointmentPackageForCustomer.Appointments),
                //                                      AppointmentBookedFor =
                //                                          _customerRepository.GetCustomer(
                //                                          appointmentPackageForCustomer.Customers.CustomerId),
                //                                      Event = _eventMapper.Map(appointmentPackageForCustomer.Events),
                //                                      PackageAndTests = packageAndTests
                //                                  });
                //}

                //return appointmentAggregates;
                #endregion
            }
        }
        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;
                }
            }
        }
Example #10
0
        public CustomerScreeningViewData GetCustomerScreeningViewData(long customerId, long eventId)
        {
            var eventCustomer   = _eventCustomerRepository.Get(eventId, customerId);
            var customer        = _customerRepository.GetCustomer(customerId);
            var theEvent        = _eventRepository.GetById(eventId);
            var isNewResultFlow = theEvent.EventDate >= _settings.ResultFlowChangeDate;
            var testResults     = GetTestResults(customerId, eventId, isNewResultFlow);
            var appointment     = _appointmentRepository.GetEventCustomerAppointment(eventId, customerId);
            var order           = _orderRepository.GetOrder(customerId, eventId);
            var package         = _packageRepository.GetPackageForOrder(order.Id);

            var tests = _testRepository.GetTestsForOrder(order.Id);

            var evaluatingPhysicians = _physicianEvaluationRepsoitory.GetPhysicianEvaluation(eventCustomer.Id);
            var primaryEvalRecord    = evaluatingPhysicians != null?evaluatingPhysicians.Where(p => p.IsPrimaryEvaluator).OrderByDescending(p => p.EvaluationEndTime ?? p.EvaluationStartTime).FirstOrDefault() : null;

            var primaryPhysicianId  = primaryEvalRecord != null ? primaryEvalRecord.PhysicianId : 0;
            var overreadPhysicianId = primaryEvalRecord != null?evaluatingPhysicians.Where(p => !p.IsPrimaryEvaluator && p.EvaluationStartTime > primaryEvalRecord.EvaluationStartTime).OrderByDescending(
                p => p.EvaluationEndTime ?? p.EvaluationStartTime).Select(p => p.PhysicianId).FirstOrDefault() : 0;

            if (primaryPhysicianId < 1)
            {
                var assignment = _physicianAssignmentService.GetPhysicianIdsAssignedtoaCustomer(eventId, customerId);
                if (assignment != null)
                {
                    primaryPhysicianId  = assignment.First();
                    overreadPhysicianId = assignment.ElementAtOrDefault(1);
                }
                else // Should be Skip Evaluation Case
                {
                    var physicians = testResults.Where(tr => tr.EvaluatedbyOrgRoleUserId > 0).Select(tr => tr.EvaluatedbyOrgRoleUserId).Distinct().ToArray();

                    if (physicians.Any())
                    {
                        primaryPhysicianId = physicians.First();
                    }

                    if (physicians.Count() > 1)
                    {
                        overreadPhysicianId = physicians.Last();
                    }
                }
            }
            if (primaryPhysicianId < 1)
            {
                //todo:default for the state
                primaryPhysicianId = _physicianRepository.GetDefaultPhysicianforEvent(eventId);
            }

            var primaryPhysician  = _physicianRepository.GetPhysician(primaryPhysicianId);
            var overreadPhysician = overreadPhysicianId > 0 ? _physicianRepository.GetPhysician(overreadPhysicianId) : null;

            var host           = _hostRepository.GetHostForEvent(eventId);
            var basicBiometric = _basicBiometricRepository.Get(eventId, customerId);

            CustomerScreeningViewData viewData = _factory.Create(testResults, customer, appointment, theEvent, package != null ? package.Package : null, tests != null ? tests.Select(t => t.Test).ToArray() : null, host,
                                                                 primaryPhysician, overreadPhysician, order, basicBiometric);

            if (order.PaymentsApplied != null)
            {
                var chargeCardPayments =
                    order.PaymentsApplied.Where(pa => pa.PaymentType == PaymentType.CreditCard).Select(
                        pa => (ChargeCardPayment)pa).ToArray();

                if (chargeCardPayments.Count() > 0)
                {
                    viewData.ChargeCards = _chargeCardRepository.GetByIds(chargeCardPayments.Select(cp => cp.ChargeCardId).ToArray());
                }

                var checkPayments = order.PaymentsApplied.Where(pa => pa.PaymentType == PaymentType.Check).Select(
                    pa => (CheckPayment)pa).ToArray();

                if (checkPayments.Count() > 0)
                {
                    viewData.Checks = _checkRepository.GetByIds(checkPayments.Select(c => c.CheckId).ToArray());
                }
            }

            var eventHospitalPartner = _hospitalPartnerRepository.GetEventHospitalPartnersByEventId(eventId);

            if (eventHospitalPartner != null && eventHospitalPartner.RestrictEvaluation)
            {
                var eventPhysicianTests = _eventPhysicianTestRepository.GetByEventId(eventId);
                if (eventPhysicianTests != null && eventPhysicianTests.Any())
                {
                    viewData.EventPhysicianTests = eventPhysicianTests;
                }
            }

            return(viewData);
        }