Ejemplo n.º 1
0
        public static void InsertDataIntoElastic(IEnumerable <IEnumerable <IElasticMapper> > data, string index_name)
        {
            foreach (var data_list in data)
            {
                if (data_list.Any())
                {
                    switch (data_list.First().GetType().Name)
                    {
                    case "Case_Model": Add_New_Case.Import_Case_Data_to_ElasticDB(data_list.Cast <Case_Model>().ToList(), index_name); break;

                    case "Aftercare_Model": Add_New_Aftercare.Import_Aftercare_Data_to_ElasticDB(data_list.Cast <Aftercare_Model>().ToList(), index_name); break;

                    case "Settlement_Model": Add_new_Settlement.Import_Settlement_to_ElasticDB(data_list.Cast <Settlement_Model>().ToList(), index_name); break;

                    case "Order_Model": Add_New_Order.Import_Order_Data_to_ElasticDB(data_list.Cast <Order_Model>().ToList(), index_name); break;

                    case "Patient_Model": Add_New_Patient.Import_Patients_to_ElasticDB(data_list.Cast <Patient_Model>().ToList(), index_name); break;

                    case "Submitted_Case_Model": Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(data_list.Cast <Submitted_Case_Model>().ToList(), index_name); break;

                    case "PatientDetailViewModel": Add_New_Patient.ImportPatientDetailsToElastic(data_list.Cast <PatientDetailViewModel>().ToList(), index_name); break;

                    case "Oct_Model": Add_New_Oct.Import_Oct_Data_to_ElasticDB(data_list.Cast <Oct_Model>().ToList(), index_name); break;

                    default: break;
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public static Patient_Model Get_Patient_for_PatientID(string patient_id, SessionSecurityTicket userSecurityTicket)
        {
            Patient_Model patient     = new Patient_Model();
            var           TenantID    = userSecurityTicket.TenantID.ToString();
            var           serializer  = new JsonNetSerializer();
            var           connection  = Elastic_Utils.ElsaticConnection();
            string        elasticType = "patient";

            string query = Add_New_Patient.BuildGetPatientQuery(patient_id);

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

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

            foreach (var item in foundResults.Documents)
            {
                patient = item;
            }
            return(patient);
        }
        public 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;
            }
        }
        protected static FR_CAS_SCCS_1520 Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_SCCS_1520 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_CAS_SCCS_1520();

            returnValue.Result = new CAS_SCCS_1520();

            //Put your code here
            var Ids_eligible      = new List <Guid>();
            var StatusOld         = DateTime.Now;
            var StatusNew         = DateTime.Now;
            var settlements       = new List <Settlement_Model>();
            var patientDetailList = new List <PatientDetailViewModel>();
            var itemsForChange    = Parameter.ids_to_change.Count();

            //filter case eligibility
            foreach (var id in Parameter.ids_to_change)
            {
                if (Parameter.status_to == 8)
                {
                    var settlementEdit = Get_Settlement.GetSettlementForID(id.ToString(), securityTicket);

                    if (settlementEdit != null)
                    {
                        if (settlementEdit.status == "FS4" || settlementEdit.status == "FS12")
                        {
                            Ids_eligible.Add(id);
                        }
                    }
                }
                else if (Parameter.status_to == 9)
                {
                    var settlementEdit = Get_Settlement.GetSettlementForID(id.ToString(), securityTicket);
                    if (settlementEdit != null)
                    {
                        if (settlementEdit.status == "FS7")
                        {
                            Ids_eligible.Add(id);
                        }
                    }
                }
            }

            var itemsChanged = Ids_eligible.Count;
            foreach (var ideligible in Ids_eligible)
            {
                #region update setttlement elastic

                var settlementEdit = Get_Settlement.GetSettlementForID(ideligible.ToString(), securityTicket);
                settlementEdit.status      = Parameter.status_to == 8 ? "FS" + 7 : "FS" + 12;
                settlementEdit.status_date = DateTime.Now;
                settlements.Add(settlementEdit);

                PatientDetailViewModel patient_detail = Retrieve_Patients.Get_PatientDetaiForID(settlementEdit.id, securityTicket);
                if (patient_detail != null)
                {
                    patient_detail.status = settlementEdit.status;
                    patientDetailList.Add(patient_detail);
                }
                #endregion

                List <CAS_GCTCfCID_1427> casePositions = cls_Get_Case_TransmitionCode_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCTCfCID_1427()
                {
                    CaseID = Guid.Parse(settlementEdit.case_id)
                }, securityTicket).Result.ToList();
                var aftercareNum = casePositions.Count(fs => fs.fs_key == "aftercare");
                foreach (var item in casePositions)
                {
                    if (item.fs_key == "treatment")
                    {
                        var StatusForCase = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_TransmitionStatus.Query()
                        {
                            IsDeleted    = false,
                            IsActive     = true,
                            Tenant_RefID = securityTicket.TenantID,
                            BIL_BillPosition_TransmitionStatusID = item.status_id
                        }).SingleOrDefault();

                        if (StatusForCase != null)
                        {
                            StatusOld = StatusForCase.Modification_Timestamp;

                            StatusForCase.Modification_Timestamp = DateTime.Now;
                            StatusForCase.IsActive = false;
                            StatusForCase.Save(Connection, Transaction);
                            StatusNew = StatusForCase.Modification_Timestamp;

                            var NewStatusForCase = new ORM_BIL_BillPosition_TransmitionStatus();
                            NewStatusForCase.IsDeleted              = false;
                            NewStatusForCase.Creation_Timestamp     = DateTime.Now;
                            NewStatusForCase.Modification_Timestamp = DateTime.Now;
                            NewStatusForCase.Tenant_RefID           = securityTicket.TenantID;
                            NewStatusForCase.IsActive = true;
                            NewStatusForCase.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                            NewStatusForCase.BillPosition_RefID   = StatusForCase.BillPosition_RefID;
                            NewStatusForCase.TransmitionCode      = Convert.ToInt32(Parameter.status_to) == 9 ? 12 : 7;
                            NewStatusForCase.TransmittedOnDate    = DateTime.Now;
                            NewStatusForCase.TransmitionStatusKey = StatusForCase.TransmitionStatusKey;
                            NewStatusForCase.Save(Connection, Transaction);
                        }
                    }
                    else
                    {
                        if ((aftercareNum > 1 && (item.fs_status != 8)) || aftercareNum == 0)
                        {
                            var StatusForCase = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_TransmitionStatus.Query()
                            {
                                IsDeleted    = false,
                                IsActive     = true,
                                Tenant_RefID = securityTicket.TenantID,
                                BIL_BillPosition_TransmitionStatusID = item.status_id
                            }).SingleOrDefault();

                            if (StatusForCase != null)
                            {
                                StatusOld = StatusForCase.Modification_Timestamp;

                                StatusForCase.Modification_Timestamp = DateTime.Now;
                                StatusForCase.IsActive = false;
                                StatusForCase.Save(Connection, Transaction);
                                StatusNew = StatusForCase.Modification_Timestamp;

                                var NewStatusForCase = new ORM_BIL_BillPosition_TransmitionStatus();
                                NewStatusForCase.IsDeleted              = false;
                                NewStatusForCase.Creation_Timestamp     = DateTime.Now;
                                NewStatusForCase.Modification_Timestamp = DateTime.Now;
                                NewStatusForCase.Tenant_RefID           = securityTicket.TenantID;
                                NewStatusForCase.IsActive = true;
                                NewStatusForCase.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                                NewStatusForCase.BillPosition_RefID   = StatusForCase.BillPosition_RefID;
                                NewStatusForCase.TransmitionCode      = Convert.ToInt32(Parameter.status_to) == 9 ? 12 : 7;
                                NewStatusForCase.TransmittedOnDate    = DateTime.Now;
                                NewStatusForCase.TransmitionStatusKey = StatusForCase.TransmitionStatusKey;
                                NewStatusForCase.Save(Connection, Transaction);
                            }
                        }
                    }
                }

                if (settlements.Count != 0)
                {
                    Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());
                }

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

            returnValue.Result.number_of_ids_changed   = itemsChanged;
            returnValue.Result.number_of_ids_to_change = itemsForChange;
            returnValue.Result.status_to = Parameter.status_to;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_CCtSE_1100 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo("de-DE");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
            //Get statuses from Resources
            var  FS1  = Properties.Resources.FS1;
            var  FS2  = Properties.Resources.FS2;
            var  FS3  = Properties.Resources.FS3;
            var  FS4  = Properties.Resources.FS4;
            var  FS5  = Properties.Resources.FS5;
            var  FS6  = Properties.Resources.FS6;
            var  FS7  = Properties.Resources.FS7;
            var  FS8  = Properties.Resources.FS8;
            var  FS9  = Properties.Resources.FS9;
            var  FS10 = Properties.Resources.FS10;
            var  FS11 = Properties.Resources.FS11;
            Guid treatment_performed_action_type_id = Guid.Empty;

            var treatment_performed_action_type = ORM_HEC_ACT_ActionType.Query.Search(Connection, Transaction, new ORM_HEC_ACT_ActionType.Query()
            {
                Tenant_RefID             = securityTicket.TenantID,
                IsDeleted                = false,
                GlobalPropertyMatchingID = "mm.docconect.doc.app.performed.action.treatment"
            }).SingleOrDefault();

            if (treatment_performed_action_type == null)
            {
                treatment_performed_action_type = new ORM_HEC_ACT_ActionType();
                treatment_performed_action_type.GlobalPropertyMatchingID = "mm.docconect.doc.app.performed.action.treatment";
                treatment_performed_action_type.Creation_Timestamp       = DateTime.Now;
                treatment_performed_action_type.Modification_Timestamp   = DateTime.Now;
                treatment_performed_action_type.Tenant_RefID             = securityTicket.TenantID;

                treatment_performed_action_type.Save(Connection, Transaction);

                treatment_performed_action_type_id = treatment_performed_action_type.HEC_ACT_ActionTypeID;
            }
            else
            {
                treatment_performed_action_type_id = treatment_performed_action_type.HEC_ACT_ActionTypeID;
            }

            List <Submitted_Case_Model>   allCases          = Get_All_Cases_With_Custom_Status.Get_All_Submited_Cases_With_Custom_Status("FS2", securityTicket);
            List <Submitted_Case_Model>   allCases_FS11     = Get_All_Cases_With_Custom_Status.Get_All_Submited_Cases_With_Custom_Status("FS11", securityTicket);
            List <Submitted_Case_Model>   newCaseList       = new List <Submitted_Case_Model>();
            List <Settlement_Model>       settlements       = new List <Settlement_Model>();
            List <PatientDetailViewModel> patientDetailList = new List <PatientDetailViewModel>();
            List <DateTime>        OldTransmitionDateList   = new List <DateTime>();
            Dictionary <Guid, int> consentValidToCache      = new Dictionary <Guid, int>();
            //List<Guid> casesToChange = new List<Guid>();
            //List<string> typeList = new List<string>();
            List <NegativeResponseModel> NegativeResponseList = new List <NegativeResponseModel>();
            var preexaminationsCache = cls_Get_Patient_Preexaminations_on_Tenant.Invoke(Connection, Transaction, securityTicket).Result.GroupBy(t => t.PatientID).ToDictionary(t => t.Key, t => t.GroupBy(c => c.Localization).ToDictionary(d => d.Key, d => d));

            DateTime DateForElastic = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
            var      casesForReport = cls_Get_Cases_For_Report.Invoke(Connection, Transaction, new P_CAS_GCFR_0910()
            {
                Status = 2
            }, securityTicket).Result;
            var casesForReport_FS11 = cls_Get_Cases_For_Report.Invoke(Connection, Transaction, new P_CAS_GCFR_0910()
            {
                Status = 11
            }, securityTicket).Result;
            Dictionary <string, string> serviceFeeValueCache = new Dictionary <string, string>();
            List <CaseForReportModel>   caseModelList        = new List <CaseForReportModel>();

            foreach (var item in Parameter.CasesToBeChanged)
            {
                try
                {
                    var  errorCase         = casesForReport.SingleOrDefault(i => int.Parse(i.PositionNumber) == int.Parse(item.bill_number));
                    bool shouldChangeToFS8 = false;

                    if (errorCase == null)
                    {
                        errorCase         = casesForReport_FS11.SingleOrDefault(i => int.Parse(i.PositionNumber) == int.Parse(item.bill_number));
                        shouldChangeToFS8 = true;
                    }

                    var management_fee_value = "-";
                    if (!string.IsNullOrEmpty(errorCase.BillingCode))
                    {
                        if (!serviceFeeValueCache.ContainsKey(errorCase.BillingCode))
                        {
                            var service_fee_value = cls_Get_ServiceFeeValue_for_BillingCode.Invoke(Connection, Transaction, new P_CAS_GSFVfBC_1721()
                            {
                                BillingCode = errorCase.BillingCode
                            }, securityTicket).Result;
                            if (service_fee_value != null)
                            {
                                serviceFeeValueCache.Add(errorCase.BillingCode, service_fee_value.service_fee);
                            }
                        }

                        management_fee_value = serviceFeeValueCache[errorCase.BillingCode];
                    }

                    var negativeTransmitionQuery = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                    negativeTransmitionQuery.Tenant_RefID       = securityTicket.TenantID;
                    negativeTransmitionQuery.IsDeleted          = false;
                    negativeTransmitionQuery.BillPosition_RefID = errorCase.StatusID;

                    var negativeTransmition = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, negativeTransmitionQuery).ToList();

                    var caseStatusQuery = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                    caseStatusQuery.Tenant_RefID = securityTicket.TenantID;
                    caseStatusQuery.IsDeleted    = false;
                    caseStatusQuery.IsActive     = true;
                    caseStatusQuery.BIL_BillPosition_TransmitionStatusID = errorCase.StatusID;

                    var caseStatusOld = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, caseStatusQuery).SingleOrDefault();

                    if (caseStatusOld == null)
                    {
                        throw new Exception("Transmition status not found for id: " + errorCase.StatusID);
                    }

                    OldTransmitionDateList.Add(caseStatusOld.TransmittedOnDate);
                    caseStatusOld.IsActive = false;
                    caseStatusOld.Save(Connection, Transaction);

                    var caseStatus = new ORM_BIL_BillPosition_TransmitionStatus();
                    caseStatus.IsDeleted              = false;
                    caseStatus.Creation_Timestamp     = DateTime.Now;
                    caseStatus.Modification_Timestamp = DateTime.Now;
                    caseStatus.Tenant_RefID           = securityTicket.TenantID;
                    caseStatus.IsActive       = true;
                    caseStatus.PrimaryComment = item.error_message;
                    caseStatus.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                    caseStatus.BillPosition_RefID   = caseStatusOld.BillPosition_RefID;
                    caseStatus.TransmitionCode      = 5;
                    caseStatus.TransmittedOnDate    = DateTime.Now;// should we use from edifact?
                    caseStatus.TransmitionStatusKey = caseStatusOld.TransmitionStatusKey;
                    caseStatus.Save(Connection, Transaction);

                    if (shouldChangeToFS8)
                    {
                        caseStatus.IsActive = false;
                        caseStatus.Save(Connection, Transaction);


                        var caseStatus2 = new ORM_BIL_BillPosition_TransmitionStatus();
                        caseStatus2.IsDeleted              = false;
                        caseStatus2.Creation_Timestamp     = DateTime.Now;
                        caseStatus2.Modification_Timestamp = DateTime.Now;
                        caseStatus2.Tenant_RefID           = securityTicket.TenantID;
                        caseStatus2.IsActive       = true;
                        caseStatus2.PrimaryComment = item.error_message;
                        caseStatus2.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                        caseStatus2.BillPosition_RefID   = caseStatusOld.BillPosition_RefID;
                        caseStatus2.TransmitionCode      = 8;
                        caseStatus2.TransmittedOnDate    = DateTime.Now;// should we use from edifact?
                        caseStatus2.TransmitionStatusKey = caseStatusOld.TransmitionStatusKey;
                        caseStatus2.Save(Connection, Transaction);
                    }

                    Guid caseID = errorCase.CaseID;
                    NegativeResponseModel negativeResponse = new NegativeResponseModel();

                    negativeResponse.caseID = caseID;
                    //casesToChange.Add(caseID);
                    if (caseStatusOld.TransmitionStatusKey == "aftercare")
                    {
                        negativeResponse.plannedActionID = errorCase.IsAftercareID;
                        negativeResponse.type            = "ac";
                    }

                    //typeList.Add("ac");
                    else if (caseStatusOld.TransmitionStatusKey == "treatment")
                    {
                        negativeResponse.plannedActionID = errorCase.IsTreatmentID;
                        negativeResponse.type            = "op";
                    }
                    else
                    {
                        negativeResponse.plannedActionID = errorCase.IsTreatmentID;
                        negativeResponse.type            = caseStatusOld.TransmitionStatusKey;
                    }
                    //typeList.Add("op");

                    NegativeResponseList.Add(negativeResponse);

                    P_PA_GPDfPID_1124 patientData = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                    {
                        PatientID = errorCase.Patient_RefID
                    }, securityTicket).Result;


                    #region Report data

                    CaseForReportModel caseModel = new CaseForReportModel();
                    caseModel.HIP                    = patientData.health_insurance_provider;
                    caseModel.ContractID             = patientData.contractID;
                    caseModel.HIP_IK                 = patientData.HealthInsurance_IKNumber;
                    caseModel.PatientInsuranceNumber = patientData.insurance_id;
                    caseModel.PatientGender          = patientData.gender;
                    caseModel.PatientStatusNumber    = patientData.insurance_status;
                    caseModel.PatientFirstName       = patientData.patient_first_name;
                    caseModel.PatientLastName        = patientData.patient_last_name;
                    caseModel.PatientBirthday        = patientData.birthday;
                    try
                    {
                        if (!consentValidToCache.ContainsKey(patientData.contractID))
                        {
                            double DurationOfParticipationConsentinMonths = ORM_CMN_CTR_Contract_Parameter.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract_Parameter.Query()
                            {
                                IsDeleted      = false,
                                Tenant_RefID   = securityTicket.TenantID,
                                ParameterName  = "Duration of participation consent – Month",
                                Contract_RefID = patientData.contractID
                            }).SingleOrDefault().IfNumericValue_Value;
                            consentValidToCache.Add(patientData.contractID, Convert.ToInt32(DurationOfParticipationConsentinMonths));
                        }

                        DateTime participationConsentValidTo = patientData.ParticipationConsent.OrderBy(dt => dt.participation_consent_issue_date).FirstOrDefault().participation_consent_issue_date.AddMonths(consentValidToCache[patientData.contractID]);
                        caseModel.PatientParticipationConsentValidUntil = participationConsentValidTo;
                    }
                    catch (Exception ex)
                    {
                        caseModel.PatientParticipationConsentValidUntil = DateTime.MinValue;
                    }

                    caseModel.CaseNumber = Convert.ToInt32(errorCase.CaseNumber);
                    caseModel.CaseType   = errorCase.CodeName;

                    try
                    {
                        caseModel.Drug = cls_Get_Drug_Details_for_DrugID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1614()
                        {
                            DrugID = errorCase.DrugID
                        }, securityTicket).Result.drug_name;
                    }
                    catch (Exception ex)
                    {
                        caseModel.Drug = "-";
                    }

                    caseModel.Diagnose     = errorCase.IM_PotentialDiagnosis_Name;
                    caseModel.DiagnoseCode = errorCase.IM_PotentialDiagnosis_Code;
                    caseModel.Localization = errorCase.IM_PotentialDiagnosisLocalization_Code;

                    P_CAS_GTCfPIDaDIDaLC_1008 parameterDia = new P_CAS_GTCfPIDaDIDaLC_1008();
                    parameterDia.PatientID        = errorCase.Patient_RefID;
                    parameterDia.DiagnoseID       = errorCase.CodeForType == "treatment" || errorCase.CodeForType == "preexamination" ? errorCase.TreatmentPerformedDiganoseID : errorCase.AftercasePerformedDiagnoseID;
                    parameterDia.LocalizationCode = errorCase.IM_PotentialDiagnosisLocalization_Code;
                    parameterDia.PerformedDate    = errorCase.CodeForType == "treatment" || errorCase.CodeForType == "preexamination" ? errorCase.TreatmentDate : errorCase.AfterCareDate;
                    parameterDia.ActionTypeID     = treatment_performed_action_type_id;
                    if (errorCase.CodeForType == "preexamination")
                    {
                        if (preexaminationsCache.ContainsKey(errorCase.Patient_RefID) && preexaminationsCache[errorCase.Patient_RefID].ContainsKey(errorCase.IM_PotentialDiagnosisLocalization_Code))
                        {
                            caseModel.TreatmentCount = preexaminationsCache[errorCase.Patient_RefID][errorCase.IM_PotentialDiagnosisLocalization_Code].Count(c => c.PreexaminationDate.Date <= errorCase.TreatmentDate.Date);
                        }
                    }
                    else
                    {
                        caseModel.TreatmentCount = cls_Get_Treatment_Count_for_PatientID_And_DiagnoseID_and_LocalizationCode.Invoke(Connection, Transaction, parameterDia, securityTicket).Result.treatment_count;
                    }

                    caseModel.GPOS         = errorCase.BillingCode;
                    caseModel.TreatmentDay = errorCase.CodeForType == "treatment" || errorCase.CodeForType == "preexamination" ? errorCase.TreatmentDate : errorCase.AfterCareDate;
                    if (errorCase.CodeForType == "treatment")
                    {
                        caseModel.SurgeryDateForThisCase = errorCase.TreatmentDate;
                    }
                    else if (errorCase.CodeForType == "preexamination")
                    {
                        caseModel.SurgeryDateForThisCase = DateTime.MinValue;
                    }
                    else
                    {
                        CAS_GTdfA_0936 Trdate = cls_Get_Treatment_Date_for_Aftercare.Invoke(Connection, Transaction, new P_CAS_GTdfA_0936()
                        {
                            CaseID = errorCase.CaseID
                        }, securityTicket).Result;
                        if (Trdate != null)
                        {
                            caseModel.SurgeryDateForThisCase = Trdate.TreatmentDate;
                        }
                    }

                    switch (patientData.gender)
                    {
                    case 0:
                        caseModel.PatientSalutation = "Herr";
                        break;

                    case 1:
                        caseModel.PatientSalutation = "Frau";
                        break;

                    default:
                        caseModel.PatientSalutation = "-";
                        break;
                    }

                    if (!shouldChangeToFS8)
                    {
                        caseModel.CurrentStatus = FS5;
                    }
                    else
                    {
                        caseModel.CurrentStatus = FS8;
                    }
                    caseModel.DateOfCurrentStatus = DateTime.Now;
                    if (!shouldChangeToFS8)
                    {
                        caseModel.PreCurrentStatus = FS2;
                    }
                    else
                    {
                        caseModel.PreCurrentStatus = FS11;
                    }
                    caseModel.DateOfPreCurrentStatus = caseStatusOld.TransmittedOnDate;

                    caseModel.InvoiceNumberForTheHIP = Convert.ToInt32(errorCase.PositionNumber);

                    caseModel.AmountForThisGPOS           = errorCase.NumberForPayment;
                    caseModel.NumberOfNegativeTry         = negativeTransmition.Count.ToString();
                    caseModel.DateOfTheSubmissionToTheHIP = Parameter.transferToHIPDate;
                    caseModel.FeedBackOfTheHIP            = item.transmition_date;
                    caseModel.PaymentDate = DateTime.MinValue;

                    caseModel.DrugOrdered       = (errorCase.orderId != Guid.Empty && int.Parse(errorCase.orderStatusCode) != 6) ? "Ja" : "Nein";
                    caseModel.NoFee             = errorCase.IsPatientFeeWaived ? "Ja" : "Nein";
                    caseModel.InvoiceToPractice = errorCase.SendInvoiceToPractice ? "Ja" : "Nein";
                    caseModel.OnlyLabelRequired = errorCase.isLabelOnly ? "Ja" : "Nein";

                    var gposAssignmentCount = cls_Get_Gpos_AssignmentCount_for_GposID.Invoke(Connection, Transaction, new P_CAS_GGPOSACfGPOSID_1252()
                    {
                        GposID = errorCase.GposID
                    }, securityTicket).Result;
                    if (gposAssignmentCount.AssignmentCount != 0)
                    {
                        var is_management_fee_waived = cls_Get_Management_Fee_Property_Value_for_CaseID_and_GposID.Invoke(Connection, Transaction, new P_CAS_GMFPVfCIDaGPOSTID_1749()
                        {
                            CaseID = errorCase.CaseID, GposID = errorCase.GposID
                        }, securityTicket).Result;
                        caseModel.ManagementFee = is_management_fee_waived == null ? "-" : is_management_fee_waived.PropertyValue == "waived" ? "-" : management_fee_value;
                    }
                    else
                    {
                        caseModel.ManagementFee = "-";
                    }

                    Guid DocID = errorCase.CodeForType == "treatment" || errorCase.CodeForType == "preexamination" ? errorCase.SurgeryDoctor : errorCase.AfterCareDoctor;

                    DO_GDDfDID_0823 doctorData = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                    {
                        DoctorID = DocID
                    }, securityTicket).Result.First();

                    caseModel.BSNR              = doctorData.BSNR;
                    caseModel.PracticeName      = doctorData.practice;
                    caseModel.DocName           = doctorData.first_name + " " + doctorData.last_name;
                    caseModel.LANR              = doctorData.lanr;
                    caseModel.BankAccountHolder = string.IsNullOrEmpty(doctorData.OwnerText) ? "-" : doctorData.OwnerText;
                    caseModel.BankName          = doctorData.BankName == null ? "-" : doctorData.BankName;
                    caseModel.IBAN              = doctorData.IBAN == null ? "-" : doctorData.IBAN;
                    caseModel.BIC = doctorData.BICCode == null ? "-" : doctorData.BICCode;

                    caseModelList.Add(caseModel);


                    #endregion
                }
                catch (Exception ex)
                {
                    LogUtils.Logger.LogInfo(new LogUtils.LogEntry(ex.StackTrace));
                    throw new Exception("Bill position: " + item.bill_number, ex);
                }
            }

            //Change in Elastic---------------------------------------------------------------------------------

            for (int k = 0; k < NegativeResponseList.Count; k++)
            {
                var errorCase = allCases.SingleOrDefault(i => i.case_id == NegativeResponseList[k].caseID.ToString() && i.type == NegativeResponseList[k].type);
                if (errorCase == null)
                {
                    errorCase = allCases_FS11.SingleOrDefault(i => i.case_id == NegativeResponseList[k].caseID.ToString() && i.type == NegativeResponseList[k].type);
                    if (errorCase == null)
                    {
                        continue;
                    }

                    errorCase.status = "FS8";
                    //Change settlement from Stornierung anhängig to storniert
                    Settlement_Model settlement = Get_Settlement.GetSettlementForID(NegativeResponseList[k].plannedActionID.ToString(), securityTicket);
                    settlement.status = "FS8";
                    settlements.Add(settlement);
                    PatientDetailViewModel patient_detail = Retrieve_Patients.Get_PatientDetaiForID(settlement.id, securityTicket);
                    if (patient_detail != null)
                    {
                        patient_detail.status = "FS8";
                        patientDetailList.Add(patient_detail);
                    }
                }
                else
                {
                    errorCase.status = "FS5";
                }

                errorCase.status_date        = DateTime.Now;
                errorCase.status_date_string = DateTime.Now.ToString("dd.MM.yyyy");
                newCaseList.Add(errorCase);
            }

            if (settlements.Count > 0)
            {
                Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());
            }

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

            if (newCaseList.Count > 0)
            {
                Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(newCaseList, securityTicket.TenantID.ToString());

                List <Documents> documentList = new List <Documents>();


                string hipID = Parameter.hipId;

                var healthInsuranceCompanyQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();
                healthInsuranceCompanyQuery.IsDeleted                = false;
                healthInsuranceCompanyQuery.Tenant_RefID             = securityTicket.TenantID;
                healthInsuranceCompanyQuery.HealthInsurance_IKNumber = hipID;

                var helathInsurance = ORM_HEC_HIS_HealthInsurance_Company.Query.Search(Connection, Transaction, healthInsuranceCompanyQuery).Single();

                var businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                businessParticipantQuery.CMN_BPT_BusinessParticipantID = helathInsurance.CMN_BPT_BusinessParticipant_RefID;
                businessParticipantQuery.IsDeleted    = false;
                businessParticipantQuery.Tenant_RefID = securityTicket.TenantID;

                var businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).Single();
                //Save Edifact
                string edi_path = System.IO.Path.GetTempPath() + Parameter.edi_name;
                System.IO.File.WriteAllText(edi_path, Parameter.edi_message);
                List <string> files = new List <string>();
                files.Add(edi_path);

                string zipPath = System.IO.Path.GetTempPath() + Parameter.edi_name + ".zip";
                ZipFIlesUtils.AddToArchive(zipPath, files);

                string    earliestDate    = OldTransmitionDateList.OrderBy(d => d).First().ToString("dd.MM.yyyy");
                string    lastDate        = OldTransmitionDateList.OrderBy(d => d).Last().ToString("dd.MM.yyyy");
                Documents documentEdifact = new Documents();
                documentEdifact.documentName           = "Import von " + earliestDate + " - " + lastDate;
                documentEdifact.documentOutputLocation = zipPath;
                documentEdifact.receiver = businessParticipant.DisplayName;
                documentEdifact.mimeType = "Application/Edifact_Error";
                documentList.Add(documentEdifact);

                Documents documentExcel = new Documents();

                documentExcel.documentName           = "ExcelReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm");
                documentExcel.documentOutputLocation = GenerateReportCases.CreateCaseXlsReport(caseModelList, documentExcel.documentName);
                documentExcel.mimeType = UtilMethods.GetMimeType(documentExcel.documentOutputLocation);
                documentExcel.receiver = "MM";
                documentList.Add(documentExcel);

                foreach (var item in documentList)
                {
                    MemoryStream ms = new MemoryStream(File.ReadAllBytes(item.documentOutputLocation));

                    byte[] byteArrayFile    = ms.ToArray();
                    var    _providerFactory = ProviderFactory.Instance;
                    var    documentProvider = _providerFactory.CreateDocumentServiceProvider();
                    var    uploadedFrom     = HttpContext.Current.Request.UserHostAddress;
                    Guid   documentID       = documentProvider.UploadDocument(byteArrayFile, item.documentOutputLocation, securityTicket.SessionTicket, uploadedFrom);
                    string downloadURL      = documentProvider.GenerateImageThumbnailLink(documentID, securityTicket.SessionTicket, false, 200);

                    P_ARCH_UD_1326 parameterDoc = new P_ARCH_UD_1326();
                    parameterDoc.DocumentID   = documentID;
                    parameterDoc.Mime         = item.mimeType;
                    parameterDoc.DocumentName = item.documentName;
                    parameterDoc.DocumentDate = DateForElastic;
                    parameterDoc.Receiver     = item.receiver;
                    parameterDoc.ContractID   = item.ContractID;

                    if (parameterDoc.Mime == "Application/Edifact_Error")
                    {
                        parameterDoc.Description = parameterDoc.DocumentName;
                    }
                    else
                    {
                        parameterDoc.Description = "KV Fehler";
                    }

                    cls_Upload_Report.Invoke(Connection, Transaction, parameterDoc, securityTicket);
                }
            }


            return(returnValue);

            #endregion UserCode
        }
Ejemplo n.º 6
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_SP_1436 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 DATA
            var patient_details = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
            {
                PatientID = Parameter.patient_id
            }, securityTicket).Result;
            if (patient_details == null)
            {
                throw new Exception("Patient details not found for ID: " + Parameter.patient_id);
            }

            var doctor = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                Tenant_RefID = securityTicket.TenantID, HEC_DoctorID = Parameter.treatment_doctor_id, IsDeleted = false
            }).SingleOrDefault();
            if (doctor == null)
            {
                throw new Exception("Doctor not found for ID: " + Parameter.treatment_doctor_id);
            }


            var doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
            {
                DoctorID = Parameter.treatment_doctor_id
            }, securityTicket).Result.FirstOrDefault();

            if (doctor_details == null)
            {
                throw new Exception("Doctor details not found for ID: " + Parameter.treatment_doctor_id);
            }

            var practice_details = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
            {
                PracticeID = doctor_details.practice_id
            }, securityTicket).Result.FirstOrDefault();
            if (practice_details == null)
            {
                throw new Exception("Practice details not found for ID: " + doctor_details.practice_id);
            }
            #endregion

            #region EDIT
            var preexaminationCase = ORM_HEC_CAS_Case.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case.Query()
            {
                Tenant_RefID   = securityTicket.TenantID,
                IsDeleted      = false,
                HEC_CAS_CaseID = Parameter.case_id
            }).SingleOrDefault();

            if (preexaminationCase == null)
            {
                throw new Exception("Case not found; id: " + Parameter.case_id);
            }

            preexaminationCase.Patient_BirthDate      = patient_details.birthday;
            preexaminationCase.Patient_FirstName      = patient_details.patient_first_name;
            preexaminationCase.Patient_Gender         = patient_details.gender;
            preexaminationCase.Patient_LastName       = patient_details.patient_last_name;
            preexaminationCase.Patient_RefID          = Parameter.patient_id;
            preexaminationCase.Modification_Timestamp = DateTime.Now;

            preexaminationCase.Save(Connection, Transaction);

            var plannedAction = cls_Get_Treatment_Planned_Action_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GTPAfCID_0946()
            {
                CaseID = Parameter.case_id
            }, securityTicket).Result;

            if (plannedAction == null)
            {
                throw new Exception("Planned action not found; case id: " + Parameter.case_id);
            }

            var preexaminationPlannedAction = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
            {
                HEC_ACT_PlannedActionID = plannedAction.planned_action_id,
                Tenant_RefID            = securityTicket.TenantID,
                IsDeleted = false
            }).SingleOrDefault();

            if (preexaminationPlannedAction == null)
            {
                throw new Exception("Preexamination planned action not found; case id: " + Parameter.case_id);
            }

            preexaminationPlannedAction.Patient_RefID          = Parameter.patient_id;
            preexaminationPlannedAction.Modification_Timestamp = DateTime.Now;
            preexaminationPlannedAction.PlannedFor_Date        = Parameter.treatment_date;
            preexaminationPlannedAction.ToBePerformedBy_BusinessParticipant_RefID = doctor.BusinessParticipant_RefID;

            preexaminationPlannedAction.Save(Connection, Transaction);

            var diagnosisIDs = cls_Get_Planned_Action_DiagnosisIDs_for_PlannedActionID.Invoke(Connection, Transaction, new P_CAS_GPADIDsfPAID_1041()
            {
                PlannedActionID = preexaminationPlannedAction.HEC_ACT_PlannedActionID
            }, securityTicket).Result;
            if (diagnosisIDs == null)
            {
                throw new Exception("Diagnosis ids not found for planned action id: " + preexaminationPlannedAction.HEC_ACT_PlannedActionID);
            }

            var diagnosisLocalization = ORM_HEC_ACT_PerformedAction_DiagnosisUpdate_Localization.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PerformedAction_DiagnosisUpdate_Localization.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false,
                HEC_ACT_PerformedAction_DiagnosisUpdate_LocalizationID = diagnosisIDs.HEC_ACT_PerformedAction_DiagnosisUpdate_LocalizationID
            }).SingleOrDefault();

            if (diagnosisLocalization == null)
            {
                throw new Exception("Diagnosis localization not found for id: " + diagnosisIDs.HEC_ACT_PerformedAction_DiagnosisUpdate_LocalizationID);
            }

            diagnosisLocalization.Modification_Timestamp = DateTime.Now;
            diagnosisLocalization.IM_PotentialDiagnosisLocalization_Code = Parameter.is_left_eye ? "L" : "R";

            diagnosisLocalization.Save(Connection, Transaction);
            #endregion

            #region ELASTIC
            try
            {
                var settlements        = new List <Settlement_Model>();
                var treatments         = new List <Submitted_Case_Model>();
                var patientDetailsList = new List <PatientDetailViewModel>();

                #region Settlement
                var settlement = Get_Settlement.GetSettlementForID(preexaminationPlannedAction.HEC_ACT_PlannedActionID.ToString(), securityTicket);
                settlement.birthday                 = patient_details.birthday.ToString("dd.MM.yyyy");
                settlement.bsnr                     = practice_details.practice_BSNR;
                settlement.doctor                   = MMDocConnectDocApp.GenericUtils.GetDoctorName(doctor_details);
                settlement.first_name               = patient_details.patient_first_name;
                settlement.hip                      = patient_details.health_insurance_provider;
                settlement.lanr                     = doctor_details.lanr;
                settlement.last_name                = patient_details.patient_last_name;
                settlement.localization             = Parameter.is_left_eye ? "L" : "R";
                settlement.patient_full_name        = patient_details.patient_first_name + " " + patient_details.patient_last_name;
                settlement.patient_id               = Parameter.patient_id.ToString();
                settlement.patient_insurance_number = patient_details.insurance_id;
                settlement.practice_id              = doctor_details.practice_id.ToString();
                settlement.surgery_date             = Parameter.treatment_date;
                settlement.surgery_date_string      = Parameter.treatment_date.ToString("dd.MM.yyyy");
                settlement.treatment_doctor_id      = Parameter.treatment_doctor_id.ToString();

                settlements.Add(settlement);
                #endregion

                #region MM Treatment
                var treatment = Get_Submitted_Cases.GetSubmittedCaseforSubmittedCaseID(preexaminationPlannedAction.HEC_ACT_PlannedActionID.ToString(), securityTicket);
                treatment.doctor_id                 = Parameter.treatment_doctor_id.ToString();
                treatment.doctor_lanr               = doctor_details.lanr;
                treatment.doctor_name               = MMDocConnectDocApp.GenericUtils.GetDoctorName(doctor_details);
                treatment.hip_name                  = patient_details.health_insurance_provider;
                treatment.localization              = Parameter.is_left_eye ? "L" : "R";
                treatment.patient_birthdate         = patient_details.birthday;
                treatment.patient_birthdate_string  = patient_details.birthday.ToString("dd.MM.yyyy");
                treatment.patient_id                = Parameter.patient_id.ToString();
                treatment.patient_insurance_number  = patient_details.insurance_id;
                treatment.patient_name              = patient_details.patient_last_name + ", " + patient_details.patient_first_name;
                treatment.practice_bsnr             = practice_details.practice_BSNR;
                treatment.practice_id               = practice_details.practiceID.ToString();
                treatment.practice_name             = practice_details.practice_name;
                treatment.treatment_date            = Parameter.treatment_date;
                treatment.treatment_date_month_year = Parameter.treatment_date.ToString("MMMM yyyy", new System.Globalization.CultureInfo("de", true));
                treatment.treatment_date_string     = Parameter.treatment_date.ToString("dd.MM.yyyy");

                treatments.Add(treatment);
                #endregion

                #region Patient details
                PatientDetailViewModel patientDetal_elastic = Retrieve_Patients.Get_PatientDetaiForID(preexaminationPlannedAction.HEC_ACT_PlannedActionID.ToString(), securityTicket);
                patientDetal_elastic.practice_id            = settlement.practice_id;
                patientDetal_elastic.date                   = settlement.surgery_date;
                patientDetal_elastic.date_string            = settlement.surgery_date_string;
                patientDetal_elastic.treatment_doctor_id    = settlement.treatment_doctor_id;
                patientDetal_elastic.diagnose_or_medication = settlement.diagnose;
                patientDetal_elastic.doctor                 = settlement.doctor;
                patientDetal_elastic.localisation           = settlement.localization;
                patientDetal_elastic.patient_id             = settlement.patient_id;
                patientDetal_elastic.status                 = settlement.status;

                patientDetailsList.Add(patientDetal_elastic);
                #endregion

                if (settlements.Any())
                {
                    Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());
                }
                if (treatments.Any())
                {
                    Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(treatments, securityTicket.TenantID.ToString());
                }
                if (patientDetailsList.Any())
                {
                    Add_New_Patient.ImportPatientDetailsToElastic(patientDetailsList, securityTicket.TenantID.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Retrieval/Import to elastic failed. " + ex.Message);
            }
            #endregion

            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guids Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_SCfEC_1641 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guids();
            //Put your code here
            var case_to_submit = cls_Get_Case_Details_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCDfCID_1435()
            {
                CaseID = Parameter.case_id
            }, securityTicket).Result;
            if (case_to_submit != null)
            {
                var diagnose_details = cls_Get_Diagnose_Details_for_DiagnoseID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1608()
                {
                    DiagnoseID = case_to_submit.diagnose_id
                }, securityTicket).Result;
                var drug_details = cls_Get_Drug_Details_for_DrugID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1614()
                {
                    DrugID = case_to_submit.drug_id
                }, securityTicket).Result;
                var treatment_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = case_to_submit.op_doctor_id
                }, securityTicket).Result.SingleOrDefault();
                var oct_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = case_to_submit.oct_doctor_id
                }, securityTicket).Result.SingleOrDefault();
                var patient_details = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                {
                    PatientID = case_to_submit.patient_id
                }, securityTicket).Result;
                var aftercare_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = case_to_submit.ac_doctor_id
                }, securityTicket).Result.SingleOrDefault();
                var treatment_practice_details = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
                {
                    PracticeID = case_to_submit.practice_id
                }, securityTicket).Result.FirstOrDefault();
                var status_ids = cls_Get_Case_TransmitionStatusIDs_for_CaseID_and_StatusCode.Invoke(Connection, Transaction, new P_CAS_GCTSIDsfCIDaSC_1619()
                {
                    CaseID = Parameter.case_id, StatusCode = 5
                }, securityTicket).Result;

                var transmition_statusQ = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                transmition_statusQ.Tenant_RefID = securityTicket.TenantID;
                transmition_statusQ.IsDeleted    = false;
                var result = new List <Guid>();

                var status_key = "aftercare";
                if (Parameter.action_type == "op")
                {
                    status_key = "treatment";
                }
                else if (Parameter.action_type == "oct")
                {
                    status_key = "oct";
                }

                if (status_key == "oct")
                {
                    var relevant_action = ORM_HEC_CAS_Case_RelevantPlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case_RelevantPlannedAction.Query()
                    {
                        PlannedAction_RefID = Parameter.planned_action_id,
                        Tenant_RefID        = securityTicket.TenantID,
                        IsDeleted           = false
                    }).Single();

                    if (relevant_action.Case_RefID != Parameter.case_id)
                    {
                        Parameter.case_id = relevant_action.Case_RefID;
                    }

                    var oct_status_ids = cls_Get_Case_TransmitionStatusIDs_for_PatientID_and_StatusCode.Invoke(Connection, Transaction, new P_CAS_GCTSIDsfPIDaSC_1859()
                    {
                        PatientID = case_to_submit.patient_id, StatusCode = 5
                    }, securityTicket).Result;

                    var all_case_status_ids = cls_Get_Case_TransmitionStatusIDs_for_PatientID.Invoke(Connection, Transaction, new P_CAS_GCTSIDsfPID_1856()
                    {
                        PatientID = case_to_submit.patient_id
                    }, securityTicket).Result.Where(t => t.status_key == "oct").ToArray();
                    var new_status_ids             = new List <CAS_GCTSIDsfPIDaSC_1859>();
                    var oct_planned_action_type_id = cls_Get_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GATID_1514()
                    {
                        action_type_gpmid = EActionType.PlannedOct.Value()
                    }, securityTicket).Result;

                    var case_relevant_actions = cls_Get_PlannedActionIDs_for_PatientID_and_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GPAIDsfPIDaATID_1705()
                    {
                        ActionTypeID = oct_planned_action_type_id,
                        PatientID    = case_to_submit.patient_id
                    }, securityTicket).Result.Where(t => t.performed).ToList();

                    var case_bill_positions = cls_Get_BillPositionIDs_for_PatientID_and_GposType.Invoke(Connection, Transaction, new P_CAS_GBPIDsfPIDaGposT_1709()
                    {
                        PatientID = case_to_submit.patient_id,
                        GposType  = EGposType.Oct.Value()
                    }, securityTicket).Result.Where(t => t.status_id != Guid.Empty).ToList();

                    for (var i = 0; i < case_relevant_actions.Count; i++)
                    {
                        if (case_relevant_actions[i].action_id == Parameter.planned_action_id)
                        {
                            var status        = all_case_status_ids.Single(t => t.bill_position_id == case_bill_positions[i].bill_position_id);
                            var status_to_add = oct_status_ids.Single(t => t.bill_position_id == status.bill_position_id);
                            new_status_ids.Add(status_to_add);
                            break;
                        }
                    }

                    if (!new_status_ids.Any())
                    {
                        throw new ArgumentException(String.Format("No suitable bill position found for action id: {0}; and case id: {1}", Parameter.planned_action_id, Parameter.case_id));
                    }

                    status_ids = new_status_ids.Select(t => new CAS_GCTSIDsfCIDaSC_1619()
                    {
                        bill_position_id            = t.bill_position_id,
                        global_property_matching_id = t.global_property_matching_id,
                        status_id  = t.status_id,
                        status_key = t.status_key
                    }).ToArray();
                }

                foreach (var status in status_ids)
                {
                    if (status.status_key == status_key)
                    {
                        transmition_statusQ.BIL_BillPosition_TransmitionStatusID = status.status_id;
                        var transmition_status = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, transmition_statusQ).SingleOrDefault();
                        if (transmition_status != null)
                        {
                            transmition_status.IsActive = false;
                            transmition_status.Save(Connection, Transaction);

                            var new_status = new ORM_BIL_BillPosition_TransmitionStatus();
                            new_status.PrimaryComment  = Parameter.comment;
                            new_status.TransmitionCode = 6;
                            new_status.IsActive        = true;
                            new_status.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                            new_status.BillPosition_RefID     = status.bill_position_id;
                            new_status.Creation_Timestamp     = DateTime.Now;
                            new_status.Modification_Timestamp = DateTime.Now;
                            new_status.Tenant_RefID           = securityTicket.TenantID;
                            new_status.TransmitionStatusKey   = transmition_status.TransmitionStatusKey;

                            var today = DateTime.Today;
                            var age   = today.Year - patient_details.birthday.Year;
                            if (patient_details.birthday > today.AddYears(-age))
                            {
                                age--;
                            }

                            var snapshot = cls_Create_XML_for_Immutable_Fields.Invoke(Connection, Transaction, new P_CAS_CXFIF_0830()
                            {
                                DiagnosisCatalogCode             = diagnose_details == null ? "-" : diagnose_details.diagnose_icd_10,
                                DiagnosisCatalogName             = diagnose_details == null ? "-" : diagnose_details.catalog_display_name,
                                DiagnosisName                    = diagnose_details == null ? "-" : diagnose_details.diagnose_name,
                                IFPerformedMedicalPracticeName   = treatment_practice_details.practice_name,
                                IFPerformedResponsibleBPFullName = treatment_doctor_details != null ? MMDocConnectDocApp.GenericUtils.GetDoctorName(treatment_doctor_details) : null,
                                Localization     = case_to_submit.localization,
                                PatientBirthDate = patient_details.birthday.ToString("dd.MM.yyyy"),
                                PatientFirstName = patient_details.patient_first_name,
                                PatientGender    = patient_details.gender.ToString(),
                                PatientLastName  = patient_details.patient_last_name,
                                PatientAge       = age.ToString()
                            }, securityTicket).Result;

                            if (snapshot != null)
                            {
                                new_status.TransmissionDataXML = snapshot.XmlFileString;
                            }

                            new_status.TransmittedOnDate = DateTime.Now;

                            new_status.Save(Connection, Transaction);

                            result.Add(new_status.BIL_BillPosition_TransmitionStatusID);
                        }
                    }
                }

                #region IMPORT SUBMITTED CASE TO ELASTIC
                var submitted_case_model_elastic = Get_Submitted_Cases.GetSubmittedCaseforSubmittedCaseID(Parameter.planned_action_id.ToString(), securityTicket);
                submitted_case_model_elastic.status             = "FS6";
                submitted_case_model_elastic.status_date        = DateTime.Now;
                submitted_case_model_elastic.status_date_string = DateTime.Now.ToString("dd.MM.yyyy");

                var cases_to_submit = new List <Submitted_Case_Model>();
                cases_to_submit.Add(submitted_case_model_elastic);

                Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(cases_to_submit, securityTicket.TenantID.ToString());
                #endregion

                #region IMPORT SETTLEMENT TO ELASTIC
                var doctor_name = default(string);
                switch (Parameter.action_type)
                {
                case "op":
                    if (treatment_doctor_details != null)
                    {
                        doctor_name = GenericUtils.GetDoctorName(treatment_doctor_details);
                    }
                    break;

                case "ac":
                    if (aftercare_doctor_details != null)
                    {
                        doctor_name = GenericUtils.GetDoctorName(aftercare_doctor_details);
                    }
                    break;

                case "oct":
                    if (oct_doctor_details != null)
                    {
                        doctor_name = GenericUtils.GetDoctorName(oct_doctor_details);
                    }
                    break;
                }

                var settlement = Get_Settlement.GetSettlementForID(Parameter.planned_action_id.ToString(), securityTicket);
                settlement.status = "FS6";
                if (!String.IsNullOrEmpty(doctor_name))
                {
                    settlement.doctor = doctor_name;
                }

                settlement.patient_full_name = patient_details.patient_last_name + ", " + patient_details.patient_first_name;
                settlement.first_name        = patient_details.patient_first_name;
                settlement.last_name         = patient_details.patient_last_name;

                var settlements = new List <Settlement_Model>()
                {
                    settlement
                };
                Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());

                var patientDetailList = new List <PatientDetailViewModel>();
                var patient_detail    = Retrieve_Patients.Get_PatientDetaiForID(settlement.id, securityTicket);
                if (patient_detail != null)
                {
                    patient_detail.doctor = doctor_name;
                    patient_detail.status = settlement.status;
                    patientDetailList.Add(patient_detail);
                    Add_New_Patient.ImportPatientDetailsToElastic(patientDetailList, securityTicket.TenantID.ToString());
                }
                #endregion

                returnValue.Result = result.ToArray();
            }

            return(returnValue);

            #endregion UserCode
        }
Ejemplo n.º 8
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_OR_COS_0840 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            List <Case_Model>             cases             = new List <Case_Model>();
            List <PatientDetailViewModel> patientDetailList = new List <PatientDetailViewModel>();
            List <Order_Model>            OrderModelL       = new List <Order_Model>();
            //Put your code here
            foreach (var ParameterInstance in Parameter.ParameterArray)
            {
                var procurmentHeader = ORM_ORD_PRC_ProcurementOrder_Header.Query.Search(Connection, Transaction, new ORM_ORD_PRC_ProcurementOrder_Header.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    ORD_PRC_ProcurementOrder_HeaderID = ParameterInstance.Order_ID
                }).Single();


                var newOrderStatus = new ORM_ORD_PRC_ProcurementOrder_Status();
                newOrderStatus.Tenant_RefID           = securityTicket.TenantID;
                newOrderStatus.Status_Code            = ParameterInstance.Status_To;
                newOrderStatus.Modification_Timestamp = DateTime.Now;
                newOrderStatus.Save(Connection, Transaction);

                var newOrderStatusHistory = new ORM_ORD_PRC_ProcurementOrder_StatusHistory();
                newOrderStatusHistory.Tenant_RefID = securityTicket.TenantID;
                newOrderStatusHistory.ProcurementOrder_Status_RefID = newOrderStatus.ORD_PRC_ProcurementOrder_StatusID;
                newOrderStatusHistory.IsStatus_RejectedBySupplier   = true;
                newOrderStatusHistory.ProcurementOrder_Header_RefID = procurmentHeader.ORD_PRC_ProcurementOrder_HeaderID;
                newOrderStatusHistory.Save(Connection, Transaction);

                procurmentHeader.Current_ProcurementOrderStatus_RefID = newOrderStatus.ORD_PRC_ProcurementOrder_StatusID;
                procurmentHeader.Save(Connection, Transaction);

                #region Update Case Elastic
                var caseForUpdate = cls_Get_Case_Details_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCDfCID_1435()
                {
                    CaseID = ParameterInstance.CaseID
                }, securityTicket).Result;
                var patient_details = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                {
                    PatientID = caseForUpdate.patient_id
                }, securityTicket).Result;
                var diagnose_details = cls_Get_Diagnose_Details_for_DiagnoseID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1608()
                {
                    DiagnoseID = caseForUpdate.diagnose_id
                }, securityTicket).Result;
                var drug_details = cls_Get_Drug_Details_for_DrugID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1614()
                {
                    DrugID = caseForUpdate.drug_id
                }, securityTicket).Result;
                var treatment_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = caseForUpdate.op_doctor_id
                }, securityTicket).Result.SingleOrDefault();
                var case_status = cls_Check_Case_Status.Invoke(Connection, Transaction, new P_CAS_CCS_1639()
                {
                    CaseID = ParameterInstance.CaseID
                }, securityTicket).Result;
                if (case_status == null)
                {
                    var case_model_elastic = Get_Cases.GetCaseforCaseID(caseForUpdate.case_id.ToString(), securityTicket);
                    if (case_model_elastic != null)
                    {
                        case_model_elastic.status_drug_order                   = ParameterInstance.Status_To_Str;
                        case_model_elastic.order_modification_timestamp        = caseForUpdate.order_modification_timestamp;
                        case_model_elastic.order_modification_timestamp_string = caseForUpdate.order_modification_timestamp.ToString("dd.MM.yyyy");

                        cases.Add(case_model_elastic);
                    }
                }
                #endregion

                var orderM = Get_Orders.GetOrderforOrderID(procurmentHeader.ORD_PRC_ProcurementOrder_HeaderID.ToString(), securityTicket);
                if (orderM != null)
                {
                    orderM.status_drug_order                   = ParameterInstance.Status_To_Str;
                    orderM.order_modification_timestamp        = DateTime.Now;
                    orderM.order_modification_timestamp_string = DateTime.Now.ToString("dd.MM.yyyy");

                    OrderModelL.Add(orderM);

                    var patientDetalTreatmentWithOrder = Retrieve_Patients.Get_PatientDetaiForIDandOrderID(orderM.id, securityTicket).Where(i => i.detail_type == "op").SingleOrDefault();


                    if (patientDetalTreatmentWithOrder == null)
                    {
                        PatientDetailViewModel patient_detail = new PatientDetailViewModel();
                        patient_detail.case_id                = orderM.case_id;
                        patient_detail.date                   = orderM.treatment_date;
                        patient_detail.date_string            = patient_detail.date.ToString("dd.MM.");
                        patient_detail.detail_type            = "order";
                        patient_detail.diagnose_or_medication = orderM.drug;
                        patient_detail.practice_id            = orderM.practice_id;
                        patient_detail.id           = orderM.id;
                        patient_detail.order_id     = orderM.id;
                        patient_detail.case_id      = orderM.case_id;
                        patient_detail.order_status = orderM.status_drug_order;
                        patient_detail.patient_id   = patient_details.id.ToString();
                        patient_detail.drug_id      = orderM.drug_id;

                        patientDetailList.Add(patient_detail);
                    }
                    else
                    {
                        patientDetalTreatmentWithOrder.date         = orderM.treatment_date;
                        patientDetalTreatmentWithOrder.date_string  = patientDetalTreatmentWithOrder.date.ToString("dd.MM.");
                        patientDetalTreatmentWithOrder.case_id      = orderM.case_id;
                        patientDetalTreatmentWithOrder.order_id     = orderM.id;
                        patientDetalTreatmentWithOrder.practice_id  = orderM.practice_id;
                        patientDetalTreatmentWithOrder.drug         = orderM.drug;
                        patientDetalTreatmentWithOrder.drug_id      = orderM.drug_id;
                        patientDetalTreatmentWithOrder.order_status = orderM.status_drug_order;
                        patientDetalTreatmentWithOrder.patient_id   = patient_details.id.ToString();

                        patientDetailList.Add(patientDetalTreatmentWithOrder);
                    }
                }
            }

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

            if (OrderModelL.Count != 0)
            {
                Add_New_Order.Import_Order_Data_to_ElasticDB(OrderModelL, securityTicket.TenantID.ToString());
            }

            if (cases.Count != 0)
            {
                Add_New_Case.Import_Case_Data_to_ElasticDB(cases, securityTicket.TenantID.ToString());
            }

            return(returnValue);

            #endregion UserCode
        }
Ejemplo n.º 9
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
        }
Ejemplo n.º 10
0
        public static void Import_Data_From_DB_To_Elastic(DbConnection Connection, DbTransaction Transaction, SessionSecurityTicket securityTicket)
        {
            #region add Practices and Doctors to Elastic
            List <Practice_Doctors_Model> LdoctorPracticeM = new List <Practice_Doctors_Model>();
            var dataPractice = cls_Get_All_Practices_from_DB.Invoke(Connection, Transaction, securityTicket).Result;
            IAccountServiceProvider accountService;
            var _providerFactory = ProviderFactory.Instance;
            accountService = _providerFactory.CreateAccountServiceProvider();

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

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

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

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

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

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

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

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

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

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

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


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



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

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

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

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

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

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

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

            #endregion

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

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

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

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


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

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


                        Order_Model orderM = new Order_Model();

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

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

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


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

                    Console.Write("Type Case deleted");
                }
                catch
                {
                    Console.Write("Type do not exsists");
                }
                Add_New_Case.Import_Case_Data_to_ElasticDB(cases, securityTicket.TenantID.ToString());
                Add_New_Order.Import_Order_Data_to_ElasticDB(OrderModelL, securityTicket.TenantID.ToString());
                Console.Write("Cases and Orders imported to Elastic");
            }
            #endregion
        }
Ejemplo n.º 11
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_ARCH_UCPD_0950 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            if (Parameter.PlannedActionID == Guid.Empty)
            {
                return(returnValue);
            }

            var documentUpload = ORM_DOC_Document.Query.Search(Connection, Transaction, new ORM_DOC_Document.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false,
                Alias        = Parameter.PlannedActionID.ToString()
            }).SingleOrDefault();

            var documentUploadRevision = new ORM_DOC_DocumentRevision();
            documentUploadRevision.Revision = 0;

            if (documentUpload == null)
            {
                documentUpload = new ORM_DOC_Document();
                documentUpload.Tenant_RefID             = securityTicket.TenantID;
                documentUpload.Alias                    = Parameter.PlannedActionID.ToString();
                documentUpload.GlobalPropertyMatchingID = "case pdf";

                documentUpload.Save(Connection, Transaction);
            }
            else
            {
                var previousDocumentUploadRevision = ORM_DOC_DocumentRevision.Query.Search(Connection, Transaction, new ORM_DOC_DocumentRevision.Query()
                {
                    IsLastRevision = true,
                    Tenant_RefID   = securityTicket.TenantID,
                    IsDeleted      = false,
                    Document_RefID = documentUpload.DOC_DocumentID
                }).SingleOrDefault();

                previousDocumentUploadRevision.IsLastRevision         = false;
                previousDocumentUploadRevision.Modification_Timestamp = DateTime.Now;

                previousDocumentUploadRevision.Save(Connection, Transaction);

                documentUploadRevision.Revision = previousDocumentUploadRevision.Revision + 1;
            }

            documentUploadRevision.File_MIMEType       = Parameter.Mime;
            documentUploadRevision.Tenant_RefID        = securityTicket.TenantID;
            documentUploadRevision.Document_RefID      = documentUpload.DOC_DocumentID;
            documentUploadRevision.UploadedByAccount   = securityTicket.AccountID;
            documentUploadRevision.File_ServerLocation = Parameter.DocumentID.ToString();
            documentUploadRevision.File_Name           = Parameter.DocumentName;
            documentUploadRevision.File_Description    = Parameter.CaseID.ToString();
            documentUploadRevision.IsLastRevision      = true;

            documentUploadRevision.Save(Connection, Transaction);

            var docStructure = ORM_DOC_Structure.Query.Search(Connection, Transaction, new ORM_DOC_Structure.Query()
            {
                IsDeleted    = false,
                Tenant_RefID = securityTicket.TenantID,
                Label        = Parameter.CaseID.ToString()
            }).FirstOrDefault();

            if (docStructure == null)
            {
                docStructure = new ORM_DOC_Structure();
                docStructure.Tenant_RefID = securityTicket.TenantID;
                docStructure.Label        = Parameter.CaseID.ToString();

                docStructure.Save(Connection, Transaction);
            }

            var doc2docStructure = new ORM_DOC_Document_2_Structure();
            doc2docStructure.Tenant_RefID    = securityTicket.TenantID;
            doc2docStructure.Document_RefID  = documentUpload.DOC_DocumentID;
            doc2docStructure.Structure_RefID = docStructure.DOC_StructureID;

            doc2docStructure.Save(Connection, Transaction);

            #region Case property
            var caseProperty = ORM_HEC_CAS_Case_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case_UniversalProperty.Query()
            {
                GlobalPropertyMatchingID = ECaseProperty.ReportDownloaded.Value(),
                Tenant_RefID             = securityTicket.TenantID,
                IsValue_String           = true,
                IsDeleted    = false,
                PropertyName = "Case Report Downloaded"
            }).SingleOrDefault();

            if (caseProperty == null)
            {
                caseProperty = new ORM_HEC_CAS_Case_UniversalProperty();
                caseProperty.GlobalPropertyMatchingID = ECaseProperty.ReportDownloaded.Value();
                caseProperty.IsValue_String           = true;
                caseProperty.Modification_Timestamp   = DateTime.Now;
                caseProperty.PropertyName             = "Case Report Downloaded";
                caseProperty.Tenant_RefID             = securityTicket.TenantID;

                caseProperty.Save(Connection, Transaction);
            }

            var casePropertyValue = ORM_HEC_CAS_Case_UniversalPropertyValue.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case_UniversalPropertyValue.Query()
            {
                HEC_CAS_Case_RefID = Parameter.CaseID,
                HEC_CAS_Case_UniversalProperty_RefID = caseProperty.HEC_CAS_Case_UniversalPropertyID,
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false
            }).SingleOrDefault();

            if (casePropertyValue == null)
            {
                casePropertyValue = new ORM_HEC_CAS_Case_UniversalPropertyValue();
                casePropertyValue.HEC_CAS_Case_RefID = Parameter.CaseID;
                casePropertyValue.HEC_CAS_Case_UniversalProperty_RefID = caseProperty.HEC_CAS_Case_UniversalPropertyID;
                casePropertyValue.Tenant_RefID = securityTicket.TenantID;
            }

            casePropertyValue.Modification_Timestamp = DateTime.Now;
            if (casePropertyValue.Value_String == null)
            {
                casePropertyValue.Value_String = Parameter.PlannedActionID.ToString();
            }
            else
            {
                if (!casePropertyValue.Value_String.Contains(Parameter.PlannedActionID.ToString()))
                {
                    casePropertyValue.Value_String += ";" + Parameter.PlannedActionID.ToString();
                }
            }

            casePropertyValue.Save(Connection, Transaction);
            #endregion

            if (!Parameter.IsBackgroundTask)
            {
                #region Update elastic
                try
                {
                    var settlement = Get_Settlement.GetSettlementForID(Parameter.PlannedActionID.ToString(), securityTicket);
                    settlement.is_report_downloaded = true;

                    Add_new_Settlement.Import_Settlement_to_ElasticDB(new List <Settlement_Model>()
                    {
                        settlement
                    }, securityTicket.TenantID.ToString());

                    var patientDetails = Retrieve_Patients.Get_PatientDetaiForID(Parameter.PlannedActionID.ToString(), securityTicket);
                    patientDetails.if_settlement_is_report_downloaded = true;

                    Add_New_Patient.ImportPatientDetailsToElastic(new List <PatientDetailViewModel>()
                    {
                        patientDetails
                    }, securityTicket.TenantID.ToString());
                }
                catch { }
            }

            #endregion

            return(returnValue);

            #endregion UserCode
        }
Ejemplo n.º 12
0
        public static void ImportTestPatients(DbConnection Connection, DbTransaction Transaction, SessionSecurityTicket securityTicket, Guid medical_practice_id)
        {
            List <Patient_Model_xls> patientList        = new List <Patient_Model_xls>();
            List <Patient_Model>     elasticPatientList = new List <Patient_Model>();
            IFormatProvider          culture            = new System.Globalization.CultureInfo("de", true);

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

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

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

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

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


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

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

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

            var medicalPracticeQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();

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

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


            int i = 0;

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

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

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

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


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

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

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

                case 1:
                    genre = 1;
                    break;

                case 2:
                    genre = 0;
                    break;
                }

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


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

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

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


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

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

                Patient_Model patientModel = new Patient_Model();


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

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


                elasticPatientList.Add(patientModel);



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



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

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


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

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

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

            if (!checkTupe)
            {
                string jsonProductMapping   = Add_New_Patient.BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }
            Elastic_Utils.BulkType_Generic <Patient_Model>(elasticPatientList, connection, serializer, indexElastic, "patient");
        }
Ejemplo n.º 13
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
        }
Ejemplo n.º 14
0
        protected static FR_CAS_CCS_1516 Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_CCS_1516 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode

            #region Thread cultrue
            Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo("de-DE");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
            var germanCulture = new CultureInfo("de-de");
            #endregion

            #region Local variables
            var returnValue = new FR_CAS_CCS_1516();
            returnValue.Result = new CAS_CCS_1516();
            var settlements         = new List <Settlement_Model>();
            var patientDetailList   = new List <PatientDetailViewModel>();
            var cases_to_submit     = new List <Submitted_Case_Model>();
            var documents           = new List <Documents>();
            var statusChangedOnDate = Parameter.StatusChangedOnDate == DateTime.MinValue ? DateTime.Now : Parameter.StatusChangedOnDate;

            var DateForElastic = DateTime.Now;

            var cases = cls_Generate_Report.Invoke(Connection, Transaction, new P_CAS_GR_1608()
            {
                statuses         = Parameter.StatusFrom == 2 ? new int[] { 2, 11 } : Parameter.StatusFrom == 4 ? new int[] { 4, 8, 10 } : new int[] { Convert.ToInt32(Parameter.StatusFrom) },
                position_numbers = Parameter.PositionNumbers,
                updateCasesSubmittedBeforeDate = Parameter.UpdatedCasesSubmittedBeforeDate
            }, securityTicket).Result.cases;

            var earliestFsStatusDate = DateTime.MinValue;
            var latestFsStatusDate   = DateTime.MinValue;

            #endregion

            #region Pre-fetched data

            // todo: write queries for ids!
            var activeFsStatuses = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_TransmitionStatus.Query()
            {
                IsDeleted       = false,
                IsActive        = true,
                Tenant_RefID    = securityTicket.TenantID,
                TransmitionCode = Convert.ToInt32(Parameter.StatusFrom)
            }).ToDictionary(t => t.BIL_BillPosition_TransmitionStatusID, t => t);

            var casesToUpdate = ORM_HEC_CAS_Case.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case.Query()
            {
                IsDeleted    = false,
                Tenant_RefID = securityTicket.TenantID
            }).ToDictionary(t => t.HEC_CAS_CaseID, t => t);
            #endregion

            foreach (var reportCase in cases)
            {
                if (Parameter.StatusTo == 7 && (reportCase.CurrentFsStatusCode == 8 || reportCase.CurrentFsStatusCode == 11 || reportCase.CurrentFsStatusCode == 17))
                {
                    continue;
                }

                #region Patient age calculation
                DateTime today      = DateTime.Today;
                int      patientAge = today.Year - reportCase.PatientBirthday.Year;
                if (reportCase.PatientBirthday > today.AddYears(-patientAge))
                {
                    patientAge--;
                }
                #endregion

                #region FS status update
                var caseActiveFsStatus = activeFsStatuses.ContainsKey(reportCase.TransmitionStatusID) ? activeFsStatuses[reportCase.TransmitionStatusID] : ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_TransmitionStatus.Query()
                {
                    BIL_BillPosition_TransmitionStatusID = reportCase.TransmitionStatusID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();

                var responseFromHip = "";
                if (Parameter.StatusTo == 5)
                {
                    var edifact        = new EDIFACT();
                    var edifactMessage = Parameter.EdifactMessage;
                    var parser         = new Parser(ref edifactMessage);
                    EDIMessage.segmentArray = parser.GetSegments();
                    var parsedEdifact = EDIMessage.SegmentsToParsedEdifact();
                    var message       = parsedEdifact.transmitionMessages.Single(t => Int32.Parse(t.Rgi.Segment5.Value.Split('K').Last()) == reportCase.InvoiceNumberForTheHIP);
                    responseFromHip = String.Join("; ", message.Fhl.Select(t => t.Segment4.Value));
                }

                if (!Parameter.AreCasesPaymentAndStatus)
                {
                    if (caseActiveFsStatus.TransmittedOnDate.Date > latestFsStatusDate)
                    {
                        latestFsStatusDate = caseActiveFsStatus.TransmittedOnDate;
                    }

                    if (earliestFsStatusDate < caseActiveFsStatus.TransmittedOnDate.Date)
                    {
                        earliestFsStatusDate = caseActiveFsStatus.TransmittedOnDate;
                    }

                    caseActiveFsStatus.Modification_Timestamp = DateTime.Now;
                    caseActiveFsStatus.IsActive = false;

                    caseActiveFsStatus.Save(Connection, Transaction);

                    var NewStatusForCase = new ORM_BIL_BillPosition_TransmitionStatus();
                    NewStatusForCase.Modification_Timestamp = DateTime.Now;
                    NewStatusForCase.Tenant_RefID           = securityTicket.TenantID;
                    NewStatusForCase.BillPosition_RefID     = caseActiveFsStatus.BillPosition_RefID;
                    NewStatusForCase.TransmitionStatusKey   = caseActiveFsStatus.TransmitionStatusKey;
                    NewStatusForCase.TransmittedOnDate      = statusChangedOnDate;
                    NewStatusForCase.PrimaryComment         = responseFromHip;
                    NewStatusForCase.TransmitionCode        = Convert.ToInt32(Parameter.StatusTo);
                    NewStatusForCase.TransmissionDataXML    = cls_Create_XML_for_Immutable_Fields.Invoke(Connection, Transaction, new P_CAS_CXFIF_0830()
                    {
                        DiagnosisCatalogCode             = reportCase.DiagnoseCode,
                        DiagnosisCatalogName             = "ICD-10",
                        IFPerformedMedicalPracticeName   = reportCase.PracticeName,
                        IFPerformedResponsibleBPFullName = reportCase.DocName,
                        Localization     = reportCase.Localization,
                        PatientBirthDate = reportCase.PatientBirthday.ToString("dd.MM.yyyy"),
                        PatientFirstName = reportCase.PatientFirstName,
                        PatientGender    = reportCase.PatientGender.ToString(),
                        PatientAge       = patientAge.ToString()
                    }, securityTicket).Result.XmlFileString;

                    if (caseActiveFsStatus.TransmitionCode == 11)
                    {
                        var cancellingStatus = new ORM_BIL_BillPosition_TransmitionStatus();
                        cancellingStatus.TransmitionCode        = 8;
                        cancellingStatus.BillPosition_RefID     = caseActiveFsStatus.BillPosition_RefID;
                        cancellingStatus.IsActive               = true;
                        cancellingStatus.Modification_Timestamp = DateTime.Now;
                        cancellingStatus.Tenant_RefID           = securityTicket.TenantID;
                        cancellingStatus.TransmittedOnDate      = statusChangedOnDate;
                        cancellingStatus.TransmitionStatusKey   = caseActiveFsStatus.TransmitionStatusKey;
                        cancellingStatus.TransmissionDataXML    = NewStatusForCase.TransmissionDataXML;

                        cancellingStatus.Save(Connection, Transaction);
                    }
                    else
                    {
                        NewStatusForCase.IsActive = true;
                    }

                    NewStatusForCase.Save(Connection, Transaction);


                    #region Elastic updates
                    var elasticId = reportCase.UniqueID.ToString();
                    try
                    {
                        var submitted_case_model_elastic = Get_Submitted_Cases.GetSubmittedCaseforSubmittedCaseID(elasticId, securityTicket);
                        var settlement     = Get_Settlement.GetSettlementForID(elasticId, securityTicket);
                        var patient_detail = Retrieve_Patients.Get_PatientDetaiForID(elasticId, securityTicket);

                        var newStatus = "";
                        if (caseActiveFsStatus.TransmitionCode == 11)
                        {
                            newStatus = "FS8";
                        }
                        else
                        {
                            newStatus = "FS" + Parameter.StatusTo;
                        }

                        submitted_case_model_elastic.status             = newStatus;
                        submitted_case_model_elastic.status_date        = statusChangedOnDate;
                        submitted_case_model_elastic.status_date_string = statusChangedOnDate.ToString("dd.MM.yyyy");
                        settlement.status      = newStatus;
                        settlement.status_date = statusChangedOnDate;
                        patient_detail.status  = newStatus;

                        cases_to_submit.Add(submitted_case_model_elastic);
                        settlements.Add(settlement);
                        patientDetailList.Add(patient_detail);
                    }
                    catch
                    {
                    }
                    #endregion
                }
                #endregion

                #region Immutable fields update
                var caseToUpdate = casesToUpdate[reportCase.CaseID];
                caseToUpdate.Modification_Timestamp = DateTime.Now;
                caseToUpdate.Patient_BirthDate      = reportCase.PatientBirthday;
                caseToUpdate.Patient_FirstName      = reportCase.PatientFirstName;
                caseToUpdate.Patient_LastName       = reportCase.PatientLastName;
                caseToUpdate.Patient_Gender         = reportCase.PatientGender;
                caseToUpdate.Patient_Age            = patientAge;

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

            if (cases.Any())
            {
                #region Edifact generation
                if (Parameter.StatusTo == 2)
                {
                    var contracts  = cases.GroupBy(i => i.ContractID).ToDictionary(t => t.Key, t => t.ToList());
                    var isTestData = false;
                    try
                    {
                        isTestData = bool.Parse(WebConfigurationManager.AppSettings["edifact-generate-test-data"]);
                    }
                    catch { }

                    var cmnContracts = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                    {
                        Tenant_RefID = securityTicket.TenantID, IsDeleted = false
                    });

                    foreach (var contract in contracts)
                    {
                        var contractID         = contract.Key;
                        var contractParameters = ORM_CMN_CTR_Contract_Parameter.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract_Parameter.Query()
                        {
                            Contract_RefID = contractID,
                            Tenant_RefID   = securityTicket.TenantID,
                            IsDeleted      = false
                        });

                        var contractCharacteristicIDParameter = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.CharacteristicID.Value());
                        var edifactType                = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.EdifactType.Value());
                        var encryptEdifactParameter    = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.EncryptEdifact.Value());
                        var nextEdifactNumberParameter = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.NextEdifactNumber.Value());

                        var contractType      = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.ContractType.Value());
                        var messageType       = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.MessageType.Value());
                        var mergeForAllHips   = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.MergeForAllHips.Value());
                        var useKForCorrection = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.UseKForCorrection.Value());
                        var IKNumber          = contractParameters.SingleOrDefault(t => t.ParameterName == EContractParameter.IKNumber.Value());

                        var IKNumberValue = IKNumber != null ? IKNumber.IfStringValue_Value : contract.Value.First() != null?contract.Value.First().HIP_IK : "";

                        var mergeForAllHipsValue   = mergeForAllHips != null ? mergeForAllHips.IfBooleanValue_Value : false;
                        var useKForVorrectionValue = useKForCorrection != null ? useKForCorrection.IfBooleanValue_Value : true;
                        var contactTypeValue       = contractType != null ? contractType.IfStringValue_Value : "7";

                        var hipNameForMergedEdifact = mergeForAllHipsValue ? cls_Get_HIP_Name_for_HIP_IK_Number.Invoke(Connection, Transaction, new P_CAS_GHIPIKfHIPIKN_1207
                        {
                            HIPIKNumber = IKNumberValue
                        }, securityTicket).Result.Name : "";

                        var encryptEdifact = false;
                        if (encryptEdifactParameter != null)
                        {
                            encryptEdifact = encryptEdifactParameter.IfBooleanValue_Value;
                        }

                        var contractCharacteristicID = "000000";
                        if (contractCharacteristicIDParameter != null)
                        {
                            contractCharacteristicID = contractCharacteristicIDParameter.IfStringValue_Value;
                        }


                        var controldocumentExcel = cls_Get_Number_of_Edifacts.Invoke(Connection, Transaction, new P_ARCH_GNoE_0910 {
                            ContractID = contractID.ToString()
                        }, securityTicket).Result;

                        uint controlReference = 1;
                        if (controldocumentExcel != null && (uint)controldocumentExcel.numberOfEdifacts > 0 &&
                            nextEdifactNumberParameter != null && nextEdifactNumberParameter.IfNumericValue_Value > 0)
                        {
                            controlReference = nextEdifactNumberParameter != null?Convert.ToUInt32(nextEdifactNumberParameter.IfNumericValue_Value) : 1;
                        }

                        var casesINContract = contract.Value;
                        var hips            = mergeForAllHipsValue ? new Dictionary <string, List <CaseForReportModel> >()
                        {
                            { "", casesINContract }
                        } : casesINContract.GroupBy(i => i.HIP_IK).ToDictionary(t => t.Key, t => t.ToList());
                        foreach (var hip in hips)
                        {
                            var casesWithHIP_IK  = hip.Value;
                            var baseHipData      = casesWithHIP_IK.First();
                            var mmIkNumber       = Resources.InterchangeSenderID;
                            var minTreatmentDate = baseHipData.TreatmentDay;
                            var maxTreatmentDate = baseHipData.TreatmentDay;
                            var ikNumberForHIP   = mergeForAllHipsValue ? IKNumberValue : baseHipData.HIP_IK;

                            var edi = new EDIFACT();
                            edi.mmIkNumber  = mmIkNumber;
                            edi.hipIkNumber = ikNumberForHIP;

                            foreach (var _case in casesWithHIP_IK)
                            {
                                if (_case.TreatmentDay != DateTime.MinValue && _case.TreatmentDay < minTreatmentDate)
                                {
                                    minTreatmentDate = _case.TreatmentDay;
                                }

                                if (_case.TreatmentDay != DateTime.MaxValue && _case.TreatmentDay > maxTreatmentDate)
                                {
                                    maxTreatmentDate = _case.TreatmentDay;
                                }
                            }

                            edi.Una = "UNA:+,? '\n";
                            var edifactVersion = 3;
                            if (edifactType != null && edifactType.IfStringValue_Value == "4")
                            {
                                edifactVersion = 4;
                            }
                            edi.FileName = String.Format("{0}DRC0{1}", isTestData ? "T" : "E", controlReference.ToString("D3"));

                            #region UNB
                            edi.Unb.Segment1 = "UNOC";
                            edi.Unb.Segment2 = "3";
                            edi.Unb.Segment3 = mmIkNumber;
                            edi.Unb.Segment4 = ikNumberForHIP;
                            // todo: check if this date is always subtracted
                            edi.Unb.Segment5 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                            edi.Unb.Segment6 = DateTime.Now.ToString("HHmm");
                            edi.Unb.Segment7 = controlReference.ToString("D5");
                            edi.Unb.Segment8 = String.Format("{0}DRC0{1}{2}", isTestData ? "T" : "E", controlReference.ToString("D2"), DateTime.Now.ToString("yyMM"));
                            if (isTestData && edifactVersion == 4)
                            {
                                edi.Unb.Segment9 = "1";
                            }

                            #endregion

                            var referenceNumber = 1;
                            foreach (var caseModel in casesWithHIP_IK)
                            {
                                var hipIkNumber = mergeForAllHipsValue ? IKNumberValue : caseModel.HIP_IK;

                                var message = new TransmitionMessage();
                                var gender  = "0";
                                var currentMessageNumber = String.Format("99{0}", referenceNumber.ToString("D8"));

                                #region Gender

                                switch (caseModel.PatientGender)
                                {
                                case 0:
                                    gender = "2";
                                    break;

                                case 1:
                                    gender = "1";
                                    break;

                                case 2:
                                    gender = "3";
                                    break;
                                }

                                #endregion

                                #region Version independent

                                #region UNH

                                message.Unh.Segment1 = currentMessageNumber;
                                message.Unh.Segment2 = messageType != null ? messageType.IfStringValue_Value : "DIR73C";
                                message.Unh.Segment3 = edifactVersion.ToString();
                                message.Unh.Segment4 = "0";
                                message.Unh.Segment5 = "DR";

                                #endregion

                                #region IVK

                                message.Ivk.Segment1 = useKForVorrectionValue ? "10" : Convert.ToInt32(caseModel.NumberOfNegativeTry) > 0 ? "30" : "10";
                                message.Ivk.Segment2 = "01";
                                message.Ivk.Segment3 = mmIkNumber;
                                message.Ivk.Segment4 = hipIkNumber;

                                #endregion

                                #region IBH

                                message.Ibh.Segment1 = caseModel.LANR;
                                message.Ibh.Segment2 = caseModel.BSNR;

                                #endregion

                                #region INF

                                message.Inf.Segment1 = contractCharacteristicID;
                                message.Inf.Segment2 = "";
                                message.Inf.Segment3 = "0";
                                message.Inf.Segment4 = contactTypeValue;

                                #endregion

                                #region INV
                                message.Inv.Segment4 = caseModel.PatientInsuranceNumber;
                                message.Inv.Segment5 = hipIkNumber;
                                message.Inv.Segment6 = caseModel.PatientLastName;
                                message.Inv.Segment7 = caseModel.PatientFirstName;
                                message.Inv.Segment8 = caseModel.PatientBirthday.ToString("yyyyMMdd");
                                message.Inv.Segment9 = gender;

                                #endregion

                                #region DIA

                                message.Dia.Segment1 = caseModel.DiagnoseCode;
                                message.Dia.Segment2 = "G";
                                message.Dia.Segment3 = caseModel.Localization;

                                #endregion

                                #region ABR

                                message.Abr.Segment1  = "";
                                message.Abr.Segment2  = caseModel.GPOS;
                                message.Abr.Segment3  = "";
                                message.Abr.Segment4  = "";
                                message.Abr.Segment5  = "1";
                                message.Abr.Segment6  = caseModel.AmountForThisGPOS.ToString("F", germanCulture);
                                message.Abr.Segment7  = "";
                                message.Abr.Segment8  = "";
                                message.Abr.Segment9  = "";
                                message.Abr.Segment10 = "";
                                message.Abr.Segment11 = caseModel.TreatmentDay.ToString("yyyyMMdd");

                                #endregion

                                #region FKI

                                message.Fki.Segment1 = caseModel.AmountForThisGPOS.ToString("F", germanCulture);
                                message.Fki.Segment2 = "";
                                message.Fki.Segment3 = "";
                                message.Fki.Segment4 = "";
                                message.Fki.Segment5 = "";
                                message.Fki.Segment6 = "";
                                message.Fki.Segment7 = caseModel.AmountForThisGPOS.ToString("F", germanCulture);

                                #endregion

                                #region RGI
                                message.Rgi.Segment1 = minTreatmentDate.ToString("yyyyMMdd");
                                message.Rgi.Segment2 = maxTreatmentDate.ToString("yyyyMMdd");
                                message.Rgi.Segment3 = "1";
                                message.Rgi.Segment4 = mmIkNumber;

                                message.Rgi.Segment5 = useKForVorrectionValue && Convert.ToInt32(caseModel.NumberOfNegativeTry) > 0
                                    ? String.Format("{0}K{1}", caseModel.NumberOfNegativeTry, caseModel.InvoiceNumberForTheHIP.ToString())
                                    : caseModel.InvoiceNumberForTheHIP.ToString();

                                message.Rgi.Segment6 = DateTime.Now.ToString("yyyyMMdd");
                                message.Rgi.Segment7 = "";
                                message.Rgi.Segment8 = Convert.ToUInt32(caseModel.NumberOfNegativeTry).ToString("D3");

                                #endregion

                                #region UNT

                                message.Unt.Segment1 = "10";
                                message.Unt.Segment2 = currentMessageNumber;

                                #endregion

                                #endregion

                                #region Version specific

                                var InvSegment1Value = caseModel.PatientStatusNumber.Replace(" ", string.Empty);
                                switch (edifactVersion)
                                {
                                case 3:
                                    message.Inv.Segment1 = InvSegment1Value.Length < 5 ? InvSegment1Value.Substring(0, 1) + "0001" : InvSegment1Value;
                                    message.Ivk.Segment5 = caseModel.InvoiceNumberForTheHIP.ToString();
                                    break;

                                case 4:
                                    message.Inv.Segment1 = InvSegment1Value.Substring(0, 1);
                                    message.Inv.Segment2 = "";
                                    message.Inv.Segment3 = "";

                                    message.Ivk.Segment5 = "99999999999999";
                                    message.Ivk.Segment6 = hipIkNumber;

                                    break;

                                default:
                                    break;
                                }

                                #endregion

                                edi.transmitionMessages.Add(message);

                                referenceNumber++;
                            }

                            #region UNZ

                            edi.Unz.Segment1 = edi.transmitionMessages.Count.ToString();
                            edi.Unz.Segment2 = controlReference.ToString("D5");

                            #endregion

                            var edifact  = edi.GetEdifact();
                            var edi_path = System.IO.Path.GetTempPath() + edifact.edifactName;
                            var i        = 1;
                            while (File.Exists(edi_path))
                            {
                                edifact.edifactName = string.Format("{0}({1})", edifact.edifactName, i++);
                                edi_path            = System.IO.Path.GetTempPath() + edifact.edifactName;
                            }

                            File.WriteAllText(edi_path, edifact.edifactFileOutput);
                            var fi = new FileInfo(edi_path);
                            edi.decryptedFileSize = fi.Length;
                            edi.encryptedFileSize = fi.Length;

                            var aufFile  = edi.GetAufFile();
                            var path_auf = System.IO.Path.GetTempPath() + aufFile.aufName;
                            File.WriteAllText(path_auf, aufFile.aufFileOutput);

                            var files = new List <string>();

                            files.Add(edi_path);
                            files.Add(path_auf);

                            var zipPath = System.IO.Path.GetTempPath() + edifact.edifactName + ".zip";
                            ZipFIlesUtils.AddToArchive(zipPath, files);

                            var documentEdifact = new Documents();
                            documentEdifact.documentName           = "Export von " + minTreatmentDate.ToString("dd.MM.yyyy") + " - " + maxTreatmentDate.ToString("dd.MM.yyyy");
                            documentEdifact.documentOutputLocation = zipPath;
                            documentEdifact.ContractID             = contractID;
                            documentEdifact.receiver = mergeForAllHipsValue ? hipNameForMergedEdifact : casesWithHIP_IK[0].HIP;
                            documentEdifact.mimeType = "Application/Edifact";

                            documents.Add(documentEdifact);

                            controlReference++;
                        }

                        #region Update parameters
                        cls_Save_Contract_Parameter.Invoke(Connection, Transaction, new P_MD_SCP_1754()
                        {
                            Name         = EContractParameter.NextEdifactNumber.Value(),
                            ContractID   = contractID,
                            NumericValue = Convert.ToDouble(controlReference)
                        }, securityTicket);
                        #endregion
                    }
                }
                #endregion

                #region Excel report generation
                Documents documentExcel = new Documents();
                documentExcel.documentName           = "ExcelReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm");
                documentExcel.documentOutputLocation = GenerateReportCases.CreateCaseXlsReport(cases.ToList(), documentExcel.documentName);
                documentExcel.mimeType = UtilMethods.GetMimeType(documentExcel.documentOutputLocation);
                documentExcel.receiver = "MM";
                documents.Add(documentExcel);
                #endregion

                #region Negative feedback edifact
                if (Parameter.StatusTo == 5 && !String.IsNullOrEmpty(Parameter.HipIkNumber))
                {
                    var files    = new List <string>();
                    var edi_path = Path.GetTempPath() + Parameter.EdifactFileName;
                    File.WriteAllText(edi_path, Parameter.EdifactMessage);
                    files.Add(edi_path);

                    var zipPath = Path.GetTempPath() + Parameter.EdifactFileName + ".zip";
                    ZipFIlesUtils.AddToArchive(zipPath, files);

                    var errorEdifact = new Documents();
                    errorEdifact.documentName           = String.Format("Import von {0} - {1}", earliestFsStatusDate.ToString("dd.MM.yyyy"), latestFsStatusDate.ToString("dd.MM.yyyy"));
                    errorEdifact.documentOutputLocation = zipPath;
                    errorEdifact.receiver = cls_Get_HIP_Name_for_HIP_IK_Number.Invoke(Connection, Transaction, new P_CAS_GHIPIKfHIPIKN_1207()
                    {
                        HIPIKNumber = Parameter.HipIkNumber
                    }, securityTicket).Result.Name;
                    errorEdifact.mimeType = "Application/Edifact_Error";

                    documents.Add(errorEdifact);
                }
                #endregion

                #region Document upload
                foreach (var document in documents)
                {
                    var ms = new MemoryStream(File.ReadAllBytes(document.documentOutputLocation));

                    var byteArrayFile    = ms.ToArray();
                    var _providerFactory = ProviderFactory.Instance;
                    var documentProvider = _providerFactory.CreateDocumentServiceProvider();
                    var uploadedFrom     = HttpContext.Current.Request.UserHostAddress;
                    var documentID       = documentProvider.UploadDocument(byteArrayFile, document.documentOutputLocation, securityTicket.SessionTicket, uploadedFrom);
                    var downloadURL      = documentProvider.GenerateImageThumbnailLink(documentID, securityTicket.SessionTicket, false, 200);

                    var parameterDoc = new P_ARCH_UD_1326();
                    parameterDoc.DocumentID   = documentID;
                    parameterDoc.Mime         = document.mimeType;
                    parameterDoc.DocumentName = document.documentName;
                    parameterDoc.DocumentDate = DateForElastic;
                    parameterDoc.Receiver     = document.receiver;
                    parameterDoc.ContractID   = document.ContractID;
                    if (!Parameter.AreCasesFiltered)
                    {
                        if (parameterDoc.Mime == "Application/Edifact")
                        {
                            parameterDoc.Description = parameterDoc.DocumentName;
                        }
                        else
                        {
                            if (Parameter.AreCasesPositive)
                            {
                                parameterDoc.Description = "DATEV";
                            }
                            else
                            {
                                parameterDoc.Description = "EDIFACT";
                            }
                        }
                    }
                    else
                    {
                        if (Parameter.StatusTo == 5)
                        {
                            if (parameterDoc.Mime == "Application/Edifact_Error")
                            {
                                parameterDoc.Description = parameterDoc.DocumentName;
                            }
                            else
                            {
                                parameterDoc.Description = "KV Fehler";
                            }
                        }
                        else
                        {
                            parameterDoc.Description = "KV Import";
                        }
                    }

                    cls_Upload_Report.Invoke(Connection, Transaction, parameterDoc, securityTicket);
                }
                #endregion
            }

            #region Receipt pdf generation
            var create_pdf_report = false;
            try
            {
                create_pdf_report = Boolean.Parse(WebConfigurationManager.AppSettings["generateReceiptPdf"]);
            }
            catch { }

            if (create_pdf_report && Parameter.StatusTo == 7)
            {
                cls_Create_Pdf_Report.Invoke(Connection, Transaction, new P_CAS_CPR_1050()
                {
                    cases = cases
                }, securityTicket);
            }
            #endregion



            #region Elastic import
            if (cases_to_submit.Count != 0)
            {
                Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(cases_to_submit, securityTicket.TenantID.ToString());
            }
            if (settlements.Count != 0)
            {
                Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());
            }
            if (patientDetailList.Count != 0)
            {
                Add_New_Patient.ImportPatientDetailsToElastic(patientDetailList, securityTicket.TenantID.ToString());
            }
            #endregion

            returnValue.Result.caseList = cases.Select(t => new CaseLogObject()
            {
                BillPositionNumber = t.InvoiceNumberForTheHIP.ToString(),
                BillPositionType   = t.CaseType,
                CaseNumber         = t.CaseNumber.ToString()
            }).ToArray();

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

            var         temporary_doctor_bpt_id = Guid.Empty;
            List <Guid> case_ids = new List <Guid>();
            var         BusinessParticipantID = Guid.Empty;

            #region PURGE TEMPORARY DOCTOR
            var temporary_doctor = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                HEC_DoctorID = Parameter.TemporaryDoctorID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
            }).SingleOrDefault();
            if (temporary_doctor != null)
            {
                temporary_doctor.IsDeleted = true;
                temporary_doctor.Save(Connection, Transaction);

                var temporary_doctor_bpt = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    CMN_BPT_BusinessParticipantID = temporary_doctor.BusinessParticipant_RefID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                }).SingleOrDefault();
                if (temporary_doctor_bpt != null)
                {
                    temporary_doctor_bpt_id        = temporary_doctor_bpt.CMN_BPT_BusinessParticipantID;
                    temporary_doctor_bpt.IsDeleted = true;
                    temporary_doctor_bpt.Save(Connection, Transaction);

                    var temporary_doctor_person_info = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query()
                    {
                        CMN_PER_PersonInfoID = temporary_doctor_bpt.IfNaturalPerson_CMN_PER_PersonInfo_RefID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                    }).SingleOrDefault();
                    if (temporary_doctor_person_info != null)
                    {
                        temporary_doctor_person_info.IsDeleted = true;
                        temporary_doctor_person_info.Save(Connection, Transaction);

                        var temporary_doctor_communication_contact = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, new ORM_CMN_PER_CommunicationContact.Query()
                        {
                            PersonInfo_RefID = temporary_doctor_person_info.CMN_PER_PersonInfoID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                        });
                        foreach (var tdc in temporary_doctor_communication_contact)
                        {
                            tdc.IsDeleted = true;
                            tdc.Save(Connection, Transaction);
                        }
                    }
                }

                var temporary_doctor_universal_property_value = ORM_HEC_Doctor_UniversalPropertyValue.Query.Search(Connection, Transaction, new ORM_HEC_Doctor_UniversalPropertyValue.Query()
                {
                    HEC_Doctor_RefID = temporary_doctor.HEC_DoctorID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                }).SingleOrDefault();
                if (temporary_doctor_universal_property_value != null)
                {
                    temporary_doctor_universal_property_value.IsDeleted = true;
                    temporary_doctor_universal_property_value.Save(Connection, Transaction);

                    var temporary_doctor_universal_property = ORM_HEC_Doctor_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_Doctor_UniversalProperty.Query()
                    {
                        PropertyName = "Comment", HEC_Doctor_UniversalPropertyID = temporary_doctor_universal_property_value.HEC_Doctor_UniversalPropertyValueID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                    }).SingleOrDefault();
                    if (temporary_doctor_universal_property != null)
                    {
                        temporary_doctor_universal_property.IsDeleted = true;
                        temporary_doctor_universal_property.Save(Connection, Transaction);
                    }
                }
            }
            #endregion

            #region GET MERGED DOCTOR BPT
            var merge_doctor = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                HEC_DoctorID = Parameter.DoctorID, Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).SingleOrDefault();
            if (merge_doctor != null)
            {
                BusinessParticipantID = merge_doctor.BusinessParticipant_RefID;
            }
            else
            {
                throw new Exception("Doctor not found");
            }
            #endregion

            #region LINK AFTERCARES TO MERGED DOCTOR
            var aftercare_planned_actions = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false,
                IsPerformed  = false,
                IsCancelled  = false,
                ToBePerformedBy_BusinessParticipant_RefID = temporary_doctor_bpt_id
            });

            foreach (var aftercare in aftercare_planned_actions)
            {
                aftercare.ToBePerformedBy_BusinessParticipant_RefID = BusinessParticipantID;
                aftercare.Modification_Timestamp = DateTime.Now;

                aftercare.Save(Connection, Transaction);

                var case_id = ORM_HEC_CAS_Case_RelevantPlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case_RelevantPlannedAction.Query()
                {
                    PlannedAction_RefID = aftercare.HEC_ACT_PlannedActionID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                }).SingleOrDefault();
                if (case_id != null)
                {
                    case_ids.Add(case_id.Case_RefID);
                }
            }
            #endregion

            #region UPDATE ELASTIC
            List <Case_Model>                    cases                         = new List <Case_Model>();
            List <Aftercare_Model>               aftercares                    = new List <Aftercare_Model>();
            List <PatientDetailViewModel>        patientDetailList             = new List <PatientDetailViewModel>();
            List <Settlement_Model>              settlements                   = new List <Settlement_Model>();
            Dictionary <Guid, CAS_GDDfDID_1608>  diagnose_data_cache           = new Dictionary <Guid, CAS_GDDfDID_1608>();
            Dictionary <Guid, CAS_GDDfDID_1614>  drug_data_cache               = new Dictionary <Guid, CAS_GDDfDID_1614>();
            Dictionary <Guid, DO_GDDfDID_0823>   treatment_doctor_data_cache   = new Dictionary <Guid, DO_GDDfDID_0823>();
            Dictionary <Guid, P_PA_GPDfPID_1124> patient_data_cache            = new Dictionary <Guid, P_PA_GPDfPID_1124>();
            Dictionary <Guid, DO_GPDfPID_1432>   treatment_practice_data_cache = new Dictionary <Guid, DO_GPDfPID_1432>();
            var merged_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
            {
                DoctorID = Parameter.DoctorID
            }, securityTicket).Result.SingleOrDefault();

            var doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
            {
                DoctorID = Parameter.DoctorID
            }, securityTicket).Result.SingleOrDefault();
            if (doctor_details != null)
            {
                foreach (var case_id in case_ids)
                {
                    var treatment_planned_action = cls_Get_Treatment_Planned_Action_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GTPAfCID_0946()
                    {
                        CaseID = case_id
                    }, securityTicket).Result;
                    if (treatment_planned_action != null)
                    {
                        #region IF CASE SUBMITTED, CREATE AFTERCARE
                        if (treatment_planned_action.is_treatment_performed)
                        {
                            var case_details = cls_Get_Case_Details_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCDfCID_1435()
                            {
                                CaseID = case_id
                            }, securityTicket).Result;

                            #region CACHE
                            if (!diagnose_data_cache.ContainsKey(case_details.diagnose_id))
                            {
                                diagnose_data_cache.Add(case_details.diagnose_id, cls_Get_Diagnose_Details_for_DiagnoseID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1608()
                                {
                                    DiagnoseID = case_details.diagnose_id
                                }, securityTicket).Result);
                            }
                            var diagnose_details = diagnose_data_cache[case_details.diagnose_id];

                            if (!drug_data_cache.ContainsKey(case_details.drug_id))
                            {
                                drug_data_cache.Add(case_details.drug_id, cls_Get_Drug_Details_for_DrugID.Invoke(Connection, Transaction, new P_CAS_GDDfDID_1614()
                                {
                                    DrugID = case_details.drug_id
                                }, securityTicket).Result);
                            }
                            var drug_details = drug_data_cache[case_details.drug_id];

                            if (!treatment_doctor_data_cache.ContainsKey(case_details.op_doctor_id))
                            {
                                treatment_doctor_data_cache.Add(case_details.op_doctor_id, cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                                {
                                    DoctorID = case_details.op_doctor_id
                                }, securityTicket).Result.SingleOrDefault());
                            }
                            var treatment_doctor_details = treatment_doctor_data_cache[case_details.op_doctor_id];

                            if (!patient_data_cache.ContainsKey(case_details.patient_id))
                            {
                                patient_data_cache.Add(case_details.patient_id, cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                                {
                                    PatientID = case_details.patient_id
                                }, securityTicket).Result);
                            }
                            var patient_details = patient_data_cache[case_details.patient_id];

                            if (!treatment_practice_data_cache.ContainsKey(case_details.practice_id))
                            {
                                treatment_practice_data_cache.Add(case_details.practice_id, cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
                                {
                                    PracticeID = case_details.practice_id
                                }, securityTicket).Result.FirstOrDefault());
                            }
                            var treatment_practice_details = treatment_practice_data_cache[case_details.practice_id];

                            #endregion

                            if (case_details != null)
                            {
                                #region CREATE NEW AFTERCARE
                                Aftercare_Model aftercare = new Aftercare_Model();
                                aftercare.hip_ik_number         = patient_details.HealthInsurance_IKNumber;
                                aftercare.aftercare_doctor_name = MMDocConnectDocApp.GenericUtils.GetDoctorName(merged_doctor_details);
                                aftercare.diagnose                  = diagnose_details != null ? diagnose_details.diagnose_name + " (" + diagnose_details.catalog_display_name + ": " + diagnose_details.diagnose_icd_10 + ")" : "";
                                aftercare.id                        = case_details.aftercare_planned_action_id.ToString();
                                aftercare.localization              = case_details.localization;
                                aftercare.patient_birthdate         = case_details.Patient_BirthDate;
                                aftercare.patient_birthdate_string  = case_details.Patient_BirthDate.ToString("dd.MM.yyyy");
                                aftercare.patient_name              = patient_details != null ? patient_details.patient_last_name + ", " + patient_details.patient_first_name : "";
                                aftercare.practice_id               = merged_doctor_details.practice_id.ToString();
                                aftercare.status                    = "AC1";
                                aftercare.treatment_date            = case_details.treatment_date;
                                aftercare.treatment_date_day_month  = case_details.treatment_date.ToString("dd.MM.");
                                aftercare.treatment_date_month_year = case_details.treatment_date.ToString("MMMM yyyy", new System.Globalization.CultureInfo("de", true));
                                aftercare.treatment_doctor_name     = treatment_doctor_details != null?MMDocConnectDocApp.GenericUtils.GetDoctorName(treatment_doctor_details) : "-";

                                aftercare.treatment_doctor_practice_name = treatment_doctor_details.practice;
                                aftercare.case_id = case_id.ToString();
                                aftercare.hip     = patient_details.health_insurance_provider;
                                aftercare.patient_insurance_number = patient_details.insurance_id;
                                aftercare.op_lanr = treatment_doctor_details == null ? "" : treatment_doctor_details.lanr;
                                aftercare.ac_lanr = merged_doctor_details.lanr;
                                aftercare.bsnr    = treatment_doctor_details == null ? "" : treatment_doctor_details.BSNR;
                                aftercare.aftercare_doctor_account_id  = merged_doctor_details.doctor_account_id.ToString();
                                aftercare.aftercare_doctor_practice_id = Parameter.DoctorID.ToString();
                                aftercare.treatment_doctor_id          = treatment_doctor_details == null ? "" : treatment_doctor_details.id.ToString();
                                aftercare.diagnose_id = case_details.diagnose_id.ToString();
                                aftercare.drug_id     = case_details.drug_id.ToString();
                                aftercare.patient_id  = case_details.patient_id.ToString();
                                aftercare.treatment_doctors_practice_id = case_details.practice_id.ToString();

                                aftercares.Add(aftercare);

                                PatientDetailViewModel patientDetal_elastic = new PatientDetailViewModel();
                                patientDetal_elastic.id                           = aftercare.id;
                                patientDetal_elastic.drug_id                      = aftercare.drug_id;
                                patientDetal_elastic.practice_id                  = aftercare.practice_id;
                                patientDetal_elastic.case_id                      = aftercare.case_id;
                                patientDetal_elastic.date                         = aftercare.treatment_date;
                                patientDetal_elastic.date_string                  = aftercare.treatment_date.ToString("dd.MM.");
                                patientDetal_elastic.detail_type                  = "ac";
                                patientDetal_elastic.diagnose_or_medication       = aftercare.diagnose;
                                patientDetal_elastic.doctor                       = aftercare.aftercare_doctor_name;
                                patientDetal_elastic.localisation                 = aftercare.localization;
                                patientDetal_elastic.patient_id                   = aftercare.patient_id;
                                patientDetal_elastic.treatment_doctor_id          = aftercare.treatment_doctor_id;
                                patientDetal_elastic.aftercare_doctor_practice_id = aftercare.aftercare_doctor_practice_id;
                                patientDetal_elastic.diagnose_id                  = aftercare.diagnose_id;
                                patientDetal_elastic.status                       = "FS0";
                                patientDetal_elastic.hip_ik                       = patient_details.HealthInsurance_IKNumber;

                                patientDetailList.Add(patientDetal_elastic);
                                #endregion

                                #region Update settlement
                                var settlement = Get_Settlement.GetSettlementForID(case_details.treatment_planned_action_id.ToString(), securityTicket);
                                if (settlement != null)
                                {
                                    settlement.acpractice = merged_doctor_details.practice;
                                    settlement.aftercare_doctor_practice_id = merged_doctor_details.id.ToString();

                                    settlements.Add(settlement);
                                }
                                #endregion
                            }
                        }
                        #endregion

                        #region IF CASE NOT SUMBITTED, EDIT AFTERCARE DATA
                        else
                        {
                            var planning_case = Get_Cases.GetCaseforCaseID(case_id.ToString(), securityTicket);
                            planning_case.aftercare_doctor_lanr        = merge_doctor.DoctorIDNumber;
                            planning_case.aftercare_doctor_practice_id = merge_doctor.HEC_DoctorID.ToString();

                            var practice_details = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
                            {
                                PracticeID = doctor_details.practice_id
                            }, securityTicket).Result.FirstOrDefault();
                            if (practice_details != null)
                            {
                                planning_case.aftercare_doctors_practice_name = practice_details.practice_name;
                                planning_case.aftercare_name          = MMDocConnectDocApp.GenericUtils.GetDoctorName(doctor_details);
                                planning_case.aftercare_practice_bsnr = practice_details.practice_BSNR;
                                planning_case.is_aftercare_doctor     = true;
                            }

                            cases.Add(planning_case);
                        }
                        #endregion
                    }
                }

                #region UPDATE LAST USED AFTERCARE DOCTORS LIST
                var types  = Elastic_Utils.GetAllTypes(securityTicket.TenantID.ToString());
                var length = Guid.Empty.ToString().Length;
                length += 5;
                List <string> last_used_types = new List <string>();
                for (int i = 0; i < types.Length; i += length)
                {
                    int index = types.IndexOf("user_", i);
                    if (index != -1 && !last_used_types.Contains(types.Substring(index, length)))
                    {
                        last_used_types.Add(types.Substring(index, length));
                    }
                }

                foreach (var type in last_used_types)
                {
                    Practice_Doctor_Last_Used_Model new_last_used = new Practice_Doctor_Last_Used_Model();
                    try
                    {
                        var last_used = Get_Practices_and_Doctors.GetLastUsedDoctorPracticeForID(Parameter.TemporaryDoctorID.ToString(), type, securityTicket);

                        new_last_used.display_name = GenericUtils.GetDoctorName(doctor_details) + "(" + doctor_details.lanr + ")";
                        new_last_used.id           = Parameter.DoctorID.ToString();
                        new_last_used.practice_id  = doctor_details.practice_id.ToString();
                        new_last_used.date_of_use  = last_used.date_of_use;

                        Add_New_Practice_Last_Used.Delete_Practice_Last_Used(securityTicket.TenantID.ToString(), type, Parameter.TemporaryDoctorID.ToString());
                        Add_New_Practice_Last_Used.Import_Practice_Last_Used_Data_to_ElasticDB(new List <Practice_Doctor_Last_Used_Model>()
                        {
                            new_last_used
                        }, securityTicket.TenantID.ToString(), type.Substring(5));
                    }
                    catch (Exception ex)
                    {
                        // left empty because it's not really an exception, rather a check whether object with given id exists
                    }
                }
                #endregion

                if (aftercares.Count != 0)
                {
                    Add_New_Aftercare.Import_Aftercare_Data_to_ElasticDB(aftercares, securityTicket.TenantID.ToString());
                }

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

                if (cases.Count != 0)
                {
                    Add_New_Case.Import_Case_Data_to_ElasticDB(cases, securityTicket.TenantID.ToString());
                }

                if (settlements.Count != 0)
                {
                    Add_new_Settlement.Import_Settlement_to_ElasticDB(settlements, securityTicket.TenantID.ToString());
                }

                Add_New_Practice.Delete_Doctor_Practice(securityTicket.TenantID.ToString(), Parameter.TemporaryDoctorID.ToString());
            }
            else
            {
                throw new Exception("Doctor not found");
            }

            return(returnValue);

            #endregion

            #endregion UserCode
        }