Example #1
0
        public static void Import_Patients_to_ElasticDB(Patient_Model patient, string TenantID)
        {
            string indexElastic = TenantID;
            var    serializer   = new JsonNetSerializer();
            var    connection   = Elastic_Utils.ElsaticConnection();

            bool checkIndex = Elastic_Utils.IfIndexOrTypeExists(indexElastic, connection);


            if (!checkIndex)
            {
                string settings = Elastic_Utils.BuildIndexSettings();
                connection.Put(indexElastic, settings);

                string jsonProductMapping   = BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }

            bool checkTupe = Elastic_Utils.IfIndexOrTypeExists(indexElastic + "/patient", connection);


            if (!checkTupe)
            {
                string jsonProductMapping   = BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }

            List <Patient_Model> modelList = new List <Patient_Model>();

            modelList.Add(patient);

            Elastic_Utils.BulkType_Generic <Patient_Model>(modelList, connection, serializer, indexElastic, "patient");
        }
Example #2
0
        /// <summary>
        /// 患者手机端注册方法 返回当前id
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public int GetPatientRegister(Patient_Model m)
        {
            string sql = $"insert into patient(userName,_password,_phone,_tou) values('{m.userName}','{m._password}','{m._phone}','{m._tou}');select @@IDENTITY";
            int    h   = Convert.ToInt32(helper.ExecuteScalar(sql));

            return(h);
        }
        public async Task <IActionResult> SavePatient([FromBody] Patient_Model patient)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(m => m.Errors).Select(m => m.ErrorMessage);
                    return(BadRequest(new { errors = errors }));
                }

                var patientAddedSuccess = await _bll.SavePatient(patient).ConfigureAwait(false);

                bool patientAccountAddedSuccess = await _auth.AddPatient(patient).ConfigureAwait(false);

                if (patientAddedSuccess && patientAccountAddedSuccess)
                {
                    return(Ok(patient));
                }

                return(BadRequest(new { errors = "Unable to save the patient information, please try again" }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, new { errors = ex.Message }));
            }
        }
Example #4
0
        /// <summary>
        /// 账号管理患者修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public int GetupdPatient(Patient_Model d)
        {
            string sql = $"update patient set userName='******',_phone='{d._phone}',_password='******' where id={d.id}";
            int    h   = helper.ExceuteNonQuery(sql);

            return(h);
        }
Example #5
0
        public async Task <bool> AddPatientAsync(Patient_Model patient)
        {
            try
            {
                SqlCommand cmd = new SqlCommand
                {
                    CommandType = System.Data.CommandType.Text,
                    Connection  = cn,
                    CommandText = "INSERT INTO dbo.PatientAccount (PatientId, UserName, PW, Salt) VALUES (@PatientId, @UserName, @PW, @Salt) "
                };

                cmd.Parameters.AddWithValue("@PatientId", patient.PatientId);
                cmd.Parameters.AddWithValue("@UserName", patient.Email);
                cmd.Parameters.AddWithValue("@PW", patient.DateOfBirth.ToString("MMddyyyy"));
                cmd.Parameters.AddWithValue("@Salt", "Wat ?");

                cn.Open();
                return(await cmd.ExecuteNonQueryAsync().ConfigureAwait(false) == 1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cn.Close();
            }
        }
        public async Task <bool> SavePatient(Patient_Model patient)
        {
            try
            {
                SqlCommand cmd = new SqlCommand
                {
                    Connection  = cn,
                    CommandType = System.Data.CommandType.Text,
                    CommandText = "INSERT INTO Patient (FirstName, LastName, DateOfBirth, Gender, Phone1, Phone2, Email, EmergencyContactName, " +
                                  "EmergencyContactRelation, EmergencyContactPhone, PreferredHospital, PreferredPhysician, " +
                                  "IsActive, EnteredBy, EnteredDate, ModifiedBy, ModifiedDate) " +
                                  "output inserted.PatientId " +
                                  "VALUES(@FirstName, @LastName, @DateOfBirth, @Gender, @Phone1, @Phone2, @Email, @EmergencyContactName, @EmergencyContactRelation, " +
                                  "@EmergencyContactPhone, @PreferredHospital, @PreferredPhysician, @IsActive, @EnteredBy, @EnteredDate, @ModifiedBy, @ModifiedDate)"
                };

                DateTime now = DateTime.Now;

                cmd.Parameters.AddWithValue("@FirstName", patient.FirstName);
                cmd.Parameters.AddWithValue("@LastName", patient.LastName);
                cmd.Parameters.AddWithValue("@DateOfBirth", patient.DateOfBirth);
                cmd.Parameters.AddWithValue("@Gender", patient.Gender);
                cmd.Parameters.AddWithValue("@Phone1", patient.Phone1);
                cmd.Parameters.AddWithValue("@Phone2", patient.Phone2 ?? "");
                cmd.Parameters.AddWithValue("@Email", patient.Email);
                cmd.Parameters.AddWithValue("@EmergencyContactName", patient.EmergencyContactName ?? "");
                cmd.Parameters.AddWithValue("@EmergencyContactRelation", patient.EmergencyContactRelation ?? "");
                cmd.Parameters.AddWithValue("@EmergencyContactPhone", patient.EmergencyContactPhone ?? "");
                cmd.Parameters.AddWithValue("@PreferredHospital", patient.PreferredHospital ?? "");
                cmd.Parameters.AddWithValue("@PreferredPhysician", patient.PreferredPhysician ?? "");
                cmd.Parameters.AddWithValue("@IsActive", 1);//New patient default to active
                cmd.Parameters.AddWithValue("@EnteredBy", "Whomst here ?");
                cmd.Parameters.AddWithValue("@EnteredDate", now);
                cmd.Parameters.AddWithValue("@ModifiedBy", "Whomst here ?");
                cmd.Parameters.AddWithValue("@ModifiedDate", now);

                await cn.OpenAsync().ConfigureAwait(false);

                var patientId = (int)await cmd.ExecuteScalarAsync().ConfigureAwait(false);

                //Check that a valid patientId was generated
                if (patientId < 100000)
                {
                    return(false);
                }

                patient.PatientId = patientId;
                return(true);
            }
            catch (Exception ex)
            {
                //Log
                throw new DatabaseException($"Something went wrong saving the patient.", ex);
            }
            finally
            {
                cn.Close();
            }
        }
        public IActionResult GetFanPatient_List(int id)
        {
            List <Patient_Model> patients = patient_BLL.GetShowTable <Patient_Model>();
            Patient_Model        patient  = patients.Where(p => p.id.Equals(id)).FirstOrDefault();

            return(Ok(new
            {
                code = 0,
                msg = "",
                data = patient,
                count = patients.Count
            }));
        }
Example #8
0
        public static List <Patient_Model> Get_Patients_for_Autocomplete(string search_criteria, Guid practice_id, string connectionString, SessionSecurityTicket securityTicket)
        {
            var    TenantID   = securityTicket.TenantID.ToString();
            var    serializer = new JsonNetSerializer();
            var    connection = Elastic_Utils.ElsaticConnection();
            string queryS     = string.Empty;

            List <Patient_Model> modelForSendL = new List <Patient_Model>();

            if (Elastic_Utils.IfIndexOrTypeExists(TenantID, connection) && Elastic_Utils.IfIndexOrTypeExists(TenantID + "/" + elasticType, connection))
            {
                var query = new QueryBuilder <Patient_Model>()
                            .Query(q => q
                                   .Filtered(f => f.Filter(r => r.Missing(m => m.Field("originating_practice_id")))
                                             .Query(q1 => q1
                                                    .Bool(b => b
                                                          .Should(sh => sh
                                                                  .Match(m => m
                                                                         .Field("name_with_birthdate")
                                                                         .Query(search_criteria.Replace('.', '-').ToLower()).Operator(PlainElastic.Net.Operator.AND)
                                                                         )
                                                                  .Match(m => m
                                                                         .Field("insurance_id")
                                                                         .Query(search_criteria.ToLower()).Operator(PlainElastic.Net.Operator.AND)
                                                                         )
                                                                  ).MinimumNumberShouldMatch(1)
                                                          .Must(ma => ma.Match(m => m.Field("practice_id").Query(practice_id.ToString())))
                                                          )
                                                    )))
                            .Sort(s => s.Field("name.lower_case_sort", PlainElastic.Net.SortDirection.asc)).From(0)
                            .Size(int.MaxValue);

                queryS = query.BuildBeautified();
                string searchCommand_Doc_Practices = Commands.Search(TenantID, elasticType).Pretty();
                string result = connection.Post(searchCommand_Doc_Practices, queryS);

                var foundResults_Patients = serializer.ToSearchResult <Patient_Model>(result);

                return(foundResults_Patients.Documents.Select(item =>
                {
                    Patient_Model modelP = new Patient_Model();
                    modelP.name_with_birthdate = item.name_with_birthdate;
                    modelP.id = item.id;

                    return modelP;
                }).ToList());
            }

            return(modelForSendL);
        }
        public async Task <bool> UpatePatient(Patient_Model patient)
        {
            try
            {
                SqlCommand cmd = new SqlCommand
                {
                    Connection  = cn,
                    CommandType = System.Data.CommandType.Text,
                    CommandText = "UPDATE [dbo].[Patient] SET[FirstName] = @FirstName, [LastName] = @LastName, " +
                                  "[DateOfBirth] = @DateOfBirth, [Gender] = @Gender, [Phone1] = @Phone1, [Phone2] = @Phone2, [Email] = @Email," +
                                  " [EmergencyContactName] = @EmergencyContactName, [EmergencyContactRelation] = @EmergencyContactRelation, " +
                                  "[EmergencyContactPhone] = @EmergencyContactPhone, [PreferredHospital] = @PreferredHospital, " +
                                  "[PreferredPhysician] = @PreferredPhysician, [ModifiedBy] = @ModifiedBy, [ModifiedDate] = @ModifiedDate " +
                                  "WHERE PatientId = @PatientId "
                };

                cmd.Parameters.AddWithValue("@FirstName", patient.FirstName);
                cmd.Parameters.AddWithValue("@LastName", patient.LastName);
                cmd.Parameters.AddWithValue("@DateOfBirth", patient.DateOfBirth);
                cmd.Parameters.AddWithValue("@Gender", patient.Gender);
                cmd.Parameters.AddWithValue("@Phone1", patient.Phone1);
                cmd.Parameters.AddWithValue("@Phone2", patient.Phone2 ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@Email", patient.Email);
                cmd.Parameters.AddWithValue("@EmergencyContactName", patient.EmergencyContactName ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@EmergencyContactRelation", patient.EmergencyContactRelation ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@EmergencyContactPhone", patient.EmergencyContactPhone ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@PreferredHospital", patient.PreferredHospital ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@PreferredPhysician", patient.PreferredPhysician ?? (object)DBNull.Value);
                cmd.Parameters.AddWithValue("@ModifiedBy", "Whomst here ?");
                cmd.Parameters.AddWithValue("@ModifiedDate", DateTime.Now);
                cmd.Parameters.AddWithValue("@PatientId", patient.PatientId);

                await cn.OpenAsync().ConfigureAwait(false);

                var success = (int)await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

                //Check that a valid patientId was generated
                return(success == 1);
            }
            catch (Exception ex)
            {
                //Log
                throw new DatabaseException($"Something went wrong saving the patient.", ex);
            }
            finally
            {
                cn.Close();
            }
        }
Example #10
0
        public static Patient_Model Get_Patient_for_PatientID(string patient_id, SessionSecurityTicket securityTicket)
        {
            Patient_Model patient    = new Patient_Model();
            var           TenantID   = securityTicket.TenantID.ToString();
            var           serializer = new JsonNetSerializer();
            var           connection = Elastic_Utils.ElsaticConnection();

            string query = QueryBuilderPatients.BuildGetPatientQuery(patient_id);

            string searchCommand = Commands.Search(TenantID, elasticType).Pretty();
            string result        = connection.Post(searchCommand, query);

            var foundResults = serializer.ToSearchResult <Patient_Model>(result);

            foreach (var item in foundResults.Documents)
            {
                patient = item;
            }
            return(patient);
        }
        public async Task <Patient_Model> GetPatient(long patientId)
        {
            SqlCommand cmd = new SqlCommand
            {
                Connection  = cn,
                CommandType = System.Data.CommandType.Text,
                CommandText = "select * from dbo.Patient where PatientId = @patientId",
            };

            Patient_Model patient = null;

            try
            {
                cmd.Parameters.AddWithValue("@patientId", patientId);
                await cn.OpenAsync().ConfigureAwait(false);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        patient = DataRowToPatientMapper.Map(reader);
                    }
                    //Do i want a check here for more than one row ? I know in the db I've set it up where it just cant happen ...
                    //Leave as is for now
                }
            }
            catch (Exception ex)
            {
                //Log
                throw new DatabaseException($"Something went wrong getting the patient with id {patientId}.", ex);
            }
            finally
            {
                cn.Close();
            }

            return(patient);
        }
        public static void Update_Patients_add_Participation_Consent(string connectionString, SessionSecurityTicket securityTicket)
        {
            DbConnection  Connection         = null;
            DbTransaction Transaction        = null;
            bool          cleanupConnection  = Connection == null;
            bool          cleanupTransaction = Transaction == null;

            if (cleanupConnection == true)
            {
                Connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(connectionString);
                Connection.Open();
            }
            if (cleanupTransaction == true)
            {
                Transaction = Connection.BeginTransaction();
            }
            try
            {
                var allPatients = ORM_HEC_Patient.Query.Search(Connection, Transaction, new ORM_HEC_Patient.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID
                }).ToList();

                foreach (var patient in allPatients)
                {
                    var contractIvi = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        ContractName = "IVI-Vertrag"
                    }).SingleOrDefault();
                    if (contractIvi != null)
                    {
                        var InsuranceToBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                        InsuranceToBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                        InsuranceToBrokerContractQuery.IsDeleted    = false;
                        InsuranceToBrokerContractQuery.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;

                        ORM_HEC_CRT_InsuranceToBrokerContract InsuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, InsuranceToBrokerContractQuery).Single();

                        List <DateTime> TimeFrom = new List <DateTime>();
                        DateTime        time1    = new DateTime(2013, 6, 15);
                        DateTime        time2    = new DateTime(2014, 6, 15);
                        DateTime        time3    = new DateTime(2015, 6, 15);

                        TimeFrom.Add(time1);
                        TimeFrom.Add(time2);
                        TimeFrom.Add(time3);
                        foreach (var date in TimeFrom)
                        {
                            ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient InsuranceToBrokerContract_ParticipatingPatient = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient();
                            InsuranceToBrokerContract_ParticipatingPatient.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID = Guid.NewGuid();
                            InsuranceToBrokerContract_ParticipatingPatient.InsuranceToBrokerContract_RefID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                            InsuranceToBrokerContract_ParticipatingPatient.Creation_Timestamp     = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Modification_Timestamp = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Tenant_RefID           = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidFrom     = date;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidThrough  = DateTime.MinValue;
                            InsuranceToBrokerContract_ParticipatingPatient.Patient_RefID = patient.HEC_PatientID;
                            InsuranceToBrokerContract_ParticipatingPatient.Save(Connection, Transaction);


                            Patient_Model patientModel2 = new Patient_Model();
                            patientModel2 = Retrieve_Patients.Get_Patient_for_PatientID(patient.HEC_PatientID.ToString(), securityTicket);

                            var InsuranceToBrokerContract_ParticipatingPatientQuery = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                            InsuranceToBrokerContract_ParticipatingPatientQuery.IsDeleted     = false;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Tenant_RefID  = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Patient_RefID = patient.HEC_PatientID;

                            var allInsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, InsuranceToBrokerContract_ParticipatingPatientQuery).ToList();
                            var latest_participation_date = allInsuranceToBrokerContract_ParticipatingPatient.OrderByDescending(m => m.ValidFrom).FirstOrDefault();

                            patientModel2.participation_consent_from = latest_participation_date.ValidFrom;
                            patientModel2.participation_consent_to   = latest_participation_date.ValidThrough;
                            patientModel2.has_participation_consent  = true;

                            Add_New_Patient.Import_Patients_to_ElasticDB(patientModel2, securityTicket.TenantID.ToString());
                        }
                    }
                }
                if (cleanupTransaction == true)
                {
                    Transaction.Commit();
                }
                //Close the connection
                if (cleanupConnection == true)
                {
                    Connection.Close();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw ex;
            }
        }
 public async Task <bool> UpdatePatient(Patient_Model patient)
 {
     return(await _dal.UpatePatient(patient).ConfigureAwait(false));
 }
Example #14
0
 public async Task <bool> AddPatient(Patient_Model patient)
 {
     return(await _dal.AddPatientAsync(patient).ConfigureAwait(false));
 }
Example #15
0
        public static void ImportTestPatients(DbConnection Connection, DbTransaction Transaction, SessionSecurityTicket securityTicket, Guid medical_practice_id)
        {
            List <Patient_Model_xls> patientList        = new List <Patient_Model_xls>();
            List <Patient_Model>     elasticPatientList = new List <Patient_Model>();
            IFormatProvider          culture            = new System.Globalization.CultureInfo("de", true);

            string folder    = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string filePath  = Path.Combine(folder, "Excel\\german_names_sheet.xlsx");
            bool   hasHeader = true;

            System.Data.DataTable excelData = ExcelUtils.getDataFromExcelFile(filePath, hasHeader);

            foreach (System.Data.DataRow item in excelData.Rows)
            {
                if (item.ItemArray[0].ToString() == "")
                {
                    break;
                }
                Patient_Model_xls patientModel = new Patient_Model_xls();
                patientModel.name     = item.ItemArray[0].ToString();
                patientModel.LastName = item.ItemArray[1].ToString();
                patientModel.sex      = item.ItemArray[2].ToString();
                patientModel.birthday = DateTime.Parse(item.ItemArray[3].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                patientList.Add(patientModel);
            }

            List <string> StateCode_first_Caracter = new List <string>();

            StateCode_first_Caracter.Add("1");
            StateCode_first_Caracter.Add("3");
            StateCode_first_Caracter.Add("5");


            List <string> StateCode_fift_Caracter = new List <string>();

            StateCode_fift_Caracter.Add("1");
            StateCode_fift_Caracter.Add("4");
            StateCode_fift_Caracter.Add("6");
            StateCode_fift_Caracter.Add("7");
            StateCode_fift_Caracter.Add("8");
            StateCode_fift_Caracter.Add("9");
            StateCode_fift_Caracter.Add("D");
            StateCode_fift_Caracter.Add("F");
            StateCode_fift_Caracter.Add("A");
            StateCode_fift_Caracter.Add("C");
            StateCode_fift_Caracter.Add("S");
            StateCode_fift_Caracter.Add("P");
            StateCode_fift_Caracter.Add("E");
            StateCode_fift_Caracter.Add("N");
            StateCode_fift_Caracter.Add("M");
            StateCode_fift_Caracter.Add("X");
            StateCode_fift_Caracter.Add("L");
            StateCode_fift_Caracter.Add("K");

            int status_code_counter = 0;
            int status_fift_counter = 0;
            int counter             = 0;

            var medicalPracticeQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();

            medicalPracticeQuery.IsDeleted    = false;
            medicalPracticeQuery.Tenant_RefID = securityTicket.TenantID;

            var HIPList = ORM_HEC_HIS_HealthInsurance_Company.Query.Search(Connection, Transaction, medicalPracticeQuery).ToList();


            int i = 0;

            foreach (var item in patientList)
            {
                ORM_HEC_Patient patients = new ORM_HEC_Patient();
                patients.HEC_PatientID                     = Guid.NewGuid();
                patients.Tenant_RefID                      = securityTicket.TenantID;
                patients.Creation_Timestamp                = DateTime.Now;
                patients.Modification_Timestamp            = DateTime.Now;
                patients.CMN_BPT_BusinessParticipant_RefID = Guid.NewGuid();
                patients.Save(Connection, Transaction);

                ORM_CMN_BPT_BusinessParticipant businesParticipantPatient = new ORM_CMN_BPT_BusinessParticipant();
                businesParticipantPatient.CMN_BPT_BusinessParticipantID = patients.CMN_BPT_BusinessParticipant_RefID;
                businesParticipantPatient.Tenant_RefID           = securityTicket.TenantID;
                businesParticipantPatient.Creation_Timestamp     = DateTime.Now;
                businesParticipantPatient.Modification_Timestamp = DateTime.Now;
                businesParticipantPatient.IsNaturalPerson        = true;
                businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businesParticipantPatient.Save(Connection, Transaction);

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID   = businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Tenant_RefID           = securityTicket.TenantID;
                personInfo.Creation_Timestamp     = DateTime.Now;
                personInfo.Modification_Timestamp = DateTime.Now;
                personInfo.FirstName = item.name;           //
                personInfo.LastName  = item.LastName;       //
                personInfo.BirthDate = item.birthday;       //
                personInfo.Gender    = int.Parse(item.sex); //
                personInfo.Save(Connection, Transaction);

                ORM_HEC_Patient_MedicalPractice medical_practice_to_patient = new ORM_HEC_Patient_MedicalPractice();
                medical_practice_to_patient.HEC_Patient_MedicalPracticeID = Guid.NewGuid();
                medical_practice_to_patient.HEC_Patient_RefID             = patients.HEC_PatientID;
                medical_practice_to_patient.HEC_MedicalPractices_RefID    = medical_practice_id;//
                medical_practice_to_patient.Tenant_RefID       = securityTicket.TenantID;
                medical_practice_to_patient.Creation_Timestamp = DateTime.Now;
                medical_practice_to_patient.Save(Connection, Transaction);


                ORM_HEC_Patient_HealthInsurance patientHealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                patientHealthInsurance.HEC_Patient_HealthInsurancesID = Guid.NewGuid();
                patientHealthInsurance.Patient_RefID = patients.HEC_PatientID;

                Random rnd = new Random();
                int    random_insurance_number = rnd.Next(10000000, 99999999);

                int genre = 0;
                switch (int.Parse(item.sex))
                {
                case 0:
                    genre = 2;
                    break;

                case 1:
                    genre = 1;
                    break;

                case 2:
                    genre = 0;
                    break;
                }

                var birth = item.birthday.Year.ToString().Substring(2);
                patientHealthInsurance.HealthInsurance_Number            = random_insurance_number.ToString();                                                                                      //
                patientHealthInsurance.Tenant_RefID                      = securityTicket.TenantID;
                patientHealthInsurance.InsuranceStateCode                = StateCode_first_Caracter[status_code_counter] + genre.ToString() + birth + StateCode_fift_Caracter[status_fift_counter]; //
                patientHealthInsurance.HIS_HealthInsurance_Company_RefID = HIPList[i].HEC_HealthInsurance_CompanyID;
                patientHealthInsurance.Save(Connection, Transaction);


                if (status_code_counter == 2)
                {
                    status_code_counter = 0;
                }
                else
                {
                    status_code_counter++;
                }

                if (status_fift_counter == 17)
                {
                    status_fift_counter = 0;
                }
                else
                {
                    status_fift_counter++;
                }

                if (i == HIPList.Count - 1)
                {
                    i = 0;
                }
                else
                {
                    i++;
                }


                var businesParticipantHIPQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                businesParticipantHIPQuery.IsDeleted    = false;
                businesParticipantHIPQuery.Tenant_RefID = securityTicket.TenantID;
                businesParticipantHIPQuery.CMN_BPT_BusinessParticipantID = HIPList[i].CMN_BPT_BusinessParticipant_RefID;

                var businesParticipantHIP = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businesParticipantHIPQuery).Single();;

                Patient_Model patientModel = new Patient_Model();


                patientModel.birthday                  = DateTime.Parse(item.birthday.ToString("dd.MM.yyyy"), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                patientModel.birthday_string           = item.birthday.ToString("dd.MM.yyyy");
                patientModel.name                      = item.LastName + ", " + item.name;
                patientModel.health_insurance_provider = businesParticipantHIP.DisplayName;
                patientModel.name_with_birthdate       = item.name + " " + item.LastName + " (" + item.birthday.ToString("dd.MM.yyyy") + ")";
                patientModel.id               = patients.HEC_PatientID.ToString();
                patientModel.insurance_id     = patientHealthInsurance.HealthInsurance_Number;
                patientModel.insurance_status = patientHealthInsurance.InsuranceStateCode;
                patientModel.practice_id      = medical_practice_id.ToString();

                if (int.Parse(item.sex) == 0)
                {
                    patientModel.sex = "M";
                }
                else if (int.Parse(item.sex) == 1)
                {
                    patientModel.sex = "W";
                }
                else if (int.Parse(item.sex) == 2)
                {
                    patientModel.sex = "o.A.";
                }


                elasticPatientList.Add(patientModel);



                counter++;
                Console.WriteLine(counter + "________________________" + patientList.Count);
            }



            string indexElastic = securityTicket.TenantID.ToString();
            var    serializer   = new JsonNetSerializer();
            var    connection   = Elastic_Utils.ElsaticConnection();

            bool checkIndex = Elastic_Utils.IfIndexOrTypeExists(indexElastic, connection);


            if (!checkIndex)
            {
                string settings = Elastic_Utils.BuildIndexSettings();
                connection.Put(indexElastic, settings);

                string jsonProductMapping   = Add_New_Patient.BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }

            bool checkTupe = Elastic_Utils.IfIndexOrTypeExists(indexElastic + "/patient", connection);

            if (!checkTupe)
            {
                string jsonProductMapping   = Add_New_Patient.BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }
            Elastic_Utils.BulkType_Generic <Patient_Model>(elasticPatientList, connection, serializer, indexElastic, "patient");
        }
        public IActionResult GetUpdPatient(Patient_Model m)
        {
            int h = doctorLog_BLL.GetUpdateTable(m, "id");

            return(Ok(new { msg = h }));
        }
        public IActionResult GetupdPatient(Patient_Model m)
        {
            int h = patient_BLL.GetupdPatient(m);

            return(Ok(new { msg = h > 0 ? true : false, mrg = h > 0 ? "修改成功!" : "修改失败!" }));
        }
Example #18
0
        public static void Save_Patients_to_DB(Patient_Model_xls Parameter, bool create_consents, string connectionString, SessionSecurityTicket securityTicket)
        {
            DbConnection  Connection         = null;
            DbTransaction Transaction        = null;
            bool          cleanupConnection  = Connection == null;
            bool          cleanupTransaction = Transaction == null;
            Guid          patient_id         = Guid.NewGuid();

            if (cleanupConnection == true)
            {
                Connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(connectionString);
                Connection.Open();
            }
            if (cleanupTransaction == true)
            {
                Transaction = Connection.BeginTransaction();
            }

            try
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");

                ORM_HEC_Patient patients = new ORM_HEC_Patient();
                patients.HEC_PatientID                     = Guid.NewGuid();
                patients.Tenant_RefID                      = securityTicket.TenantID;
                patients.Creation_Timestamp                = DateTime.Now;
                patients.Modification_Timestamp            = DateTime.Now;
                patients.CMN_BPT_BusinessParticipant_RefID = Guid.NewGuid();
                patients.Save(Connection, Transaction);
                patient_id = patients.HEC_PatientID;

                ORM_CMN_BPT_BusinessParticipant businesParticipantPatient = new ORM_CMN_BPT_BusinessParticipant();
                businesParticipantPatient.CMN_BPT_BusinessParticipantID = patients.CMN_BPT_BusinessParticipant_RefID;
                businesParticipantPatient.Tenant_RefID           = securityTicket.TenantID;
                businesParticipantPatient.Creation_Timestamp     = DateTime.Now;
                businesParticipantPatient.Modification_Timestamp = DateTime.Now;
                businesParticipantPatient.IsNaturalPerson        = true;
                businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businesParticipantPatient.Save(Connection, Transaction);
                int PatientSex = 0;
                switch (Parameter.sex)
                {
                case "M":
                    PatientSex = 0;
                    break;

                case "W":
                    PatientSex = 1;
                    break;

                case "o.A.":
                    PatientSex = 2;
                    break;
                }

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID   = businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Tenant_RefID           = securityTicket.TenantID;
                personInfo.Creation_Timestamp     = DateTime.Now;
                personInfo.Modification_Timestamp = DateTime.Now;
                personInfo.FirstName = Parameter.name;
                personInfo.LastName  = Parameter.LastName;
                personInfo.BirthDate = Parameter.birthday;
                personInfo.Gender    = PatientSex;
                personInfo.Save(Connection, Transaction);

                ORM_HEC_Patient_MedicalPractice medical_practice_to_patient = new ORM_HEC_Patient_MedicalPractice();
                medical_practice_to_patient.HEC_Patient_MedicalPracticeID = Guid.NewGuid();
                medical_practice_to_patient.HEC_Patient_RefID             = patients.HEC_PatientID;
                medical_practice_to_patient.HEC_MedicalPractices_RefID    = Guid.Parse(Parameter.practice_id);//
                medical_practice_to_patient.Tenant_RefID       = securityTicket.TenantID;
                medical_practice_to_patient.Creation_Timestamp = DateTime.Now;
                medical_practice_to_patient.Save(Connection, Transaction);


                var medicalPracticeQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();
                medicalPracticeQuery.IsDeleted    = false;
                medicalPracticeQuery.Tenant_RefID = securityTicket.TenantID;

                var HIPList = ORM_HEC_HIS_HealthInsurance_Company.Query.Search(Connection, Transaction, medicalPracticeQuery).ToList();

                if (Parameter.isPrivatelyInsured)
                {
                    Parameter.health_insurance_providerNumber = "000000000";
                }

                var GetHip = HIPList.Where(hp => hp.HealthInsurance_IKNumber == Parameter.health_insurance_providerNumber).SingleOrDefault();
                if (GetHip == null)
                {
                    var businessParticipantHIP = new ORM_CMN_BPT_BusinessParticipant();
                    businessParticipantHIP.IsCompany              = true;
                    businessParticipantHIP.Tenant_RefID           = securityTicket.TenantID;
                    businessParticipantHIP.Modification_Timestamp = DateTime.Now;
                    businessParticipantHIP.DisplayName            = Parameter.health_insurance_provider;

                    businessParticipantHIP.Save(Connection, Transaction);

                    GetHip = new ORM_HEC_HIS_HealthInsurance_Company();
                    GetHip.Tenant_RefID = securityTicket.TenantID;
                    GetHip.CMN_BPT_BusinessParticipant_RefID = businessParticipantHIP.CMN_BPT_BusinessParticipantID;
                    GetHip.HealthInsurance_IKNumber          = String.IsNullOrEmpty(Parameter.health_insurance_provider) ? "privat versichert" : Parameter.health_insurance_provider;

                    GetHip.Save(Connection, Transaction);
                }

                ORM_HEC_Patient_HealthInsurance patientHealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                patientHealthInsurance.HEC_Patient_HealthInsurancesID = Guid.NewGuid();
                patientHealthInsurance.Patient_RefID                     = patients.HEC_PatientID;
                patientHealthInsurance.HealthInsurance_Number            = Parameter.insurance_id;     //
                patientHealthInsurance.Tenant_RefID                      = securityTicket.TenantID;
                patientHealthInsurance.InsuranceStateCode                = Parameter.insurance_status; //
                patientHealthInsurance.HIS_HealthInsurance_Company_RefID = GetHip.HEC_HealthInsurance_CompanyID;
                patientHealthInsurance.Save(Connection, Transaction);

                #region import Patient to Elastic
                Patient_Model patientModel = new Patient_Model();


                patientModel.birthday                  = Parameter.birthday;
                patientModel.birthday_string           = Parameter.birthday.ToString("dd.MM.yyyy");
                patientModel.name                      = Parameter.LastName + ", " + Parameter.name;
                patientModel.health_insurance_provider = String.IsNullOrEmpty(Parameter.health_insurance_provider) ? "privat versichert" : Parameter.health_insurance_provider;
                patientModel.name_with_birthdate       = Parameter.name + " " + Parameter.LastName + " (" + Parameter.birthday.ToString("dd.MM.yyyy") + ")";
                patientModel.id               = patients.HEC_PatientID.ToString();
                patientModel.insurance_id     = String.IsNullOrEmpty(Parameter.insurance_id) ? "-" : Parameter.insurance_id;
                patientModel.insurance_status = String.IsNullOrEmpty(Parameter.insurance_status) ? "-" : Parameter.insurance_status;
                patientModel.practice_id      = Parameter.practice_id.ToString();

                if (PatientSex == 0)
                {
                    patientModel.sex = "M";
                }
                else if (PatientSex == 1)
                {
                    patientModel.sex = "W";
                }
                else if (PatientSex == 2)
                {
                    patientModel.sex = "o.A.";
                }

                Add_New_Patient.Import_Patients_to_ElasticDB(patientModel, securityTicket.TenantID.ToString());
                if (create_consents)
                {
                    #region Participation Consent
                    var contractIvi = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        ContractName = "IVI-Vertrag"
                    }).SingleOrDefault();

                    if (contractIvi != null)
                    {
                        var InsuranceToBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                        InsuranceToBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                        InsuranceToBrokerContractQuery.IsDeleted    = false;
                        InsuranceToBrokerContractQuery.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;

                        ORM_HEC_CRT_InsuranceToBrokerContract InsuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, InsuranceToBrokerContractQuery).Single();

                        List <DateTime> TimeFrom = new List <DateTime>();
                        DateTime        time1    = new DateTime(2013, 6, 15);
                        DateTime        time2    = new DateTime(2014, 6, 15);
                        DateTime        time3    = new DateTime(2015, 6, 15);

                        TimeFrom.Add(time1);
                        TimeFrom.Add(time2);
                        TimeFrom.Add(time3);
                        foreach (var date in TimeFrom)
                        {
                            ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient InsuranceToBrokerContract_ParticipatingPatient = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient();
                            InsuranceToBrokerContract_ParticipatingPatient.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID = Guid.NewGuid();
                            InsuranceToBrokerContract_ParticipatingPatient.InsuranceToBrokerContract_RefID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                            InsuranceToBrokerContract_ParticipatingPatient.Creation_Timestamp     = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Modification_Timestamp = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Tenant_RefID           = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidFrom     = date;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidThrough  = DateTime.MinValue;
                            InsuranceToBrokerContract_ParticipatingPatient.Patient_RefID = patient_id;
                            InsuranceToBrokerContract_ParticipatingPatient.Save(Connection, Transaction);

                            Patient_Model patientModel2 = new Patient_Model();
                            patientModel2 = Retrieve_Patients.Get_Patient_for_PatientID(patient_id.ToString(), securityTicket);

                            var InsuranceToBrokerContract_ParticipatingPatientQuery = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                            InsuranceToBrokerContract_ParticipatingPatientQuery.IsDeleted     = false;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Tenant_RefID  = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Patient_RefID = patient_id;

                            var allInsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, InsuranceToBrokerContract_ParticipatingPatientQuery).ToList();
                            var latest_participation_date = allInsuranceToBrokerContract_ParticipatingPatient.OrderByDescending(m => m.ValidFrom).FirstOrDefault();

                            patientModel2.participation_consent_from = latest_participation_date.ValidFrom;
                            patientModel2.participation_consent_to   = latest_participation_date.ValidThrough;
                            patientModel2.has_participation_consent  = true;

                            Add_New_Patient.Import_Patients_to_ElasticDB(patientModel2, securityTicket.TenantID.ToString());
                        }
                    }
                }

                #endregion
                //Commit the transaction
                if (cleanupTransaction == true)
                {
                    Transaction.Commit();
                }
                //Close the connection
                if (cleanupConnection == true)
                {
                    Connection.Close();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw ex;
            }

            #endregion
        }
        public IActionResult GetUpdPatient_List(Patient_Model model)
        {
            int h = patient_BLL.GetupdPatient(model);

            return(Ok(new { state = h >= 1 ? true : false, msg = h >= 1 ? "修改成功!" : "修改失败!" }));
        }
        public IActionResult GetPatientRegister(Patient_Model m)
        {
            int id = patient_BLL.GetPatientRegister(m);

            return(Ok(new { id = id }));
        }
Example #21
0
        public static void Import_Data_From_DB_To_Elastic(DbConnection Connection, DbTransaction Transaction, SessionSecurityTicket securityTicket)
        {
            #region add Practices and Doctors to Elastic
            List <Practice_Doctors_Model> LdoctorPracticeM = new List <Practice_Doctors_Model>();
            var dataPractice = cls_Get_All_Practices_from_DB.Invoke(Connection, Transaction, securityTicket).Result;
            IAccountServiceProvider accountService;
            var _providerFactory = ProviderFactory.Instance;
            accountService = _providerFactory.CreateAccountServiceProvider();

            if (dataPractice != null)
            {
                foreach (var practice in dataPractice)
                {
                    Practice_Doctors_Model doctorPracticeM = new Practice_Doctors_Model();

                    bool statusAcc = accountService.GetAccountStatusHistory(securityTicket.TenantID, practice.AccountID).OrderBy(st => st.CreationTimestamp).Reverse().FirstOrDefault().Status == EAccountStatus.BANNED;
                    doctorPracticeM.account_status = statusAcc ? "inaktiv" : "aktiv";
                    doctorPracticeM.id             = practice.PracticeID.ToString();
                    doctorPracticeM.name           = practice.Name;
                    doctorPracticeM.name_untouched = practice.Name;
                    doctorPracticeM.salutation     = "";
                    doctorPracticeM.type           = "Practice";
                    doctorPracticeM.address        = practice.Street_Name + " " + practice.Street_Number;
                    doctorPracticeM.zip            = practice.ZIP;
                    doctorPracticeM.city           = practice.City;
                    if (practice.Contact_Email != null)
                    {
                        doctorPracticeM.email = practice.Contact_Email;
                    }
                    doctorPracticeM.phone = doctorPracticeM.phone;

                    doctorPracticeM.bank_untouched = practice.BankName != null ? practice.BankName : "";
                    doctorPracticeM.bank           = practice.BankName != null ? practice.BankName : "";

                    if (practice.IBAN != null)
                    {
                        doctorPracticeM.iban = practice.IBAN;
                    }
                    if (practice.BICCode != null)
                    {
                        doctorPracticeM.bic = practice.BICCode;
                    }
                    doctorPracticeM.bsnr_lanr      = practice.BSNR;
                    doctorPracticeM.aditional_info = "";
                    doctorPracticeM.tenantid       = securityTicket.TenantID.ToString();
                    doctorPracticeM.role           = practice.IsSurgeryPractice ? "op" : "ac";
                    DO_GPCN_1133[] dataContract = cls_Get_Practice_Contract_Numbers.Invoke(Connection, Transaction, new P_DO_GPCN_1133()
                    {
                        PracticeID = practice.PracticeID
                    }, securityTicket).Result;
                    doctorPracticeM.contract = dataContract.Count();
                    LdoctorPracticeM.Add(doctorPracticeM);
                }
            }
            var dataDoc = cls_Get_All_Doctors_from_DB.Invoke(Connection, Transaction, securityTicket).Result;
            if (dataDoc != null)
            {
                foreach (var doctor in dataDoc)
                {
                    Practice_Doctors_Model doctorPracticeM = new Practice_Doctors_Model();
                    bool statusAcc = accountService.GetAccountStatusHistory(securityTicket.TenantID, doctor.AccountID).OrderBy(st => st.CreationTimestamp).Reverse().FirstOrDefault().Status == EAccountStatus.BANNED;
                    doctorPracticeM.account_status = statusAcc ? "inaktiv" : "aktiv";
                    doctorPracticeM.id             = doctor.Id.ToString();
                    var title = string.IsNullOrEmpty(doctor.Title) ? "" : doctor.Title.Trim();
                    doctorPracticeM.tenantid       = securityTicket.TenantID.ToString();
                    doctorPracticeM.name           = title + " " + doctor.LastName + " " + doctor.FirstName;
                    doctorPracticeM.name_untouched = doctor.LastName + " " + doctor.FirstName;
                    doctorPracticeM.bsnr_lanr      = doctor.Lanr.ToString();
                    doctorPracticeM.salutation     = title;
                    doctorPracticeM.type           = "Doctor";
                    doctorPracticeM.bank           = string.IsNullOrEmpty(doctor.BankName) ? "" : doctor.BankName;
                    doctorPracticeM.bank_untouched = string.IsNullOrEmpty(doctor.BankName) ? "" : doctor.BankName;
                    doctorPracticeM.phone          = doctor.Phone;
                    doctorPracticeM.email          = string.IsNullOrEmpty(doctor.Email) ? "" : doctor.Email;

                    doctorPracticeM.iban = string.IsNullOrEmpty(doctor.IBAN) ? "" : doctor.IBAN;

                    doctorPracticeM.bic = string.IsNullOrEmpty(doctor.BICCode) ? "" : doctor.BICCode;
                    var practice = dataPractice.Where(pr => pr.PracticeID == doctor.Practice_ID).SingleOrDefault();
                    doctorPracticeM.practice_for_doctor_id   = practice.PracticeID.ToString();
                    doctorPracticeM.practice_name_for_doctor = practice.Name;
                    doctorPracticeM.address = practice.Street_Name + " " + practice.Street_Number;
                    doctorPracticeM.zip     = practice.ZIP;
                    doctorPracticeM.city    = practice.City;
                    doctorPracticeM.role    = practice.IsSurgeryPractice ? "op" : "ac";

                    if (doctor.BankAccountID == practice.BankAccountID)
                    {
                        doctorPracticeM.bank_id             = practice.BankAccountID.ToString();
                        doctorPracticeM.bank_info_inherited = true;
                        doctorPracticeM.bank_untouched      = practice.BankName != null ? practice.BankName : "";
                        doctorPracticeM.bank = practice.BankName != null ? practice.BankName : "";

                        if (practice.IBAN != null)
                        {
                            doctorPracticeM.iban = practice.IBAN;
                        }
                        if (practice.BICCode != null)
                        {
                            doctorPracticeM.bic = practice.BICCode;
                        }
                    }
                    else
                    {
                        doctorPracticeM.bank_id             = doctor.BankAccountID.ToString();
                        doctorPracticeM.bank_info_inherited = false;
                        doctorPracticeM.bank_untouched      = doctor.BankName != null ? doctor.BankName : "";
                        doctorPracticeM.bank = doctor.BankName != null ? doctor.BankName : "";

                        if (doctor.IBAN != null)
                        {
                            doctorPracticeM.iban = doctor.IBAN;
                        }
                        if (doctor.BICCode != null)
                        {
                            doctorPracticeM.bic = doctor.BICCode;
                        }
                    }

                    var docContracts = cls_Get_Doctor_Contract_Numbers.Invoke(Connection, Transaction, new P_DO_CDCD_1505()
                    {
                        DoctorID = doctor.Id
                    }, securityTicket).Result;
                    doctorPracticeM.contract = docContracts.Count();
                    LdoctorPracticeM.Add(doctorPracticeM);
                }
            }
            //first delete Tenant index
            try
            {
                Add_Practice_Doctors_to_Elastic.Delete_index_on_Elastic(securityTicket.TenantID.ToString());
                //  Add_Practice_Doctors_to_Elastic.Delete_index_on_Elastic(securityTicket.TenantID.ToString() + "/" + "user");
                Console.Write("Type Doctors_Practices deleted");
            }
            catch
            {
                Console.Write("Type Doctors_Practices do not exsists");
            }

            //import items to Elastic
            if (dataDoc != null | dataPractice != null)
            {
                Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(LdoctorPracticeM, securityTicket.TenantID.ToString());
            }
            #endregion


            #region add Patients to Elastic
            var dataPatients = cls_Get_All_Patients_from_DB.Invoke(Connection, Transaction, securityTicket).Result;



            if (dataPatients != null)
            {
                try
                {
                    //     Add_Practice_Doctors_to_Elastic.Delete_index_on_Elastic(securityTicket.TenantID.ToString() + "/" + "patient");
                    Console.Write("Type Patients deleted");
                }
                catch
                {
                    Console.Write("Type Patients do not exsists");
                }

                foreach (var patient in dataPatients)
                {
                    Patient_Model   patientModel = new Patient_Model();
                    var             HIPLIst      = cls_Get_All_HIPs.Invoke(Connection, Transaction, securityTicket).Result.ToList();
                    string          HIP          = HIPLIst.Where(i => i.id == patient.HIPID).Single().name;
                    IFormatProvider culture      = new System.Globalization.CultureInfo("de", true);
                    patientModel.birthday                  = DateTime.Parse(patient.BirthDate.ToString("dd.MM.yyyy"), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                    patientModel.birthday_string           = patient.BirthDate.ToString("dd.MM.yyyy");
                    patientModel.name                      = patient.LastName + ", " + patient.FirstName;
                    patientModel.health_insurance_provider = HIP;
                    patientModel.name_with_birthdate       = patient.FirstName + " " + patient.LastName + " (" + patient.BirthDate.ToString("dd.MM.yyyy") + ")";
                    patientModel.id               = patient.Id.ToString();
                    patientModel.insurance_id     = patient.HipNumber;
                    patientModel.insurance_status = patient.InsuranceStatus;
                    patientModel.practice_id      = patient.PracticeID.ToString();

                    if (patient.Gender == 0)
                    {
                        patientModel.sex = "M";
                    }
                    else if (patient.Gender == 1)
                    {
                        patientModel.sex = "W";
                    }
                    else if (patient.Gender == 2)
                    {
                        patientModel.sex = "o.A.";
                    }

                    //Add patient participation consent
                    if (patient.ValidFrom != DateTime.MinValue)
                    {
                        patientModel.participation_consent_from = patient.ValidFrom;
                        patientModel.has_participation_consent  = true;
                    }

                    if (patient.ValidThrough != DateTime.MinValue)
                    {
                        patientModel.participation_consent_to = patient.ValidThrough;
                    }

                    Add_New_Patient.Import_Patients_to_ElasticDB(patientModel, securityTicket.TenantID.ToString());
                }

                Console.Write("Patients imported to elastic");
            }

            #endregion

            #region Add Cases to Elastic
            List <Case_Model>  cases       = new List <Case_Model>();
            List <Order_Model> OrderModelL = new List <Order_Model>();
            var dataCases = cls_Get_All_Cases_from_DB.Invoke(Connection, Transaction, securityTicket).Result;
            if (dataCases != null)
            {
                foreach (var Case in dataCases)
                {
                    if (Case.case_status == null)
                    {
                        var diagnose_details = cls_Get_Diagnose_Details_for_DiagnoseID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1357()
                        {
                            DiagnoseID = Case.diagnose_id
                        }, securityTicket).Result;
                        var drug_details = cls_Get_Drug_Details_for_DrugID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1614()
                        {
                            DrugID = Case.drug_id
                        }, securityTicket).Result;

                        Case_Model case_model_elastic = new Case_Model();
                        case_model_elastic.diagnose          = diagnose_details != null ? diagnose_details.diagnose_name + " (" + diagnose_details.catalog_display_name + ": " + diagnose_details.diagnose_icd_10 + ")" : "";
                        case_model_elastic.drug              = drug_details != null ? drug_details.drug_name : "";
                        case_model_elastic.id                = Case.case_id.ToString();
                        case_model_elastic.localization      = Case.localization;
                        case_model_elastic.status_drug_order = Case.order_id != Guid.Empty ? "MO1" : "";

                        case_model_elastic.status_treatment         = Case.diagnose_id != Guid.Empty ? "OP1" : "";
                        case_model_elastic.patient_name             = Case.patient_id != Guid.Empty ? Case.Patient_LastName + ", " + Case.Patient_FirstName : "";
                        case_model_elastic.patient_birthdate_string = Case.Patient_BirthDate.ToString("dd.MM.yyyy");
                        case_model_elastic.patient_birthdate        = Case.Patient_BirthDate;
                        if (Case.is_aftercare_practice)
                        {
                            case_model_elastic.aftercare_name = Case.aftercare_practice_display_name;
                        }
                        else if (Case.is_aftercare_doctor)
                        {
                            case_model_elastic.aftercare_name = Case.aftercare_doctor_display_name;
                        }
                        else
                        {
                            case_model_elastic.aftercare_name = "-";
                        }
                        var aftercare_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                        {
                            DoctorID = Case.ac_doctor_id
                        }, securityTicket).Result.SingleOrDefault();

                        if (aftercare_doctor_details != null)
                        {
                            case_model_elastic.aftercare_name = aftercare_doctor_details.title + " " + aftercare_doctor_details.last_name + " " + aftercare_doctor_details.first_name;
                            case_model_elastic.aftercare_doctors_practice_name = aftercare_doctor_details.practice;
                        }


                        case_model_elastic.is_aftercare_doctor       = Case.is_aftercare_doctor;
                        case_model_elastic.treatment_date_day_month  = Case.treatment_date.ToString("dd.MM.");
                        case_model_elastic.treatment_date_month_year = Case.treatment_date.ToString("MMMM yyyy", new System.Globalization.CultureInfo("de", true));
                        var treatment_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                        {
                            DoctorID = Case.treatment_doctor_id
                        }, securityTicket).Result.SingleOrDefault();
                        case_model_elastic.treatment_doctor_name = treatment_doctor_details != null ? treatment_doctor_details.title + " " + treatment_doctor_details.last_name + " " + treatment_doctor_details.first_name : "-";
                        case_model_elastic.practice_id           = Case.practice_id.ToString();

                        case_model_elastic.order_modification_timestamp        = Case.order_modification_timestamp;
                        case_model_elastic.order_modification_timestamp_string = Case.order_modification_timestamp.ToString("dd.MM.yyyy");
                        case_model_elastic.delivery_time_from   = Case.order_id != Guid.Empty ? Case.alternative_delivery_date_from : Case.treatment_date;
                        case_model_elastic.delivery_time_to     = Case.order_id != Guid.Empty ? Case.alternative_delivery_date_to : Case.treatment_date.AddHours(23).AddMinutes(59);
                        case_model_elastic.delivery_time_string = case_model_elastic.delivery_time_from.ToString("HH:mm") + " - " + case_model_elastic.delivery_time_to.ToString("HH:mm");


                        Order_Model orderM = new Order_Model();

                        if (Case.order_id != Guid.Empty)
                        {
                            case_model_elastic.is_orders_drug = true;
                            OR_GOSfCID_0858[] OrderCtatusList = cls_Get_Order_Status_for_CaseID.Invoke(Connection, Transaction, new P_OR_GOSfCID_0858()
                            {
                                CaseID = Case.case_id
                            }, securityTicket).Result;
                            OrderCtatusList = OrderCtatusList.OrderBy(tmp => tmp.StatusCreated).Reverse().ToArray();
                            case_model_elastic.status_drug_order = OrderCtatusList.Count() > 0 ? "MO" + OrderCtatusList.First().StatusCode : "MO1";
                            if (OrderCtatusList.Count() > 1)
                            {
                                case_model_elastic.previous_status_drug_order = "MO" + OrderCtatusList[1].StatusCode;
                            }
                            else
                            {
                                case_model_elastic.previous_status_drug_order = "MO1";
                            }
                            orderM.status_drug_order = OrderCtatusList.Count() > 0 ? "MO" + OrderCtatusList.First().StatusCode : "MO1";
                        }
                        else
                        {
                            case_model_elastic.is_orders_drug = false;
                        }
                        cases.Add(case_model_elastic);

                        if (Case.order_id != Guid.Empty)
                        {
                            orderM.case_id = case_model_elastic.id;
                            orderM.id      = Case.OrderHeaderID.ToString();

                            orderM.delivery_time_from                  = Case.alternative_delivery_date_from != null ? Case.alternative_delivery_date_from : Case.treatment_date;
                            orderM.delivery_time_to                    = Case.alternative_delivery_date_from != null ? Case.alternative_delivery_date_to : Case.treatment_date.AddHours(23).AddMinutes(59);
                            orderM.delivery_time_string                = case_model_elastic.delivery_time_from.ToString("HH:mm") + " - " + case_model_elastic.delivery_time_to.ToString("HH:mm");
                            orderM.practice_id                         = Case.practice_id.ToString();
                            orderM.order_modification_timestamp        = DateTime.Now;
                            orderM.order_modification_timestamp_string = DateTime.Now.ToString("dd.MM.yyyy");
                            orderM.is_orders_drug                      = true;
                            orderM.treatment_date                      = Case.treatment_date;
                            orderM.treatment_date_day_month            = Case.treatment_date.ToString("dd.MM.");
                            orderM.treatment_date_month_year           = Case.treatment_date.ToString("MMMM yyyy", new System.Globalization.CultureInfo("de", true));
                            orderM.treatment_doctor_name               = treatment_doctor_details != null ? treatment_doctor_details.title + " " + treatment_doctor_details.last_name + " " + treatment_doctor_details.first_name : "-";
                            orderM.treatment_doctor_practice_name      = treatment_doctor_details != null ? treatment_doctor_details.practice : "-";
                            orderM.localization                        = Case.diagnose_id != Guid.Empty ? Case.localization : "-";
                            orderM.diagnose                 = diagnose_details != null ? diagnose_details.diagnose_name + " (" + diagnose_details.catalog_display_name + ": " + diagnose_details.diagnose_icd_10 + ")" : "-";
                            orderM.drug                     = drug_details != null ? drug_details.drug_name : "";
                            orderM.patient_name             = Case.patient_id != Guid.Empty ? Case.Patient_LastName + ", " + Case.Patient_FirstName : "";
                            orderM.patient_birthdate_string = Case.Patient_BirthDate.ToString("dd.MM.yyyy");
                            orderM.patient_birthdate        = Case.Patient_BirthDate;


                            OrderModelL.Add(orderM);
                        }
                    }
                }
                try
                {
                    Add_Practice_Doctors_to_Elastic.Delete_index_on_Elastic(securityTicket.TenantID.ToString() + "/" + "case");

                    Console.Write("Type Case deleted");
                }
                catch
                {
                    Console.Write("Type do not exsists");
                }
                Add_New_Case.Import_Case_Data_to_ElasticDB(cases, securityTicket.TenantID.ToString());
                Add_New_Order.Import_Order_Data_to_ElasticDB(OrderModelL, securityTicket.TenantID.ToString());
                Console.Write("Cases and Orders imported to Elastic");
            }
            #endregion
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_PA_SPPC_1413 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            List <PatientDetailViewModel> patientDetailList         = new List <PatientDetailViewModel>();
            PatientDetailViewModel        elasticPatientDetailModel = new PatientDetailViewModel();

            if (Parameter.participation_id == Guid.Empty)
            {
                var InsuranceToBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                InsuranceToBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                InsuranceToBrokerContractQuery.IsDeleted    = false;
                InsuranceToBrokerContractQuery.Ext_CMN_CTR_Contract_RefID = Parameter.contract_id;

                ORM_HEC_CRT_InsuranceToBrokerContract InsuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, InsuranceToBrokerContractQuery).Single();


                ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient InsuranceToBrokerContract_ParticipatingPatient = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient();
                InsuranceToBrokerContract_ParticipatingPatient.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID = Guid.NewGuid();
                InsuranceToBrokerContract_ParticipatingPatient.InsuranceToBrokerContract_RefID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                InsuranceToBrokerContract_ParticipatingPatient.Creation_Timestamp     = DateTime.Now;
                InsuranceToBrokerContract_ParticipatingPatient.Modification_Timestamp = DateTime.Now;
                InsuranceToBrokerContract_ParticipatingPatient.Tenant_RefID           = securityTicket.TenantID;
                InsuranceToBrokerContract_ParticipatingPatient.ValidFrom = Parameter.issue_date;
                if (Parameter.participation_consent_valid_days != 0)
                {
                    InsuranceToBrokerContract_ParticipatingPatient.ValidThrough = Parameter.issue_date.AddMonths(Parameter.participation_consent_valid_days);
                }
                else
                {
                    InsuranceToBrokerContract_ParticipatingPatient.ValidThrough = Parameter.contract_ValidTo;
                }
                InsuranceToBrokerContract_ParticipatingPatient.Patient_RefID = Parameter.patient_id;
                InsuranceToBrokerContract_ParticipatingPatient.Save(Connection, Transaction);

                #region UpdateElastic

                Patient_Model patientModel = new Patient_Model();
                patientModel = Retrieve_Patients.Get_Patient_for_PatientID(Parameter.patient_id.ToString(), securityTicket);

                var InsuranceToBrokerContract_ParticipatingPatientQuery = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                InsuranceToBrokerContract_ParticipatingPatientQuery.IsDeleted     = false;
                InsuranceToBrokerContract_ParticipatingPatientQuery.Tenant_RefID  = securityTicket.TenantID;
                InsuranceToBrokerContract_ParticipatingPatientQuery.Patient_RefID = Parameter.patient_id;

                var allInsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, InsuranceToBrokerContract_ParticipatingPatientQuery).ToList();
                var latest_participation_date = allInsuranceToBrokerContract_ParticipatingPatient.OrderByDescending(m => m.ValidFrom).FirstOrDefault();

                patientModel.participation_consent_from = latest_participation_date.ValidFrom;
                patientModel.participation_consent_to   = latest_participation_date.ValidThrough;
                patientModel.has_participation_consent  = true;


                ///
                elasticPatientDetailModel.id          = InsuranceToBrokerContract_ParticipatingPatient.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID.ToString();
                elasticPatientDetailModel.practice_id = Parameter.practice_id.ToString();
                elasticPatientDetailModel.patient_id  = Parameter.patient_id.ToString();
                elasticPatientDetailModel.date        = Parameter.issue_date;
                elasticPatientDetailModel.date_string = Parameter.issue_date.ToString("dd.MM.");
                elasticPatientDetailModel.detail_type = "participation";

                var insuranceBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                insuranceBrokerContractQuery.IsDeleted    = false;
                insuranceBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                insuranceBrokerContractQuery.HEC_CRT_InsuranceToBrokerContractID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                var insuranceBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, insuranceBrokerContractQuery).Single();

                var contractQuery = new ORM_CMN_CTR_Contract.Query();
                contractQuery.IsDeleted          = false;
                contractQuery.Tenant_RefID       = securityTicket.TenantID;
                contractQuery.CMN_CTR_ContractID = insuranceBrokerContract.Ext_CMN_CTR_Contract_RefID;
                var contract = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, contractQuery).Single();

                var contractParameters = ORM_CMN_CTR_Contract_Parameter.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract_Parameter.Query()
                {
                    Tenant_RefID   = securityTicket.TenantID,
                    IsDeleted      = false,
                    Contract_RefID = Parameter.contract_id
                });

                var validUntil = contractParameters.Where(t => t.ParameterName == "Duration of participation consent – Month").SingleOrDefault();

                var aftercareDays = contractParameters.Where(t => t.ParameterName == "Number of days between surgery and aftercare - Days").SingleOrDefault();


                var validUntilDate = validUntil == null || validUntil.IfNumericValue_Value == double.MaxValue ? DateTime.MaxValue : Parameter.issue_date.AddMonths(Convert.ToInt32(validUntil.IfNumericValue_Value));

                if (aftercareDays != null && aftercareDays.IfNumericValue_Value != double.MaxValue)
                {
                    validUntilDate = validUntilDate.AddDays(-Convert.ToInt32(aftercareDays.IfNumericValue_Value));
                }
                var validUntilStr = validUntilDate == DateTime.MaxValue ? "∞" : validUntilDate.ToString("dd.MM.yyyy");

                elasticPatientDetailModel.diagnose_or_medication = Properties.Resources.participarionConsent + " " + contract.ContractName + ", " + Properties.Resources.goodUntil + " " + validUntilStr;
                elasticPatientDetailModel.case_id = contract.CMN_CTR_ContractID.ToString();

                patientDetailList.Add(elasticPatientDetailModel);

                Add_New_Patient.Import_Patients_to_ElasticDB(new List <Patient_Model>()
                {
                    patientModel
                }, securityTicket.TenantID.ToString());
                Add_New_Patient.ImportPatientDetailsToElastic(patientDetailList, securityTicket.TenantID.ToString());
                #endregion
            }
            else
            {
                //#EDIT******

                //find new contract
                var InsuranceToBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                InsuranceToBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                InsuranceToBrokerContractQuery.IsDeleted    = false;
                InsuranceToBrokerContractQuery.Ext_CMN_CTR_Contract_RefID = Parameter.contract_id;

                ORM_HEC_CRT_InsuranceToBrokerContract InsuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, InsuranceToBrokerContractQuery).Single();



                var queryParticipant = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                queryParticipant.IsDeleted    = false;
                queryParticipant.Tenant_RefID = securityTicket.TenantID;
                queryParticipant.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID = Parameter.participation_id;

                var InsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, queryParticipant).Single();
                InsuranceToBrokerContract_ParticipatingPatient.InsuranceToBrokerContract_RefID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                InsuranceToBrokerContract_ParticipatingPatient.Modification_Timestamp          = DateTime.Now;
                InsuranceToBrokerContract_ParticipatingPatient.ValidFrom = Parameter.issue_date;
                InsuranceToBrokerContract_ParticipatingPatient.ValidFrom = Parameter.issue_date;
                if (Parameter.participation_consent_valid_days != 0)
                {
                    InsuranceToBrokerContract_ParticipatingPatient.ValidThrough = Parameter.issue_date.AddMonths(Parameter.participation_consent_valid_days);
                }
                else
                {
                    InsuranceToBrokerContract_ParticipatingPatient.ValidThrough = Parameter.contract_ValidTo;
                }
                InsuranceToBrokerContract_ParticipatingPatient.Save(Connection, Transaction);


                #region Update Elastic

                Patient_Model patientModel = new Patient_Model();
                patientModel = Retrieve_Patients.Get_Patient_for_PatientID(Parameter.patient_id.ToString(), securityTicket);

                var InsuranceToBrokerContract_ParticipatingPatientQuery = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                InsuranceToBrokerContract_ParticipatingPatientQuery.IsDeleted     = false;
                InsuranceToBrokerContract_ParticipatingPatientQuery.Tenant_RefID  = securityTicket.TenantID;
                InsuranceToBrokerContract_ParticipatingPatientQuery.Patient_RefID = Parameter.patient_id;

                var allInsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, InsuranceToBrokerContract_ParticipatingPatientQuery).ToList();
                var latest_participation_date = allInsuranceToBrokerContract_ParticipatingPatient.OrderByDescending(m => m.ValidFrom).FirstOrDefault();

                patientModel.participation_consent_from = latest_participation_date.ValidFrom;
                patientModel.participation_consent_to   = latest_participation_date.ValidThrough;
                patientModel.has_participation_consent  = true;

                var insuranceBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                insuranceBrokerContractQuery.IsDeleted    = false;
                insuranceBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                insuranceBrokerContractQuery.HEC_CRT_InsuranceToBrokerContractID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                var insuranceBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, insuranceBrokerContractQuery).Single();

                var contractQuery = new ORM_CMN_CTR_Contract.Query();
                contractQuery.IsDeleted          = false;
                contractQuery.Tenant_RefID       = securityTicket.TenantID;
                contractQuery.CMN_CTR_ContractID = insuranceBrokerContract.Ext_CMN_CTR_Contract_RefID;
                var contract = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, contractQuery).Single();

                var elasticPatientDetailModel2 = Retrieve_Patients.Get_PatientDetaiForID(Parameter.participation_id.ToString(), securityTicket);
                if (elasticPatientDetailModel2 != null)
                {
                    elasticPatientDetailModel2.date        = Parameter.issue_date;
                    elasticPatientDetailModel2.date_string = Parameter.issue_date.ToString("dd.MM.");


                    var contractParameters = ORM_CMN_CTR_Contract_Parameter.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract_Parameter.Query()
                    {
                        Tenant_RefID   = securityTicket.TenantID,
                        IsDeleted      = false,
                        Contract_RefID = Parameter.contract_id
                    });

                    var validUntil = contractParameters.Where(t => t.ParameterName == "Duration of participation consent – Month").SingleOrDefault();

                    var aftercareDays = contractParameters.Where(t => t.ParameterName == "Number of days between surgery and aftercare - Days").SingleOrDefault();


                    var validUntilDate = validUntil == null || validUntil.IfNumericValue_Value == double.MaxValue ? DateTime.MaxValue : Parameter.issue_date.AddMonths(Convert.ToInt32(validUntil.IfNumericValue_Value));

                    if (aftercareDays != null && aftercareDays.IfNumericValue_Value != double.MaxValue)
                    {
                        validUntilDate = validUntilDate.AddDays(-Convert.ToInt32(aftercareDays.IfNumericValue_Value));
                    }
                    var validUntilStr = validUntilDate == DateTime.MaxValue ? "∞" : validUntilDate.ToString("dd.MM.yyyy");

                    elasticPatientDetailModel2.diagnose_or_medication = Properties.Resources.participarionConsent + " " + contract.ContractName + ", " + Properties.Resources.goodUntil + " " + validUntilStr;

                    patientDetailList.Add(elasticPatientDetailModel2);
                }

                Add_New_Patient.Import_Patients_to_ElasticDB(new List <Patient_Model>()
                {
                    patientModel
                }, securityTicket.TenantID.ToString());

                if (patientDetailList.Count != 0)
                {
                    Add_New_Patient.ImportPatientDetailsToElastic(patientDetailList, securityTicket.TenantID.ToString());
                }

                #endregion
            }

            return(returnValue);

            #endregion UserCode
        }