public HttpResponseMessage SavePatient([FromBody] PatientEnitities patientForInsert)
        {
            int result = 0;
            HttpResponseMessage httpResponseMessage;

            if (patientForInsert == null)
            {
                httpResponseMessage         = new HttpResponseMessage(HttpStatusCode.BadRequest);
                httpResponseMessage.Content = new ObjectContent(typeof(string), "Bad Request Received", GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                return(httpResponseMessage);
            }
            try
            {
                result = _patientServices.CreatePatient(patientForInsert);
                if (result != 0)
                {
                    httpResponseMessage         = new HttpResponseMessage(HttpStatusCode.Created);
                    httpResponseMessage.Content = new ObjectContent(typeof(string), "New Patient Record Created", GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                    return(httpResponseMessage);
                }
                else
                {
                    httpResponseMessage         = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                    httpResponseMessage.Content = new ObjectContent(typeof(string), "An error occured while creating patient", GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                    return(httpResponseMessage);
                }
            }
            catch (Exception ex)
            {
                httpResponseMessage         = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                httpResponseMessage.Content = new ObjectContent(typeof(string), "An error occured while creating patient", GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                return(httpResponseMessage);
            }
        }
        public void AddNewpatientTest()
        {
            PatientEnitities patientEnitities = new PatientEnitities()
            {
                ForeName       = "testForeName",
                SurName        = "testSurName",
                Gender         = "testGender",
                DOB            = DateTime.Now.ToShortDateString(),
                contactDetails = new ContactDetails()
                {
                    Home   = new List <string>(),
                    Mobile = new List <string>(),
                    Work   = new List <string>()
                }
            };

            Assert.AreNotEqual(_patientService.CreatePatient(patientEnitities), 0);
        }
        public long CreateCernerPatientToChargeCapture(long cernerPatientId, string cernerLocationId)
        {
            CernerPatientCreationInput input      = new CernerPatientCreationInput();
            List <CernerAdmission>     admissions = new List <CernerAdmission>();

            var cernerPatient = _repository.Find(cernerPatientId);

            var existingPatient = _uow.GetRepository <Patient>().Queryable().Where(x => x.ExternalKey3 == cernerPatient.CernerIntegrationId).FirstOrDefault();

            if (existingPatient == null)
            {
                var cernerPatientAddress = _uow.GetRepository <CernerPatientAddress>().Queryable().Where(x => x.CernerPatientId == cernerPatientId);
                Enum.TryParse(cernerPatient.Gender, out Gender patientGender);
                input.Patient = new Patient()
                {
                    DateOfBirth  = cernerPatient.DateOfBirth,
                    FirstName    = cernerPatient.FirstName,
                    LastName     = cernerPatient.LastName,
                    Gender       = patientGender,
                    MiddleName   = cernerPatient.MiddleName,
                    Prefix       = cernerPatient.Prefix,
                    Suffix       = cernerPatient.Suffix,
                    ExternalKey3 = cernerPatient.CernerIntegrationId,
                    AccountId    = _userInfo.AccountId
                };
                if (cernerPatient.PrimaryPhone != null || cernerPatient.Email != null || cernerPatient.Fax != null)
                {
                    input.Patient.Contact = new Contact()
                    {
                        Email        = cernerPatient.Email,
                        Fax          = cernerPatient.Fax,
                        PrimaryPhone = cernerPatient.PrimaryPhone
                    };
                    input.Patient.ContactId = input.Patient.Contact.ContactId;
                }
                if (cernerPatientAddress != null && cernerPatientAddress.Count() > 0)
                {
                    var singleAddress = cernerPatientAddress.FirstOrDefault();
                    int?stateId       = null;
                    var state         = _uow.GetRepository <State>().Queryable().Where(x => x.Abbr == singleAddress.StateAbbr).FirstOrDefault();
                    if (state != null)
                    {
                        stateId = state.StateId;
                    }
                    input.Patient.Address = new Address()
                    {
                        Address1 = singleAddress.Address1,
                        Address2 = singleAddress.Address2,
                        CityName = singleAddress.CityName,
                        StateId  = stateId,
                        ZipCode  = singleAddress.ZipCode
                    };
                    input.Patient.AddressId = input.Patient.Address.AddressId;
                }
            }
            else
            {
                input.Patient = existingPatient;
            }

            var appointments = _uow.GetRepository <CernerAppointment>().Queryable().Where(x => x.PatientId == cernerPatient.CernerIntegrationId && x.IsIntegrated == false && x.LocationId == cernerLocationId).ToList();
            var appointmentsGroupedByLocation = appointments.GroupBy(u => u.LocationId)
                                                .Select(grp => new {
                LocationId   = grp.Key,
                Appointments = grp
            }).ToList();

            foreach (var appointment in appointmentsGroupedByLocation)
            {
                CernerAdmission newAdmission      = new CernerAdmission();
                var             location          = _uow.GetRepository <Location>().Queryable().Where(x => x.ExternalKey3 == appointment.LocationId).FirstOrDefault();
                Admission       existingAdmission = null;
                if (existingPatient != null)
                {
                    existingAdmission = _uow.GetRepository <Admission>().Queryable().Where(x => x.PatientId == existingPatient.PatientId && x.DischargeDate == null && x.LocationId == location.LocationId).FirstOrDefault();
                }

                if (existingAdmission == null)
                {
                    var latestAppointment = appointment.Appointments.OrderByDescending(x => x.StartDate).FirstOrDefault();
                    newAdmission.Admission = new Admission
                    {
                        AdmissionDate = ((DateTime)latestAppointment.StartDate).ToUniversalTime(),
                        LocationId    = location.LocationId
                    };
                }
                else
                {
                    newAdmission.Admission = existingAdmission;
                }

                var appointmentsGroupedByDoctor = appointment.Appointments.GroupBy(u => u.PractitionerId)
                                                  .Select(grp => new {
                    PractitionerId = grp.Key,
                    Appointments   = grp
                }).ToList();

                foreach (var item in appointmentsGroupedByDoctor)
                {
                    var doctor    = _uow.GetRepository <Doctor>().Queryable().Where(x => x.ExternalKey3 == item.PractitionerId).FirstOrDefault();
                    var assistant = _uow.GetRepository <Assistant>().Queryable().Where(x => x.ExternalKey3 == item.PractitionerId).FirstOrDefault();
                    if (doctor != null || assistant != null)
                    {
                        Assignment existingAssignment = null;
                        if (existingAdmission != null)
                        {
                            existingAssignment = _uow.GetRepository <Assignment>().Queryable().Where(x => x.AdmissionId == existingAdmission.AdmissionId && x.DoctorId == doctor.DoctorId && x.EndDate == null).FirstOrDefault();
                        }
                        if (existingAssignment == null)
                        {
                            var latestAssignment = item.Appointments.OrderByDescending(x => x.StartDate).FirstOrDefault();
                            var newAssignment    = new Assignment
                            {
                                StartDate   = ((DateTime)latestAssignment.StartDate).ToUniversalTime(),
                                AdmissionId = (existingAdmission != null ? existingAdmission.AdmissionId : 0),
                                CreatedBy   = _userInfo.UserId,
                            };
                            if (doctor != null)
                            {
                                newAssignment.DoctorId = doctor.DoctorId;
                            }
                            if (assistant != null)
                            {
                                var applicationUser = _uow.GetRepository <ApplicationUser>().Queryable().Where(x => x.AssistantId == assistant.AssistantId && x.Type == UserType.Assistant).FirstOrDefault();
                                newAssignment.DoctorId     = assistant.AssistantId;
                                newAssignment.SupervisorId = applicationUser.DoctorId;
                            }
                            if (newAdmission.Admission.AdmissionId == 0)
                            {
                                newAdmission.Admission.AdmissionDate = ((DateTime)latestAssignment.StartDate).ToUniversalTime();
                            }
                            newAdmission.Assignments.Add(newAssignment);
                        }
                    }
                }
                input.Admissions.Add(newAdmission);
            }

            using (var scope = new TransactionScope())
            {
                if (input.Patient.PatientId == 0)
                {
                    _patientServices.CreatePatient(input.Patient);
                }
                foreach (var admission in input.Admissions)
                {
                    if (admission.Admission.AdmissionId == 0)
                    {
                        admission.Admission.PatientId = input.Patient.PatientId;
                        _admissionServices.CreateAdmission(admission.Admission);
                    }

                    foreach (var assignment in admission.Assignments)
                    {
                        assignment.AdmissionId = admission.Admission.AdmissionId;
                        _assignmentServices.Create(assignment);
                    }
                }
                cernerPatient.IsIntegrated = true;
                UpdatePatient(cernerPatient);
                _cernerAppointmentService.CreatePatientAppointments(cernerPatient.CernerIntegrationId);
                scope.Complete();

                return(input.Patient.PatientId);
            }
        }