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 static void Update_Doctors_add_Contract_Assignment(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 allDoctors = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID
                }).ToList();
                foreach (var doctor in allDoctors)
                {
                    #region Assignment to Contract

                    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)
                    {
                        Guid AssignmentID = Guid.NewGuid();
                        var  insuranceTobrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
                        {
                            Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID,
                            Tenant_RefID = securityTicket.TenantID,
                            IsDeleted    = false,
                        }).SingleOrDefault();
                        if (insuranceTobrokerContract != null)
                        {
                            AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                        }
                        else
                        {
                            var insuranceTobrokerContractNew = new ORM_HEC_CRT_InsuranceToBrokerContract();
                            insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                            insuranceTobrokerContractNew.Creation_Timestamp         = DateTime.Now;
                            insuranceTobrokerContractNew.IsDeleted                  = false;
                            insuranceTobrokerContractNew.Tenant_RefID               = securityTicket.TenantID;
                            insuranceTobrokerContractNew.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;
                            insuranceTobrokerContractNew.Save(Connection, Transaction);
                            AssignmentID = insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID;
                        }
                        var insuranceTobrokerContract2doctor = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor();
                        insuranceTobrokerContract2doctor.Creation_Timestamp = DateTime.Now;
                        insuranceTobrokerContract2doctor.HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctorID = Guid.NewGuid();
                        insuranceTobrokerContract2doctor.InsuranceToBrokerContract_RefID = AssignmentID;
                        insuranceTobrokerContract2doctor.Tenant_RefID = securityTicket.TenantID;
                        insuranceTobrokerContract2doctor.IsDeleted    = false;
                        insuranceTobrokerContract2doctor.Doctor_RefID = doctor.HEC_DoctorID;
                        insuranceTobrokerContract2doctor.ValidFrom    = new DateTime(2013, 6, 15);
                        insuranceTobrokerContract2doctor.ValidThrough = DateTime.MinValue;
                        insuranceTobrokerContract2doctor.Save(Connection, Transaction);

                        P_DO_CDCD_1505 ParameterDoctorID = new P_DO_CDCD_1505();
                        ParameterDoctorID.DoctorID = doctor.HEC_DoctorID;
                        var data = cls_Get_Doctor_Contract_Numbers.Invoke(Connection, Transaction, ParameterDoctorID, securityTicket).Result;

                        int DoctorContracts = data.Count();
                        Doctor_Contracts ParameterDoctor = new Doctor_Contracts();
                        ParameterDoctor.DocID = doctor.HEC_DoctorID;

                        Practice_Doctors_Model DoctorFound = Get_Doctors_for_PracticeID.Set_Contract_Number_for_DoctorID(ParameterDoctor, securityTicket);

                        if (DoctorFound != null)
                        {
                            List <Practice_Doctors_Model> DoctorFoundL = new List <Practice_Doctors_Model>();
                            DoctorFound.contract = DoctorContracts;
                            DoctorFoundL.Add(DoctorFound);
                            Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(DoctorFoundL, securityTicket.TenantID.ToString());
                        }


                        P_DO_GPIDfDID_1353 ParametarDocID = new P_DO_GPIDfDID_1353();
                        ParametarDocID.DoctorID = doctor.HEC_DoctorID;
                        DO_GPIDfDID_1353[] data2 = cls_Get_PracticeID_for_DoctorID.Invoke(Connection, Transaction, ParametarDocID, securityTicket).Result;

                        P_DO_GCfPID_1507 ParametarPractice = new P_DO_GCfPID_1507();

                        ParametarPractice.PracticeID = data2.First().HEC_MedicalPractiseID;
                        DO_GCfPID_1507[] Contracts       = cls_Get_all_Doctors_Contract_Assignment_for_PracticeID.Invoke(Connection, Transaction, ParametarPractice, securityTicket).Result;
                        int NumberOfContractsForPractice = Contracts.Count();
                        Practice_Doctors_Model practice  = new Practice_Doctors_Model();
                        practice.id = ParametarPractice.PracticeID.ToString();

                        Practice_Doctors_Model        PracticeFound = Get_Doctors_for_PracticeID.Get_Practice_for_PracticeID(practice, securityTicket);
                        List <Practice_Doctors_Model> practiceL     = new List <Practice_Doctors_Model>();
                        PracticeFound.contract = NumberOfContractsForPractice;
                        practiceL.Add(PracticeFound);
                        Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(practiceL, securityTicket.TenantID.ToString());
                        #endregion
                    }
                }

                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;
            }
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_MD_SCGPOSD_1306 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here

            var insuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
            {
                Ext_CMN_CTR_Contract_RefID = Parameter.ContractID,
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false
            }).SingleOrDefault();

            if (insuranceToBrokerContract == null)
            {
                insuranceToBrokerContract = new ORM_HEC_CRT_InsuranceToBrokerContract();
                insuranceToBrokerContract.Creation_Timestamp                  = DateTime.Now;
                insuranceToBrokerContract.Ext_CMN_CTR_Contract_RefID          = Parameter.ContractID;
                insuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                insuranceToBrokerContract.Modification_Timestamp              = DateTime.Now;
                insuranceToBrokerContract.Tenant_RefID = securityTicket.TenantID;

                insuranceToBrokerContract.Save(Connection, Transaction);
            }

            var allLanguages = ORM_CMN_Language.Query.Search(Connection, Transaction, new ORM_CMN_Language.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).ToArray();

            var currency = ORM_CMN_Currency.Query.Search(Connection, Transaction, new ORM_CMN_Currency.Query()
            {
                ISO4127 = "EUR", IsDeleted = false, Symbol = "EUR", Tenant_RefID = securityTicket.TenantID
            }).Single();

            #region DELETE DISCONNECTED GPOS-ES
            var currentGposesConnectedToContract = ORM_HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCode.Query.Search(Connection, Transaction, new ORM_HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCode.Query()
            {
                InsuranceToBrokerContract_RefID = insuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID,
                IsDeleted    = false,
                Tenant_RefID = securityTicket.TenantID
            });
            var gposIDs = Parameter.GposData.Select(gpos => gpos.GposID).ToArray();

            foreach (var currGpos in currentGposesConnectedToContract)
            {
                var exists = gposIDs.Any(id => currGpos.PotentialBillCode_RefID == id);
                if (!gposIDs.Any(id => id == currGpos.PotentialBillCode_RefID))
                {
                    cls_Delete_GPOS_Data.Invoke(Connection, Transaction, new P_MD_DGPOSD_1033()
                    {
                        GposID = currGpos.PotentialBillCode_RefID
                    }, securityTicket);
                }
            }
            #endregion DELETE DISCONNECTED GPOS-ES

            foreach (var gpos in Parameter.GposData)
            {
                #region NEW GPOS DATA
                if (gpos.GposID == Guid.Empty)
                {
                    #region GPOS CATALOG
                    var catalog = ORM_HEC_BIL_PotentialCode_Catalog.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_Catalog.Query()
                    {
                        GlobalPropertyMatchingID = gpos.GposType,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).SingleOrDefault();

                    if (catalog == null)
                    {
                        catalog = new ORM_HEC_BIL_PotentialCode_Catalog();
                        var catalogNameDict   = new Dict(ORM_HEC_BIL_PotentialCode_Catalog.TableName);
                        var catalogNameString = gpos.GposType.Replace("mm.docconnect.gpos.catalog.", "");
                        catalogNameString = catalogNameString.Substring(0, 1).ToUpper() + catalogNameString.Substring(1);
                        foreach (var lang in allLanguages)
                        {
                            catalogNameDict.AddEntry(lang.CMN_LanguageID, catalogNameString);
                        }
                        catalog.GlobalPropertyMatchingID = gpos.GposType;
                        catalog.Modification_Timestamp   = DateTime.Now;
                        catalog.Tenant_RefID             = securityTicket.TenantID;

                        catalog.Save(Connection, Transaction);
                    }
                    #endregion GPOS CATALOG

                    #region PRICE
                    var price = new ORM_CMN_Price();
                    price.CMN_PriceID        = Guid.NewGuid();
                    price.Creation_Timestamp = DateTime.Now;
                    price.Tenant_RefID       = securityTicket.TenantID;

                    price.Save(Connection, Transaction);

                    var priceValue = new ORM_CMN_Price_Value();
                    priceValue.CMN_Price_ValueID         = Guid.NewGuid();
                    priceValue.Creation_Timestamp        = DateTime.Now;
                    priceValue.Price_RefID               = price.CMN_PriceID;
                    priceValue.PriceValue_Amount         = gpos.FeeValue;
                    priceValue.PriceValue_Currency_RefID = currency.CMN_CurrencyID;
                    priceValue.Tenant_RefID              = securityTicket.TenantID;

                    priceValue.Save(Connection, Transaction);
                    #endregion PRICE

                    #region POTENTIAL CODE
                    var newPotentialCode = new ORM_HEC_BIL_PotentialCode();

                    var potentialCodeName = new Dict(ORM_HEC_BIL_PotentialCode.TableName);
                    foreach (var lang in allLanguages)
                    {
                        potentialCodeName.AddEntry(lang.CMN_LanguageID, gpos.GposName);
                    }

                    newPotentialCode.CodeName                    = potentialCodeName;
                    newPotentialCode.Creation_Timestamp          = DateTime.Now;
                    newPotentialCode.HEC_BIL_PotentialCodeID     = Guid.NewGuid();
                    newPotentialCode.PotentialCode_Catalog_RefID = catalog.HEC_BIL_PotentialCode_CatalogID;
                    newPotentialCode.Modification_Timestamp      = DateTime.Now;
                    newPotentialCode.Price_RefID                 = price.CMN_PriceID;
                    newPotentialCode.BillingCode                 = gpos.GposNumber;
                    newPotentialCode.Tenant_RefID                = securityTicket.TenantID;

                    newPotentialCode.Save(Connection, Transaction);
                    #endregion POTENTIAL CODE

                    #region CONTRACT CONNECTION

                    var coveredPotentialCode = new ORM_HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCode();
                    coveredPotentialCode.Creation_Timestamp = DateTime.Now;
                    coveredPotentialCode.HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCodeID = Guid.NewGuid();
                    coveredPotentialCode.InsuranceToBrokerContract_RefID = insuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                    coveredPotentialCode.Modification_Timestamp          = DateTime.Now;
                    coveredPotentialCode.PotentialBillCode_RefID         = newPotentialCode.HEC_BIL_PotentialCodeID;
                    coveredPotentialCode.Tenant_RefID = securityTicket.TenantID;

                    coveredPotentialCode.Save(Connection, Transaction);

                    #endregion CONTRACT CONNECTION

                    #region POTENTIAL CODE PROPERTIES

                    #region FROM INJECTION
                    var fromInjectionProperty = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalProperty();
                    fromInjectionProperty.Creation_Timestamp = DateTime.Now;
                    fromInjectionProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID = Guid.NewGuid();
                    fromInjectionProperty.IsValue_Number         = true;
                    fromInjectionProperty.Modification_Timestamp = DateTime.Now;
                    fromInjectionProperty.PropertyName           = "From injection no.";
                    fromInjectionProperty.Tenant_RefID           = securityTicket.TenantID;

                    fromInjectionProperty.Save(Connection, Transaction);

                    var fromInjectionPropertyToCode = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_2_UniversalProperty();
                    fromInjectionPropertyToCode.Tenant_RefID = securityTicket.TenantID;
                    fromInjectionPropertyToCode.AssignmentID = Guid.NewGuid();
                    fromInjectionPropertyToCode.CoveredPotentialBillCode_RefID = coveredPotentialCode.HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCodeID;
                    fromInjectionPropertyToCode.CoveredPotentialBillCode_UniversalProperty_RefID = fromInjectionProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID;
                    fromInjectionPropertyToCode.Creation_Timestamp     = DateTime.Now;
                    fromInjectionPropertyToCode.Modification_Timestamp = DateTime.Now;
                    fromInjectionPropertyToCode.Value_Number           = gpos.FromInjection == 0 || gpos.FromInjection == null ? int.MaxValue : gpos.FromInjection;

                    fromInjectionPropertyToCode.Save(Connection, Transaction);
                    #endregion FROM INJECTION

                    #region SERVICE FEE
                    var serviceFeeProperty = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalProperty();
                    serviceFeeProperty.Creation_Timestamp = DateTime.Now;
                    serviceFeeProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID = Guid.NewGuid();
                    serviceFeeProperty.IsValue_String         = true;
                    serviceFeeProperty.Modification_Timestamp = DateTime.Now;
                    serviceFeeProperty.PropertyName           = "Service Fee in EUR";
                    serviceFeeProperty.Tenant_RefID           = securityTicket.TenantID;

                    serviceFeeProperty.Save(Connection, Transaction);

                    var serviceFeePropertyToCode = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_2_UniversalProperty();
                    serviceFeePropertyToCode.Tenant_RefID = securityTicket.TenantID;
                    serviceFeePropertyToCode.AssignmentID = Guid.NewGuid();
                    serviceFeePropertyToCode.CoveredPotentialBillCode_RefID = coveredPotentialCode.HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCodeID;
                    serviceFeePropertyToCode.CoveredPotentialBillCode_UniversalProperty_RefID = serviceFeeProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID;
                    serviceFeePropertyToCode.Creation_Timestamp     = DateTime.Now;
                    serviceFeePropertyToCode.Modification_Timestamp = DateTime.Now;
                    serviceFeePropertyToCode.Value_String           = string.IsNullOrEmpty(gpos.ManagementFeeValue) ? "-" : gpos.ManagementFeeValue;

                    serviceFeePropertyToCode.Save(Connection, Transaction);
                    #endregion SERVICE FEE

                    #region WAIVE WITH ORDER
                    var waiveWithOrderProperty = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalProperty();
                    waiveWithOrderProperty.Creation_Timestamp = DateTime.Now;
                    waiveWithOrderProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID = Guid.NewGuid();
                    waiveWithOrderProperty.IsValue_Boolean        = true;
                    waiveWithOrderProperty.Modification_Timestamp = DateTime.Now;
                    waiveWithOrderProperty.PropertyName           = "Waive with order";
                    waiveWithOrderProperty.Tenant_RefID           = securityTicket.TenantID;

                    waiveWithOrderProperty.Save(Connection, Transaction);

                    var waiveWithOrderPropertyToCode = new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_2_UniversalProperty();
                    waiveWithOrderPropertyToCode.Tenant_RefID = securityTicket.TenantID;
                    waiveWithOrderPropertyToCode.AssignmentID = Guid.NewGuid();
                    waiveWithOrderPropertyToCode.CoveredPotentialBillCode_RefID = coveredPotentialCode.HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCodeID;
                    waiveWithOrderPropertyToCode.CoveredPotentialBillCode_UniversalProperty_RefID = waiveWithOrderProperty.HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID;
                    waiveWithOrderPropertyToCode.Creation_Timestamp     = DateTime.Now;
                    waiveWithOrderPropertyToCode.Modification_Timestamp = DateTime.Now;
                    waiveWithOrderPropertyToCode.Value_Boolean          = gpos.WaiveServiceFeeWithOrder;

                    waiveWithOrderPropertyToCode.Save(Connection, Transaction);
                    #endregion WAIVE WITH ORDER

                    #endregion POTENTIAL CODE PROPERTIES

                    #region CONNECTED DRUGS
                    if (gpos.DrugIDs.Length != 0)
                    {
                        foreach (var drugID in gpos.DrugIDs)
                        {
                            var potentialCodeToDrug = new ORM_HEC_BIL_PotentialCode_2_HealthcareProduct();
                            potentialCodeToDrug.AssignmentID                = Guid.NewGuid();
                            potentialCodeToDrug.Creation_Timestamp          = DateTime.Now;
                            potentialCodeToDrug.HEC_BIL_PotentialCode_RefID = newPotentialCode.HEC_BIL_PotentialCodeID;
                            potentialCodeToDrug.HEC_Product_RefID           = drugID;
                            potentialCodeToDrug.Modification_Timestamp      = DateTime.Now;
                            potentialCodeToDrug.Tenant_RefID                = securityTicket.TenantID;

                            potentialCodeToDrug.Save(Connection, Transaction);
                        }
                    }
                    #endregion CONNECTED DRUGS

                    #region CONNECTED DIAGNOSES
                    if (gpos.DiagnoseIDs.Length != 0)
                    {
                        foreach (var diagnoseID in gpos.DiagnoseIDs)
                        {
                            var potentialCodeToDiagnose = new ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis();
                            potentialCodeToDiagnose.AssignmentID                     = Guid.NewGuid();
                            potentialCodeToDiagnose.Creation_Timestamp               = DateTime.Now;
                            potentialCodeToDiagnose.HEC_BIL_PotentialCode_RefID      = newPotentialCode.HEC_BIL_PotentialCodeID;
                            potentialCodeToDiagnose.HEC_DIA_PotentialDiagnosis_RefID = diagnoseID;
                            potentialCodeToDiagnose.Modification_Timestamp           = DateTime.Now;
                            potentialCodeToDiagnose.Tenant_RefID                     = securityTicket.TenantID;

                            potentialCodeToDiagnose.Save(Connection, Transaction);
                        }
                    }
                    #endregion CONNECTED DIAGNOSES
                }
                #endregion NEW GPOS DATA

                #region EDIT
                else
                {
                    var currentGpos = ORM_HEC_BIL_PotentialCode.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode.Query()
                    {
                        HEC_BIL_PotentialCodeID = gpos.GposID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).SingleOrDefault();
                    if (currentGpos != null)
                    {
                        #region BASE DATA
                        var potentialCodeName = new Dict(ORM_HEC_BIL_PotentialCode.TableName);
                        foreach (var lang in allLanguages)
                        {
                            potentialCodeName.AddEntry(lang.CMN_LanguageID, gpos.GposName);
                        }
                        currentGpos.CodeName    = potentialCodeName;
                        currentGpos.BillingCode = gpos.GposNumber;

                        var catalog = ORM_HEC_BIL_PotentialCode_Catalog.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_Catalog.Query()
                        {
                            GlobalPropertyMatchingID = gpos.GposType,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        }).SingleOrDefault();

                        if (catalog == null)
                        {
                            catalog = new ORM_HEC_BIL_PotentialCode_Catalog();
                            var catalogNameDict   = new Dict(ORM_HEC_BIL_PotentialCode_Catalog.TableName);
                            var catalogNameString = gpos.GposType.Replace("mm.docconnect.gpos.catalog.", "");
                            catalogNameString = catalogNameString.Substring(0, 1).ToUpper() + catalogNameString.Substring(1);

                            foreach (var lang in allLanguages)
                            {
                                catalogNameDict.AddEntry(lang.CMN_LanguageID, catalogNameString);
                            }

                            catalog.GlobalPropertyMatchingID = gpos.GposType;
                            catalog.Modification_Timestamp   = DateTime.Now;
                            catalog.Tenant_RefID             = securityTicket.TenantID;

                            catalog.Save(Connection, Transaction);
                        }

                        currentGpos.PotentialCode_Catalog_RefID = catalog.HEC_BIL_PotentialCode_CatalogID;

                        currentGpos.Save(Connection, Transaction);
                        #endregion

                        #region PRICE
                        var currentPriceValue = ORM_CMN_Price_Value.Query.Search(Connection, Transaction, new ORM_CMN_Price_Value.Query()
                        {
                            Tenant_RefID = securityTicket.TenantID,
                            IsDeleted    = false,
                            Price_RefID  = currentGpos.Price_RefID
                        }).SingleOrDefault();

                        if (currentPriceValue != null)
                        {
                            currentPriceValue.PriceValue_Amount = gpos.FeeValue;
                            currentPriceValue.Save(Connection, Transaction);
                        }
                        #endregion

                        #region CONTRACT CONNECTION
                        var coveredPotentialCode = ORM_HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCode.Query.Search(Connection, Transaction, new ORM_HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCode.Query()
                        {
                            PotentialBillCode_RefID = gpos.GposID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        }).SingleOrDefault();
                        #endregion

                        #region POTENTIAL CODE PROPERTIES
                        var gposPropertyConnections = ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_2_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_2_UniversalProperty.Query()
                        {
                            CoveredPotentialBillCode_RefID = coveredPotentialCode.HEC_CTR_InsuranceToBrokerContracts_CoveredPotentialBillCodeID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        });

                        foreach (var conn in gposPropertyConnections)
                        {
                            var gposProperty = ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalProperty.Query()
                            {
                                HEC_CTR_I2BC_CoveredPotentialBillCodes_UniversalPropertyID = conn.CoveredPotentialBillCode_UniversalProperty_RefID,
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID
                            }).SingleOrDefault();

                            if (gposProperty != null)
                            {
                                switch (gposProperty.PropertyName)
                                {
                                case "From injection no.":
                                    conn.Value_Number = gpos.FromInjection;
                                    break;

                                case "Waive with order":
                                    conn.Value_Boolean = gpos.WaiveServiceFeeWithOrder;
                                    break;

                                case "Service Fee in EUR":
                                    conn.Value_String = gpos.ManagementFeeValue;
                                    break;
                                }

                                conn.Modification_Timestamp = DateTime.Now;
                                conn.Save(Connection, Transaction);
                            }
                        }

                        #endregion POTENTIAL CODE PROPERTIES

                        #region CONNECTED DRUGS
                        var currentGposDrugConnections = ORM_HEC_BIL_PotentialCode_2_HealthcareProduct.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_2_HealthcareProduct.Query()
                        {
                            HEC_BIL_PotentialCode_RefID = gpos.GposID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        });

                        foreach (var drugConnection in currentGposDrugConnections)
                        {
                            if (gpos.DrugIDs.Length == 0 || !gpos.DrugIDs.Any(did => did == drugConnection.HEC_Product_RefID))
                            {
                                drugConnection.IsDeleted = true;
                                drugConnection.Modification_Timestamp = DateTime.Now;

                                drugConnection.Save(Connection, Transaction);
                            }
                        }

                        foreach (var drugID in gpos.DrugIDs)
                        {
                            if (!currentGposDrugConnections.Any(cpd => cpd.HEC_Product_RefID == drugID))
                            {
                                var newDrugConnection = new ORM_HEC_BIL_PotentialCode_2_HealthcareProduct();
                                newDrugConnection.AssignmentID                = Guid.NewGuid();
                                newDrugConnection.Creation_Timestamp          = DateTime.Now;
                                newDrugConnection.HEC_BIL_PotentialCode_RefID = gpos.GposID;
                                newDrugConnection.HEC_Product_RefID           = drugID;
                                newDrugConnection.Modification_Timestamp      = DateTime.Now;
                                newDrugConnection.Tenant_RefID                = securityTicket.TenantID;

                                newDrugConnection.Save(Connection, Transaction);
                            }
                        }

                        #endregion CONNECTED DRUGS

                        #region CONNECTED DIAGNOSES
                        var currentGposDiagnoseConnections = ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis.Query()
                        {
                            HEC_BIL_PotentialCode_RefID = gpos.GposID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        });

                        foreach (var diagnoseConnection in currentGposDiagnoseConnections)
                        {
                            if (gpos.DiagnoseIDs.Length == 0 || !gpos.DiagnoseIDs.Any(did => did == diagnoseConnection.HEC_DIA_PotentialDiagnosis_RefID))
                            {
                                diagnoseConnection.IsDeleted = true;
                                diagnoseConnection.Modification_Timestamp = DateTime.Now;

                                diagnoseConnection.Save(Connection, Transaction);
                            }
                        }

                        foreach (var diagnoseID in gpos.DiagnoseIDs)
                        {
                            if (!currentGposDiagnoseConnections.Any(cpd => cpd.HEC_DIA_PotentialDiagnosis_RefID == diagnoseID))
                            {
                                var newDiagnoseConnection = new ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis();
                                newDiagnoseConnection.AssignmentID                     = Guid.NewGuid();
                                newDiagnoseConnection.Creation_Timestamp               = DateTime.Now;
                                newDiagnoseConnection.HEC_BIL_PotentialCode_RefID      = gpos.GposID;
                                newDiagnoseConnection.HEC_DIA_PotentialDiagnosis_RefID = diagnoseID;
                                newDiagnoseConnection.Modification_Timestamp           = DateTime.Now;
                                newDiagnoseConnection.Tenant_RefID                     = securityTicket.TenantID;

                                newDiagnoseConnection.Save(Connection, Transaction);
                            }
                        }
                        #endregion CONNECTED DIAGNOSES
                    }
                }
                #endregion EDIT
            }

            return(returnValue);

            #endregion UserCode
        }
Esempio n. 4
0
        public static void Save_Doctors_to_DB(Doctor_model_from_xlsx Parameter, 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
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
                Guid   BusinessParticipantID         = Guid.NewGuid();
                Guid   personInfoID                  = Guid.NewGuid();
                Guid   PracticeCustomerID            = Guid.NewGuid();
                Guid   PracticeBusinessParticipantID = Guid.NewGuid();
                Guid   PracticeCompanyInfoID         = Guid.NewGuid();
                String PracticeName                  = "";
                Guid   BankAccountID                 = Guid.Empty;
                Guid   doctor_id    = Parameter.DoctorID;
                var    isOpPractice = false;

                if (!String.IsNullOrEmpty(Parameter.LoginEmail))
                //uncomment this if you've created account
                //  if (false)
                {
                    string[] stringUser  = Parameter.LoginEmail.Split('@');
                    string   usernameStr = stringUser[0];

                    try
                    {
                        var doctorAccountInfo = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            AccountSignInEmailAddress = Parameter.LoginEmail,
                        }).Single();

                        var accountGroupQuery = new ORM_USR_Account_FunctionLevelRights_Group.Query();
                        accountGroupQuery.Tenant_RefID             = securityTicket.TenantID;
                        accountGroupQuery.IsDeleted                = false;
                        accountGroupQuery.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";

                        var accountGroup = ORM_USR_Account_FunctionLevelRights_Group.Query.Search(Connection, Transaction, accountGroupQuery).SingleOrDefault();

                        if (accountGroup == null)
                        {
                            accountGroup = new ORM_USR_Account_FunctionLevelRights_Group();
                            accountGroup.Tenant_RefID             = securityTicket.TenantID;
                            accountGroup.Label                    = "mm.docconect.doc.app.group";
                            accountGroup.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";
                            accountGroup.Creation_Timestamp       = DateTime.Now;
                            accountGroup.USR_Account_FunctionLevelRights_GroupID = Guid.NewGuid();
                            accountGroup.Save(Connection, Transaction);
                        }

                        var PracticeAccount2UniversalProperty = ORM_HEC_MedicalPractice_2_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_2_UniversalProperty.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            HEC_MedicalPractice_RefID = Parameter.PracticeID
                        }).ToList();

                        List <ORM_HEC_MedicalPractice_UniversalProperty> PracticeUniversalPropertyList = new List <ORM_HEC_MedicalPractice_UniversalProperty>();
                        foreach (var item in PracticeAccount2UniversalProperty)
                        {
                            var PracticeUniversalProperty = ORM_HEC_MedicalPractice_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_UniversalProperty.Query()
                            {
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID,
                                HEC_MedicalPractice_UniversalPropertyID = item.HEC_MedicalPractice_UniversalProperty_RefID
                            }).Single();
                            PracticeUniversalPropertyList.Add(PracticeUniversalProperty);
                        }
                        ;

                        P_DO_GPAIDfPID_1522 practiceAccountIDParameter = new P_DO_GPAIDfPID_1522();
                        practiceAccountIDParameter.PracticeID = Parameter.PracticeID;

                        var practiceAccountToFunctionLevelRightQ = new ORM_USR_Account_2_FunctionLevelRight.Query();
                        practiceAccountToFunctionLevelRightQ.Account_RefID = cls_Get_Practice_AccountID_for_PracticeID.Invoke(Connection, Transaction, practiceAccountIDParameter, securityTicket).Result.accountID;
                        practiceAccountToFunctionLevelRightQ.Tenant_RefID  = securityTicket.TenantID;
                        practiceAccountToFunctionLevelRightQ.IsDeleted     = false;

                        var practiceAccountToFunctionLevelRight = ORM_USR_Account_2_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountToFunctionLevelRightQ).SingleOrDefault();

                        if (practiceAccountToFunctionLevelRight != null)
                        {
                            var practiceAccountFunctionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                            practiceAccountFunctionLevelRightQ.Tenant_RefID = securityTicket.TenantID;
                            practiceAccountFunctionLevelRightQ.IsDeleted    = false;
                            practiceAccountFunctionLevelRightQ.USR_Account_FunctionLevelRightID = practiceAccountToFunctionLevelRight.FunctionLevelRight_RefID;

                            var practiceAccountFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountFunctionLevelRightQ).SingleOrDefault();

                            if (practiceAccountFunctionLevelRight != null)
                            {
                                isOpPractice = practiceAccountFunctionLevelRight.GlobalPropertyMatchingID.Equals("mm.docconect.doc.app.op.practice");
                            }
                        }

                        var functionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                        functionLevelRightQ.Tenant_RefID             = securityTicket.TenantID;
                        functionLevelRightQ.IsDeleted                = false;
                        functionLevelRightQ.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                        var existingFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, functionLevelRightQ).SingleOrDefault();

                        var tempFunctionLevelRightID = Guid.Empty;

                        if (existingFunctionLevelRight == null)
                        {
                            ORM_USR_Account_FunctionLevelRight functionLevelRight = new ORM_USR_Account_FunctionLevelRight();
                            functionLevelRight.USR_Account_FunctionLevelRightID = Guid.NewGuid();
                            functionLevelRight.FunctionLevelRights_Group_RefID  = accountGroup.USR_Account_FunctionLevelRights_GroupID;
                            functionLevelRight.Tenant_RefID       = securityTicket.TenantID;
                            functionLevelRight.Creation_Timestamp = DateTime.Now;

                            functionLevelRight.RightName = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";
                            functionLevelRight.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                            functionLevelRight.Save(Connection, Transaction);

                            tempFunctionLevelRightID = functionLevelRight.USR_Account_FunctionLevelRightID;
                        }
                        else
                        {
                            tempFunctionLevelRightID = existingFunctionLevelRight.USR_Account_FunctionLevelRightID;
                        }

                        var accountToFunctionLevelRight = new ORM_USR_Account_2_FunctionLevelRight();
                        accountToFunctionLevelRight.Tenant_RefID             = securityTicket.TenantID;
                        accountToFunctionLevelRight.Creation_Timestamp       = DateTime.Now;
                        accountToFunctionLevelRight.AssignmentID             = Guid.NewGuid();
                        accountToFunctionLevelRight.Account_RefID            = doctorAccountInfo.USR_AccountID;
                        accountToFunctionLevelRight.FunctionLevelRight_RefID = tempFunctionLevelRightID;

                        accountToFunctionLevelRight.Save(Connection, Transaction);

                        var businessParticipantQ = new ORM_CMN_BPT_BusinessParticipant.Query();

                        businessParticipantQ.IsDeleted    = false;
                        businessParticipantQ.Tenant_RefID = securityTicket.TenantID;
                        businessParticipantQ.CMN_BPT_BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;
                        BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;

                        var DoctorBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQ).Single();
                        DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                        DoctorBusinessParticipant.DisplayName            = Parameter.FirstName + " " + Parameter.LastNAme;
                        DoctorBusinessParticipant.IsNaturalPerson        = true;
                        DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                        DoctorBusinessParticipant.Save(Connection, Transaction);
                        personInfoID = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;


                        var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                        companyInfoPractice.IsDeleted            = false;
                        companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                        companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                        companyInfoPractice.FirstName            = Parameter.FirstName;
                        companyInfoPractice.LastName             = Parameter.LastNAme;
                        companyInfoPractice.Salutation_General   = Parameter.Salutation;
                        companyInfoPractice.Title = Parameter.Title;
                        companyInfoPractice.Save(Connection, Transaction);

                        var communicationContact = new ORM_CMN_PER_CommunicationContact();
                        communicationContact.IsDeleted              = false;
                        communicationContact.Contact_Type           = Guid.NewGuid();
                        communicationContact.Tenant_RefID           = securityTicket.TenantID;
                        communicationContact.Modification_Timestamp = DateTime.Now;
                        communicationContact.PersonInfo_RefID       = personInfoID;
                        communicationContact.Content = Parameter.Email;
                        communicationContact.Save(Connection, Transaction);
                        Guid CommunicationContactTypeID = communicationContact.Contact_Type;


                        var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                        communicationContactType.IsDeleted    = false;
                        communicationContactType.Tenant_RefID = securityTicket.TenantID;
                        communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                        communicationContactType.Type = "Email";
                        communicationContactType.Save(Connection, Transaction);

                        var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                        communicationContact2.IsDeleted              = false;
                        communicationContact2.Contact_Type           = Guid.NewGuid();
                        communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                        communicationContact2.Modification_Timestamp = DateTime.Now;
                        communicationContact2.PersonInfo_RefID       = personInfoID;
                        communicationContact2.Content = Parameter.Phone;
                        communicationContact2.Save(Connection, Transaction);
                        Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                        var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                        communicationContactType2.IsDeleted    = false;
                        communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                        communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                        communicationContactType2.Type = "Phone";
                        communicationContactType2.Save(Connection, Transaction);

                        var doctor = new ORM_HEC_Doctor();
                        doctor.HEC_DoctorID = Guid.NewGuid();
                        doctor.IsDeleted    = false;
                        doctor.Tenant_RefID = securityTicket.TenantID;
                        doctor.BusinessParticipant_RefID = BusinessParticipantID;
                        doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                        doctor.Account_RefID             = Parameter.account_id;

                        doctor.Save(Connection, Transaction);

                        doctor_id = doctor.HEC_DoctorID;

                        var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                        }).Single();


                        var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                        organizationalunit_Staff.IsDeleted    = false;
                        organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                        organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                        organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                        organizationalunit_Staff.Save(Connection, Transaction);

                        var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                        {
                            IsDeleted              = false,
                            Tenant_RefID           = securityTicket.TenantID,
                            CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                        }).Single();
                        var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                        }).Single();

                        PracticeName = PracticeBusinessParticipant.DisplayName;
                        PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                        PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;

                        if (Parameter.IsUsePracticeBank)
                        {
                            var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                            {
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID,
                                CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                            }).Single();


                            var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                            business2bankAccount.IsDeleted    = false;
                            business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                            business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                            business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                            business2bankAccount.Creation_Timestamp = DateTime.Now;
                            business2bankAccount.Save(Connection, Transaction);

                            BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                            //end of save bank data if inherited from practice
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                            {
                                var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                                business2bankAccount.IsDeleted    = false;
                                business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                                business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                                business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                                business2bankAccount.Creation_Timestamp = DateTime.Now;
                                business2bankAccount.Save(Connection, Transaction);

                                var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                                bankAccountDoctor.IsDeleted             = false;
                                bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                                bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                                bankAccountDoctor.OwnerText             = Parameter.AccountHolder;
                                bankAccountDoctor.IBAN               = Parameter.IBAN;
                                bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                                bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                                bankAccountDoctor.Save(Connection, Transaction);

                                if (!String.IsNullOrEmpty(Parameter.Bank))
                                {
                                    var bank = new ORM_ACC_BNK_Bank();
                                    bank.IsDeleted          = false;
                                    bank.Tenant_RefID       = securityTicket.TenantID;
                                    bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                                    bank.BICCode            = Parameter.Bic;
                                    bank.BankName           = Parameter.Bank;
                                    bank.Creation_Timestamp = DateTime.Now;
                                    bank.Save(Connection, Transaction);
                                }

                                BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                                // end save bank data
                            }
                        }
                    }
                    catch
                    {
                        throw new Exception();
                    }
                }
                else
                {
                    var DoctorBusinessParticipant = new ORM_CMN_BPT_BusinessParticipant();

                    DoctorBusinessParticipant.IsDeleted    = false;
                    DoctorBusinessParticipant.Tenant_RefID = securityTicket.TenantID;
                    DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID            = Guid.NewGuid();
                    DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                    DoctorBusinessParticipant.DisplayName            = Parameter.FirstName + " " + Parameter.LastNAme;
                    DoctorBusinessParticipant.IsNaturalPerson        = true;
                    DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                    DoctorBusinessParticipant.Save(Connection, Transaction);
                    personInfoID          = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                    BusinessParticipantID = DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID;

                    var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                    companyInfoPractice.IsDeleted            = false;
                    companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                    companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                    companyInfoPractice.FirstName            = Parameter.FirstName;
                    companyInfoPractice.LastName             = Parameter.LastNAme;
                    companyInfoPractice.Salutation_General   = Parameter.Salutation;
                    companyInfoPractice.Title = Parameter.Title;
                    companyInfoPractice.Save(Connection, Transaction);

                    var communicationContact = new ORM_CMN_PER_CommunicationContact();
                    communicationContact.IsDeleted              = false;
                    communicationContact.Contact_Type           = Guid.NewGuid();
                    communicationContact.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact.Modification_Timestamp = DateTime.Now;
                    communicationContact.PersonInfo_RefID       = personInfoID;
                    communicationContact.Content = Parameter.Email;
                    communicationContact.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID = communicationContact.Contact_Type;

                    var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType.IsDeleted    = false;
                    communicationContactType.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                    communicationContactType.Type = "Email";
                    communicationContactType.Save(Connection, Transaction);

                    var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                    communicationContact2.IsDeleted              = false;
                    communicationContact2.Contact_Type           = Guid.NewGuid();
                    communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact2.Modification_Timestamp = DateTime.Now;
                    communicationContact2.PersonInfo_RefID       = personInfoID;
                    communicationContact2.Content = Parameter.Phone;
                    communicationContact2.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                    var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType2.IsDeleted    = false;
                    communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                    communicationContactType2.Type = "Phone";
                    communicationContactType2.Save(Connection, Transaction);

                    var doctor = new ORM_HEC_Doctor();
                    doctor.HEC_DoctorID = Guid.NewGuid();
                    doctor.IsDeleted    = false;
                    doctor.Tenant_RefID = securityTicket.TenantID;
                    doctor.BusinessParticipant_RefID = BusinessParticipantID;
                    doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                    doctor.Account_RefID             = Parameter.account_id;

                    doctor.Save(Connection, Transaction);

                    doctor_id = doctor.HEC_DoctorID;

                    var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                    }).Single();


                    var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                    organizationalunit_Staff.IsDeleted    = false;
                    organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                    organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                    organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                    organizationalunit_Staff.Save(Connection, Transaction);


                    var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                    {
                        IsDeleted              = false,
                        Tenant_RefID           = securityTicket.TenantID,
                        CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                    }).Single();
                    var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                    }).Single();
                    PracticeName = PracticeBusinessParticipant.DisplayName;
                    PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                    PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                    if (Parameter.IsUsePracticeBank == true)
                    {
                        var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                        }).Single();


                        var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                        business2bankAccount.IsDeleted    = false;
                        business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                        business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                        business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        business2bankAccount.Creation_Timestamp = DateTime.Now;
                        business2bankAccount.Save(Connection, Transaction);

                        BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        //end of save bank data if inherited from practice
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                        {
                            var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                            business2bankAccount.IsDeleted    = false;
                            business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                            business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                            business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                            business2bankAccount.Creation_Timestamp = DateTime.Now;
                            business2bankAccount.Save(Connection, Transaction);

                            var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                            bankAccountDoctor.IsDeleted             = false;
                            bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                            bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            bankAccountDoctor.OwnerText             = Parameter.AccountHolder;
                            bankAccountDoctor.IBAN               = Parameter.IBAN;
                            bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                            bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                            bankAccountDoctor.Save(Connection, Transaction);

                            if (!String.IsNullOrEmpty(Parameter.Bank))
                            {
                                var bank = new ORM_ACC_BNK_Bank();
                                bank.IsDeleted          = false;
                                bank.Tenant_RefID       = securityTicket.TenantID;
                                bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                                bank.BICCode            = Parameter.Bic;
                                bank.BankName           = Parameter.Bank;
                                bank.Creation_Timestamp = DateTime.Now;
                                bank.Save(Connection, Transaction);
                            }

                            BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            // end save bank data
                        }
                    }
                }
                var PracticeCompanyInfoAddress = ORM_CMN_COM_CompanyInfo_Address.Query.Search(Connection, Transaction, new ORM_CMN_COM_CompanyInfo_Address.Query()
                {
                    IsDeleted           = false,
                    Tenant_RefID        = securityTicket.TenantID,
                    CompanyInfo_RefID   = PracticeCompanyInfoID,
                    Address_Description = "Standard address for billing, shipping",
                }).SingleOrDefault();



                Practice_Doctors_Model DPModel = new Practice_Doctors_Model();

                if (PracticeCompanyInfoAddress != null)
                {
                    var PracticeUCD = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, new ORM_CMN_UniversalContactDetail.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_UniversalContactDetailID = PracticeCompanyInfoAddress.Address_UCD_RefID,
                    }).SingleOrDefault();
                    DPModel.address = PracticeUCD.Street_Name + " " + PracticeUCD.Street_Number;
                    DPModel.zip     = PracticeUCD.ZIP;
                    DPModel.city    = PracticeUCD.Town;
                }

                DPModel.account_status = "aktiv";
                DPModel.id             = doctor_id.ToString();

                var title = string.IsNullOrEmpty(Parameter.Title) ? "" : Parameter.Title.Trim();

                DPModel.name              = title + " " + Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.name_untouched    = Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.bsnr_lanr         = Parameter.LANR.ToString();
                DPModel.autocomplete_name = title + " " + Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.salutation        = title;

                DPModel.type = "Doctor";

                DPModel.bank = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;

                DPModel.bank_untouched = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;


                DPModel.phone = Parameter.Phone;

                DPModel.email = string.IsNullOrEmpty(Parameter.Email) ? "" : Parameter.Email;

                DPModel.iban = string.IsNullOrEmpty(Parameter.IBAN) ? "" : Parameter.IBAN;

                DPModel.bic = string.IsNullOrEmpty(Parameter.Bic) ? "" : Parameter.Bic;

                DPModel.bank_id             = BankAccountID.ToString();
                DPModel.bank_info_inherited = Parameter.IsUsePracticeBank;
                DPModel.aditional_info      = "";
                DPModel.contract            = 0;


                DPModel.tenantid = securityTicket.TenantID.ToString();
                DPModel.practice_name_for_doctor = PracticeName;
                DPModel.practice_for_doctor_id   = Parameter.PracticeID.ToString();

                DPModel.role = isOpPractice ? "op" : "ac";

                List <Practice_Doctors_Model> DPModelL = new List <Practice_Doctors_Model>();
                DPModelL.Add(DPModel);

                Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(DPModelL, securityTicket.TenantID.ToString());

                #region Assignment to Contract

                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)
                {
                    Guid AssignmentID = Guid.NewGuid();
                    var  insuranceTobrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
                    {
                        Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID,
                        Tenant_RefID = securityTicket.TenantID,
                        IsDeleted    = false,
                    }).SingleOrDefault();
                    if (insuranceTobrokerContract != null)
                    {
                        AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                    }
                    else
                    {
                        var insuranceTobrokerContractNew = new ORM_HEC_CRT_InsuranceToBrokerContract();
                        insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                        insuranceTobrokerContractNew.Creation_Timestamp         = DateTime.Now;
                        insuranceTobrokerContractNew.IsDeleted                  = false;
                        insuranceTobrokerContractNew.Tenant_RefID               = securityTicket.TenantID;
                        insuranceTobrokerContractNew.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;
                        insuranceTobrokerContractNew.Save(Connection, Transaction);
                        AssignmentID = insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID;
                    }
                    var insuranceTobrokerContract2doctor = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor();
                    insuranceTobrokerContract2doctor.Creation_Timestamp = DateTime.Now;
                    insuranceTobrokerContract2doctor.HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctorID = Guid.NewGuid();
                    insuranceTobrokerContract2doctor.InsuranceToBrokerContract_RefID = AssignmentID;
                    insuranceTobrokerContract2doctor.Tenant_RefID = securityTicket.TenantID;
                    insuranceTobrokerContract2doctor.IsDeleted    = false;
                    insuranceTobrokerContract2doctor.Doctor_RefID = doctor_id;
                    insuranceTobrokerContract2doctor.ValidFrom    = new DateTime(2013, 6, 15);
                    insuranceTobrokerContract2doctor.ValidThrough = DateTime.MinValue;
                    insuranceTobrokerContract2doctor.Save(Connection, Transaction);

                    P_DO_CDCD_1505 ParameterDoctorID = new P_DO_CDCD_1505();
                    ParameterDoctorID.DoctorID = doctor_id;
                    var data = cls_Get_Doctor_Contract_Numbers.Invoke(Connection, Transaction, ParameterDoctorID, securityTicket).Result;

                    int DoctorContracts = data.Count();
                    Doctor_Contracts ParameterDoctor = new Doctor_Contracts();
                    ParameterDoctor.DocID = doctor_id;

                    Practice_Doctors_Model DoctorFound = Get_Doctors_for_PracticeID.Set_Contract_Number_for_DoctorID(ParameterDoctor, securityTicket);

                    if (DoctorFound != null)
                    {
                        List <Practice_Doctors_Model> DoctorFoundL = new List <Practice_Doctors_Model>();
                        DoctorFound.contract = DoctorContracts;
                        DoctorFoundL.Add(DoctorFound);
                        Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(DoctorFoundL, securityTicket.TenantID.ToString());
                    }


                    P_DO_GPIDfDID_1353 ParametarDocID = new P_DO_GPIDfDID_1353();
                    ParametarDocID.DoctorID = doctor_id;
                    DO_GPIDfDID_1353[] data2 = cls_Get_PracticeID_for_DoctorID.Invoke(Connection, Transaction, ParametarDocID, securityTicket).Result;

                    P_DO_GCfPID_1507 ParametarPractice = new P_DO_GCfPID_1507();

                    ParametarPractice.PracticeID = data2.First().HEC_MedicalPractiseID;
                    DO_GCfPID_1507[] Contracts       = cls_Get_all_Doctors_Contract_Assignment_for_PracticeID.Invoke(Connection, Transaction, ParametarPractice, securityTicket).Result;
                    int NumberOfContractsForPractice = Contracts.Count();
                    Practice_Doctors_Model practice  = new Practice_Doctors_Model();
                    practice.id = ParametarPractice.PracticeID.ToString();

                    Practice_Doctors_Model        PracticeFound = Get_Doctors_for_PracticeID.Get_Practice_for_PracticeID(practice, securityTicket);
                    List <Practice_Doctors_Model> practiceL     = new List <Practice_Doctors_Model>();
                    PracticeFound.contract = NumberOfContractsForPractice;
                    practiceL.Add(PracticeFound);
                    Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(practiceL, securityTicket.TenantID.ToString());
                }
                #endregion



                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;
            }
        }
Esempio n. 5
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
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_DO_SDtC_1228 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var  returnValue  = new FR_Guid();
            Guid AssignmentID = Guid.Empty;

            if (Parameter.DoctorAssignment == Guid.Empty)
            {
                var insuranceTobrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
                {
                    Ext_CMN_CTR_Contract_RefID = Parameter.ContractID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).SingleOrDefault();

                if (insuranceTobrokerContract != null)
                {
                    AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                }
                else
                {
                    insuranceTobrokerContract = new ORM_HEC_CRT_InsuranceToBrokerContract();
                    insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                    insuranceTobrokerContract.Creation_Timestamp         = DateTime.Now;
                    insuranceTobrokerContract.IsDeleted                  = false;
                    insuranceTobrokerContract.Tenant_RefID               = securityTicket.TenantID;
                    insuranceTobrokerContract.Ext_CMN_CTR_Contract_RefID = Parameter.ContractID;
                    insuranceTobrokerContract.Save(Connection, Transaction);

                    AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                }

                var insuranceTobrokerContract2doctor = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor();
                insuranceTobrokerContract2doctor.Creation_Timestamp = DateTime.Now;
                insuranceTobrokerContract2doctor.HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctorID = Guid.NewGuid();
                insuranceTobrokerContract2doctor.InsuranceToBrokerContract_RefID = AssignmentID;
                insuranceTobrokerContract2doctor.Tenant_RefID = securityTicket.TenantID;
                insuranceTobrokerContract2doctor.IsDeleted    = false;
                insuranceTobrokerContract2doctor.Doctor_RefID = Parameter.DoctorID;
                insuranceTobrokerContract2doctor.ValidFrom    = Parameter.ValidFrom;
                insuranceTobrokerContract2doctor.ValidThrough = Parameter.ValidThrough;

                insuranceTobrokerContract2doctor.Save(Connection, Transaction);
            }
            else
            {
                var insuranceTobrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
                {
                    Ext_CMN_CTR_Contract_RefID = Parameter.ContractID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();

                AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;

                var insuranceTobrokerContract2doctor = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor.Query()
                {
                    HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctorID = Parameter.DoctorAssignment,
                    InsuranceToBrokerContract_RefID = AssignmentID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    Doctor_RefID = Parameter.DoctorID
                }).Single();

                insuranceTobrokerContract2doctor.Modification_Timestamp = DateTime.Now;
                insuranceTobrokerContract2doctor.Doctor_RefID           = Parameter.DoctorID;
                insuranceTobrokerContract2doctor.ValidFrom    = Parameter.ValidFrom;
                insuranceTobrokerContract2doctor.ValidThrough = Parameter.ValidThrough;

                insuranceTobrokerContract2doctor.Save(Connection, Transaction);
            }

            var data = cls_Check_Doctor_Contracts_Dates.Invoke(Connection, Transaction, new P_DO_CDCD_1505()
            {
                DoctorID = Parameter.DoctorID
            }, securityTicket).Result;

            int DoctorContracts = data.Length;

            Practice_Doctors_Model DoctorFound = Get_Doctors_for_PracticeID.Set_Contract_Number_for_DoctorID(new Doctor_Contracts()
            {
                DocID = Parameter.DoctorID
            }, securityTicket);

            if (DoctorFound != null)
            {
                List <Practice_Doctors_Model> DoctorFoundL = new List <Practice_Doctors_Model>();
                DoctorFound.contract = DoctorContracts;
                DoctorFoundL.Add(DoctorFound);
                Add_New_Practice.Import_Practice_Data_to_ElasticDB(DoctorFoundL, securityTicket.TenantID.ToString());
            }

            P_DO_GPIDfDID_1353 ParametarDocID = new P_DO_GPIDfDID_1353();
            ParametarDocID.DoctorID = Parameter.DoctorID;
            DO_GPIDfDID_1353[] data2 = cls_Get_PracticeID_for_DoctorID.Invoke(Connection, Transaction, ParametarDocID, securityTicket).Result;

            P_DO_GCfPID_1507 ParametarPractice = new P_DO_GCfPID_1507();

            ParametarPractice.PracticeID = data2.First().HEC_MedicalPractiseID;
            DO_GCfPID_1507[] Contracts       = cls_Get_all_Doctors_Contract_Assignment_for_PracticeID.Invoke(Connection, Transaction, ParametarPractice, securityTicket).Result;
            int NumberOfContractsForPractice = Contracts.Count();
            Practice_Doctors_Model practice  = new Practice_Doctors_Model();
            practice.id = ParametarPractice.PracticeID.ToString();

            Practice_Doctors_Model        PracticeFound = Get_Doctors_for_PracticeID.Get_Practice_for_PracticeID(practice, securityTicket);
            List <Practice_Doctors_Model> practiceL     = new List <Practice_Doctors_Model>();
            PracticeFound.contract = NumberOfContractsForPractice;
            practiceL.Add(PracticeFound);
            Add_New_Practice.Import_Practice_Data_to_ElasticDB(practiceL, securityTicket.TenantID.ToString());

            return(returnValue);

            #endregion UserCode
        }
Esempio n. 7
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_MD_SC_1653 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            var contractID = Guid.Empty;

            #region NEW CONTRACT
            if (Parameter.ContractID == Guid.Empty)
            {
                ORM_CMN_CTR_Contract contract = new ORM_CMN_CTR_Contract()
                {
                    ContractName           = Parameter.ContractName,
                    CMN_CTR_ContractID     = Guid.NewGuid(),
                    Creation_Timestamp     = DateTime.Now,
                    Modification_Timestamp = DateTime.Now,
                    Tenant_RefID           = securityTicket.TenantID,
                    ValidFrom    = Parameter.ValidFrom,
                    ValidThrough = Parameter.ValidThrough
                };

                contract.Save(Connection, Transaction);

                contractID = contract.CMN_CTR_ContractID;

                var insuranceToBrokerContract = new ORM_HEC_CRT_InsuranceToBrokerContract();
                insuranceToBrokerContract.Creation_Timestamp                  = DateTime.Now;
                insuranceToBrokerContract.Ext_CMN_CTR_Contract_RefID          = contractID;
                insuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                insuranceToBrokerContract.Modification_Timestamp              = DateTime.Now;
                insuranceToBrokerContract.Tenant_RefID = securityTicket.TenantID;

                insuranceToBrokerContract.Save(Connection, Transaction);
            }
            #endregion

            #region EDIT CONTRACT
            else
            {
                contractID = Parameter.ContractID;

                var contract = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                {
                    CMN_CTR_ContractID = Parameter.ContractID,
                    Tenant_RefID       = securityTicket.TenantID,
                    IsDeleted          = false
                }).SingleOrDefault();

                if (contract != null)
                {
                    contract.ContractName = Parameter.ContractName;
                    contract.ValidFrom    = Parameter.ValidFrom;
                    contract.ValidThrough = Parameter.ValidThrough;

                    contract.Save(Connection, Transaction);
                }
            }
            #endregion

            #region UPDATE COVERED DRUGS

            if (Parameter.CoveredDrugIDs != null)
            {
                cls_Save_Contract_Covered_Drugs.Invoke(Connection, Transaction, new P_MD_SCCD_1811()
                {
                    ContractID = contractID, DrugIDs = Parameter.CoveredDrugIDs
                }, securityTicket);
            }

            #endregion

            #region UPDATE COVERED DIAGNOSES

            if (Parameter.CoveredDiagnoseIDs != null)
            {
                cls_Save_Contract_Covered_Diagnoses.Invoke(Connection, Transaction, new P_MD_SCCD_1854()
                {
                    ContractID = contractID, DiagnoseIDs = Parameter.CoveredDiagnoseIDs
                }, securityTicket);
            }

            #endregion

            #region UPDATE GPOSES

            if (Parameter.GposData != null)
            {
                Parameter.GposData.ContractID = contractID;
                cls_Save_Contract_GPOS_Data.Invoke(Connection, Transaction, Parameter.GposData, securityTicket);
            }

            #endregion UPDATE GPOSES

            #region UPDATE CONTRACT PARAMETERS

            if (Parameter.DueDates != null)
            {
                cls_Save_Contract_Due_Dates.Invoke(Connection, Transaction, new P_MD_SCDD_1729()
                {
                    ContractID = contractID, DueDates = Parameter.DueDates
                }, securityTicket);
            }

            #endregion

            #region UPDATE HIPS

            if (Parameter.ParticipatingHIPs != null)
            {
                cls_Save_Contract_Participating_HIPs.Invoke(Connection, Transaction, new P_MD_SCPHIPs_1341()
                {
                    ContractID = contractID, HipIDs = Parameter.ParticipatingHIPs
                }, securityTicket);
            }

            #endregion UPDATE HIPS

            #region UPDATE DOCTORS

            if (Parameter.ParticipatingDoctors != null && Parameter.ParticipatingDoctors.Length != 0)
            {
                cls_Save_Contract_Participating_Doctors.Invoke(Connection, Transaction, new P_MD_SCPD_1341()
                {
                    ContractID = contractID, ParticipatingDoctors = Parameter.ParticipatingDoctors
                }, securityTicket);
            }

            #endregion

            #region UPDATE ELASTIC
            if (Parameter.DueDates != null)
            {
                var validUntilParam = Parameter.DueDates.Where(t => t.Name == "Duration of participation consent – Month").SingleOrDefault();
                var aftercareParam  = Parameter.DueDates.Where(t => t.Name == "Number of days between surgery and aftercare - Days").SingleOrDefault();
                if (validUntilParam != null && aftercareParam != null)
                {
                    var validUntil = !validUntilParam.IsActive ? double.MaxValue : validUntilParam.Value;

                    var aftercareDays = !aftercareParam.IsActive ? double.MaxValue : aftercareParam.Value;

                    var patientDetailsList = Retrieve_Patients.GetPatientDetailsListForContractID(Parameter.ContractID.ToString(), securityTicket);
                    if (patientDetailsList.Any())
                    {
                        Add_New_Patient.ImportPatientDetailsToElastic(patientDetailsList.Select(item =>
                        {
                            var validUntilDate = validUntil == double.MaxValue ? DateTime.MaxValue : item.date.AddMonths(Convert.ToInt32(validUntil));
                            if (aftercareDays != double.MaxValue)
                            {
                                validUntilDate = validUntilDate.AddDays(-aftercareDays);
                            }
                            var validUntilStr = validUntilDate == DateTime.MaxValue ? "∞" : validUntilDate.ToString("dd.MM.yyyy");

                            item.diagnose_or_medication = Properties.Resources.participarionConsent + " " + Parameter.ContractName + ", " + Properties.Resources.goodUntil + " " + validUntilStr;
                            return(item);
                        }).ToList(),
                                                                      securityTicket.TenantID.ToString());
                    }
                }
            }
            #endregion

            returnValue.Result = contractID;
            return(returnValue);

            #endregion UserCode
        }
Esempio n. 8
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_MD_CC_1039 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here

            #region NEW CONTRACT
            var contractToCopy = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
            {
                CMN_CTR_ContractID = Parameter.ContractID,
                Tenant_RefID       = securityTicket.TenantID,
                IsDeleted          = false
            }).SingleOrDefault();

            var newContractName      = "Copy of " + contractToCopy.ContractName;
            var existingContractName = cls_Get_Existing_ContractName_for_ContractName.Invoke(Connection, Transaction, new P_MD_GECNfCN_1119()
            {
                ContractName = newContractName + "%"
            }, securityTicket).Result;
            if (existingContractName != null)
            {
                var existingName = existingContractName.ContractName.Substring(newContractName.Length).Trim();
                try
                {
                    newContractName += Convert.ToInt32(existingContractName.ContractName.Substring(newContractName.Length).Trim()) + " " + 1;
                }
                catch (Exception ex)
                {
                    newContractName += " " + 1;
                }
            }

            ORM_CMN_CTR_Contract contract = new ORM_CMN_CTR_Contract()
            {
                ContractName           = newContractName,
                CMN_CTR_ContractID     = Guid.NewGuid(),
                Creation_Timestamp     = DateTime.Now,
                Modification_Timestamp = DateTime.Now,
                Tenant_RefID           = securityTicket.TenantID,
                ValidFrom    = contractToCopy.ValidFrom,
                ValidThrough = contractToCopy.ValidThrough
            };

            contract.Save(Connection, Transaction);

            var contractID = contract.CMN_CTR_ContractID;

            var insuranceToBrokerContract = new ORM_HEC_CRT_InsuranceToBrokerContract();
            insuranceToBrokerContract.Creation_Timestamp                  = DateTime.Now;
            insuranceToBrokerContract.Ext_CMN_CTR_Contract_RefID          = contractID;
            insuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
            insuranceToBrokerContract.Modification_Timestamp              = DateTime.Now;
            insuranceToBrokerContract.Tenant_RefID = securityTicket.TenantID;

            insuranceToBrokerContract.Save(Connection, Transaction);
            #endregion

            #region UPDATE COVERED DRUGS
            var CoveredDrugs = cls_Get_All_Drugs_for_ContractID.Invoke(Connection, Transaction, new P_CAS_GADfCID_1220()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;

            if (CoveredDrugs.Length != 0)
            {
                cls_Save_Contract_Covered_Drugs.Invoke(Connection, Transaction, new P_MD_SCCD_1811()
                {
                    ContractID = contractID, DrugIDs = CoveredDrugs.Select(cd => cd.drug_id).ToArray()
                }, securityTicket);
            }

            #endregion

            #region UPDATE COVERED DIAGNOSES

            var CoveredDiagnoses = cls_Get_All_Diagnoses_for_ContractID.Invoke(Connection, Transaction, new P_CAS_GADfCID_1306()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;

            if (CoveredDiagnoses.Length != 0)
            {
                cls_Save_Contract_Covered_Diagnoses.Invoke(Connection, Transaction, new P_MD_SCCD_1854()
                {
                    ContractID = contractID, DiagnoseIDs = CoveredDiagnoses.Select(dia => dia.diagnose_id).ToArray()
                }, securityTicket);
            }

            #endregion

            #region UPDATE GPOSES

            var connectedDrugs = cls_Get_GPOS_DrugIDs_for_ContractID.Invoke(Connection, Transaction, new P_MD_GGPOSDIDsfCID_1629()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;
            var connectedDiagnoses = cls_Get_GPOS_DiagnoseIDs_for_ContractID.Invoke(Connection, Transaction, new P_MD_GGPOSDIDsfCID_1633()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;

            var GposData = cls_Get_GPOS_Details_for_ContractID.Invoke(Connection, Transaction, new P_MD_GGPOSDfCID_1616()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;
            cls_Save_Contract_GPOS_Data.Invoke(Connection, Transaction, new P_MD_SCGPOSD_1306()
            {
                ContractID = contractID,
                GposData   = GposData.Select(gpos =>
                {
                    return(new P_MD_SCGPOSD_1306_Array()
                    {
                        DiagnoseIDs = connectedDiagnoses.Where(dia => dia.GposID == gpos.GposID).Select(dia => dia.DiagnoseID).ToArray(),
                        DrugIDs = connectedDrugs.Where(drug => drug.GposID == gpos.GposID).Select(drug => drug.DrugID).ToArray(),
                        FeeValue = gpos.FeeValue,
                        FromInjection = gpos.FromInjection,
                        GposID = Guid.Empty,
                        GposName = gpos.GposName,
                        GposNumber = gpos.GposNumber,
                        GposType = gpos.GposType,
                        ManagementFeeValue = gpos.ManagementFeeValue,
                        WaiveServiceFeeWithOrder = gpos.WaiveWithOrder
                    });
                }).ToArray()
            }, securityTicket);

            #endregion UPDATE GPOSES

            #region UPDATE CONTRACT PARAMETERS

            var currentDueDates = cls_Get_Due_Dates_for_ContractID.Invoke(Connection, Transaction, new P_MD_GDDfCID_1544()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;
            if (currentDueDates.Length != 0)
            {
                cls_Save_Contract_Due_Dates.Invoke(Connection, Transaction, new P_MD_SCDD_1729()
                {
                    ContractID = contractID,
                    DueDates   = currentDueDates.Select(dd =>
                    {
                        return(new P_MD_SCDD_1729_Array()
                        {
                            Value = dd.Value,
                            Name = dd.Name,
                            IsActive = true
                        });
                    }).ToArray()
                }, securityTicket);
            }
            #endregion

            #region UPDATE HIPS
            var currentHIPs = cls_Get_All_HIPs_for_ContractID.Invoke(Connection, Transaction, new P_MD_GAHIPsfCID_1905()
            {
                ContractID = Parameter.ContractID
            }, securityTicket).Result;

            if (currentHIPs.Length != 0)
            {
                cls_Save_Contract_Participating_HIPs.Invoke(Connection, Transaction, new P_MD_SCPHIPs_1341()
                {
                    ContractID = contractID, HipIDs = currentHIPs.Select(hip => hip.HipBptID).ToArray()
                }, securityTicket);
            }

            #endregion UPDATE HIPS

            return(returnValue);

            #endregion UserCode
        }
        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
        }