Ejemplo n.º 1
0
        public List <Submitted_Case_Model> GetSubmittedCasesList(ElasticParameterObject sort_parameter, string connectionString, string sessionTicket, out TransactionalInformation transaction)
        {
            var method = MethodInfo.GetCurrentMethod();
            var ipInfo = Util.GetIPInfo(HttpContext.Current.Request);

            transaction = new TransactionalInformation();
            List <Submitted_Case_Model> SubmittedCasesList = new List <Submitted_Case_Model>();
            var securityTicket = VerifySessionToken(sessionTicket);

            try
            {
                SubmittedCasesList = Get_Submitted_Cases.GetAllCases(sort_parameter, securityTicket);
            }
            catch (Exception ex)
            {
                Logger.LogInfo(new LogEntry(ipInfo.address, ipInfo.agent, connectionString, method, securityTicket, ex));

                transaction.ReturnMessage = new List <string>();
                string errorMessage = ex.Message;
                transaction.ReturnStatus = false;
                transaction.ReturnMessage.Add(errorMessage);
                transaction.IsAuthenicated = true;
                transaction.IsException    = true;
            }

            return(SubmittedCasesList);
        }
Ejemplo n.º 2
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
        }
Ejemplo n.º 3
0
        public Guid[] ChangeCaseStatus(bool all_selected, Guid[] selected_action_ids, Guid[] deselected_action_ids, FilterObject filter, Guid[] case_ids, bool?is_management_fee_waived, CaseStatus?case_status, string case_status_ground, string connectionString, string sessionTicket, out TransactionalInformation transaction)
        {
            var method = MethodInfo.GetCurrentMethod();
            var ipInfo = Util.GetIPInfo(HttpContext.Current.Request);

            transaction = new TransactionalInformation();
            var securityTicket = VerifySessionToken(sessionTicket);

            try
            {
                if (case_status.HasValue)
                {
                    var parameter = new P_CAS_CPASfPAID_1654()
                    {
                        change_status = case_status.HasValue, planned_action_ids = case_ids, new_status = (int)case_status.Value, new_status_ground = case_status_ground
                    };
                    cls_Change_PerformedAction_Status_for_PlannedActionID.Invoke(connectionString, parameter, securityTicket);

                    Logger.LogInfo(new LogEntry(ipInfo.address, ipInfo.agent, connectionString, method, securityTicket, parameter));
                }

                if (is_management_fee_waived.HasValue)
                {
                    if (all_selected || deselected_action_ids.Length != 0)
                    {
                        ElasticParameterObject filter_by = new ElasticParameterObject();
                        filter_by.date_from = filter.date_from;
                        filter_by.date_to   = filter.date_to;
                        filter_by.filter_by.filter_status = filter.filter_by.filter_status;
                        filter_by.filter_by.filter_type   = filter.filter_by.filter_type;
                        filter_by.search_params           = filter.search_params;

                        var ids = Get_Submitted_Cases.GetSubmittedCasesFilteredIDs(filter_by, null, securityTicket).Select(cas => Guid.Parse(cas.id));
                        selected_action_ids = ids.Except(deselected_action_ids).ToArray();
                    }
                    var parameter = new P_CAS_CMFSfPAID_1502()
                    {
                        is_management_fee_waived = is_management_fee_waived.Value, planned_action_ids = selected_action_ids
                    };
                    cls_Change_ManagementFee_Status_for_PlannedActionID.Invoke(connectionString, parameter, securityTicket);

                    Logger.LogInfo(new LogEntry(ipInfo.address, ipInfo.agent, connectionString, method, securityTicket, parameter));
                }
            }
            catch (Exception ex)
            {
                Logger.LogInfo(new LogEntry(ipInfo.address, ipInfo.agent, connectionString, method, securityTicket, ex));

                transaction.ReturnMessage = new List <string>();
                transaction.ReturnStatus  = false;
                transaction.ReturnMessage.Add(ex.Message);
                if (ex.InnerException != null)
                {
                    transaction.ReturnMessage.Add(ex.InnerException.Message);
                    transaction.ReturnMessage.Add(ex.InnerException.StackTrace);

                    if (ex.InnerException.InnerException != null)
                    {
                        transaction.ReturnMessage.Add(ex.InnerException.InnerException.Message);
                    }
                }
                transaction.IsAuthenicated = true;
                transaction.IsException    = true;
            }

            return(case_ids);
        }
Ejemplo n.º 4
0
        public Guid[] GetEligibleCases(bool all_selected, Guid[] selected_action_ids, Guid[] deselected_action_ids, FilterObject filter, CaseStatus?case_status, string connectionString, string sessionTicket, out TransactionalInformation transaction)
        {
            var method = MethodInfo.GetCurrentMethod();
            var ipInfo = Util.GetIPInfo(HttpContext.Current.Request);

            transaction = new TransactionalInformation();
            var securityTicket = VerifySessionToken(sessionTicket);

            Submitted_Case_Model[] selected_cases = new Submitted_Case_Model[] { };

            try
            {
                if (all_selected || deselected_action_ids.Length != 0)
                {
                    ElasticParameterObject filter_by = new ElasticParameterObject();
                    filter_by.date_from = filter.date_from;
                    filter_by.date_to   = filter.date_to;
                    filter_by.filter_by.filter_status = filter.filter_by.filter_status;
                    filter_by.filter_by.filter_type   = filter.filter_by.filter_type;
                    filter_by.search_params           = filter.search_params;

                    selected_cases = Get_Submitted_Cases.GetSubmittedCasesFilteredIDs(filter_by, case_status.HasValue ? case_status.Value.ToString().ToLower() : null, securityTicket);
                }
                else
                {
                    selected_cases = Get_Submitted_Cases.GetSubmittedCaseforIDArray(Array.ConvertAll(selected_action_ids, x => x.ToString()), case_status.HasValue ? case_status.Value.ToString().ToLower() : null, securityTicket);
                }

                selected_action_ids = selected_cases.Select(ac =>
                {
                    if (ac.status == "FS13")
                    {
                        return(Guid.Empty);
                    }

                    if (ac.type == "op")
                    {
                        return(Guid.Parse(ac.id));
                    }
                    else
                    {
                        var acs  = selected_cases.Where(selAc => selAc.type == "ac" && selAc.status == "FS8").GroupBy(selAc => selAc.case_id, selAc => selAc.id, (key, value) => new { CaseID = key, AcIDs = value.ToList() });
                        var data = acs.Where(t => t.CaseID == ac.case_id);
                        if (data.Count() != 0 && data.Single().AcIDs.Count > 1)
                        {
                            return(Guid.Empty);
                        }
                        else
                        {
                            if (ac.status != "FS8")
                            {
                                return(Guid.Parse(ac.id));
                            }
                            else if (cls_Get_is_Aftercares_Status_Editable_for_CaseID.Invoke(connectionString, new P_CAS_GiASEfCID_1127()
                            {
                                CaseID = Guid.Parse(ac.case_id)
                            }, securityTicket).Result.IsEditable)
                            {
                                return(Guid.Parse(ac.id));
                            }
                        }
                    }

                    return(Guid.Empty);
                }).Where(id => id != Guid.Empty).ToArray();

                if (deselected_action_ids.Length != 0)
                {
                    selected_action_ids = selected_action_ids.Except(deselected_action_ids).ToArray();
                }
            }
            catch (Exception ex)
            {
                Logger.LogInfo(new LogEntry(ipInfo.address, ipInfo.agent, connectionString, method, securityTicket, ex));

                transaction.ReturnMessage = new List <string>();
                string errorMessage = ex.Message;
                transaction.ReturnStatus = false;
                transaction.ReturnMessage.Add(errorMessage);
                transaction.IsAuthenicated = true;
                transaction.IsException    = true;
            }

            return(selected_action_ids);
        }
        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.º 6
0
        protected static FR_Guids Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_CMFSfPAID_1502 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guids();
            List <Submitted_Case_Model> submitted_cases = new List <Submitted_Case_Model>();

            // todo: update to support OCT
            foreach (var planned_action_id in Parameter.planned_action_ids)
            {
                var action_gpmid = cls_Get_PlannedActionType_GlobalPropertyMatchingID_for_PlannedActionID.Invoke(Connection, Transaction, new P_CAS_GPAGPMIDfPAID_1652()
                {
                    PlannedActionID = planned_action_id
                }, securityTicket).Result.GlobalPropertyMatchingID;
                var is_treatment = action_gpmid == EActionType.PlannedOperation.Value();
                var case_id      = Guid.Empty;
                if (is_treatment)
                {
                    ORM_HEC_ACT_PlannedAction.Query planned_actionQ = new ORM_HEC_ACT_PlannedAction.Query();
                    planned_actionQ.HEC_ACT_PlannedActionID = planned_action_id;
                    planned_actionQ.Tenant_RefID            = securityTicket.TenantID;
                    planned_actionQ.IsDeleted = false;
                    var planned_action = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, planned_actionQ).SingleOrDefault();
                    if (planned_action != null)
                    {
                        ORM_HEC_CAS_Case_RelevantPerformedAction.Query relevant_performed_actionQ = new ORM_HEC_CAS_Case_RelevantPerformedAction.Query();
                        relevant_performed_actionQ.PerformedAction_RefID = planned_action.IfPlannedFollowup_PreviousAction_RefID;
                        relevant_performed_actionQ.Tenant_RefID          = securityTicket.TenantID;
                        relevant_performed_actionQ.IsDeleted             = false;

                        var relevant_performed_action = ORM_HEC_CAS_Case_RelevantPerformedAction.Query.Search(Connection, Transaction, relevant_performed_actionQ).SingleOrDefault();
                        if (relevant_performed_action != null)
                        {
                            case_id = relevant_performed_action.Case_RefID;
                        }
                    }
                }
                else
                {
                    ORM_HEC_CAS_Case_RelevantPlannedAction.Query relevant_planned_actionQ = new ORM_HEC_CAS_Case_RelevantPlannedAction.Query();
                    relevant_planned_actionQ.PlannedAction_RefID = planned_action_id;
                    relevant_planned_actionQ.Tenant_RefID        = securityTicket.TenantID;
                    relevant_planned_actionQ.IsDeleted           = false;
                    var relevant_planned_action = ORM_HEC_CAS_Case_RelevantPlannedAction.Query.Search(Connection, Transaction, relevant_planned_actionQ).SingleOrDefault();
                    if (relevant_planned_action != null)
                    {
                        case_id = relevant_planned_action.Case_RefID;
                    }
                }

                var gpos_type = EGposType.Aftercare.Value();
                if (action_gpmid == EActionType.PlannedOperation.Value())
                {
                    gpos_type = EGposType.Operation.Value();
                }
                else if (action_gpmid == EActionType.PlannedOct.Value())
                {
                    gpos_type = EGposType.Oct.Value();
                }

                var all_bill_positions = cls_Get_BillPositionIDs_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GBPIDsfCID_0928()
                {
                    CaseID = case_id
                }, securityTicket).Result;
                if (all_bill_positions.Any())
                {
                    List <CAS_GBPIDsfCID_0928> bill_positions_to_update = new List <CAS_GBPIDsfCID_0928>();
                    if (action_gpmid == EActionType.PlannedOperation.Value())
                    {
                        bill_positions_to_update = all_bill_positions.Where(t => t.gpos_type == gpos_type).ToList();
                    }
                    else if (action_gpmid == EActionType.PlannedOct.Value())
                    {
                        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 relevant_octs = cls_Get_RelevanActionIDs_for_CaseID_and_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GRAIDsfCIDaATID_1547()
                        {
                            CaseID       = case_id,
                            ActionTypeID = oct_planned_action_type_id
                        }, securityTicket).Result;

                        var index = -1;
                        for (int i = 0; i < relevant_octs.Length; i++)
                        {
                            if (relevant_octs[i].action_id == planned_action_id)
                            {
                                index = i;
                                break;
                            }
                        }

                        var bill_positions = all_bill_positions.Where(t => t.gpos_type == EGposType.Oct.Value()).ToList();
                        var bill_position  = bill_positions.Any() ? bill_positions[index] : bill_positions.First();
                        bill_positions_to_update.Add(bill_position);
                    }
                    else
                    {
                        var aftercare_planned_action_type_id = cls_Get_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GATID_1514()
                        {
                            action_type_gpmid = EActionType.PlannedAftercare.Value()
                        }, securityTicket).Result;
                        var relevant_aftercares = cls_Get_RelevanActionIDs_for_CaseID_and_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GRAIDsfCIDaATID_1547()
                        {
                            CaseID       = case_id,
                            ActionTypeID = aftercare_planned_action_type_id
                        }, securityTicket).Result;

                        var index = -1;
                        for (int i = 0; i < relevant_aftercares.Length; i++)
                        {
                            if (relevant_aftercares[i].action_id == planned_action_id)
                            {
                                index = i;
                                break;
                            }
                        }

                        var bill_positions = all_bill_positions.Where(t => t.gpos_type == EGposType.Aftercare.Value()).ToList();
                        var bill_position  = bill_positions.Any() ? bill_positions[index] : bill_positions.First();
                        bill_positions_to_update.Add(bill_position);

                        foreach (var other_bill_position in bill_positions)
                        {
                            var update_bill_position_status = false;

                            var any_covered_diagnoses = ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_2_PotentialDiagnosis.Query()
                            {
                                HEC_BIL_PotentialCode_RefID = other_bill_position.gpos_id,
                                Tenant_RefID = securityTicket.TenantID,
                                IsDeleted    = false
                            }).Any();

                            if (any_covered_diagnoses)
                            {
                                update_bill_position_status = ORM_HEC_BIL_PotentialCode_2_HealthcareProduct.Query.Search(Connection, Transaction, new ORM_HEC_BIL_PotentialCode_2_HealthcareProduct.Query()
                                {
                                    HEC_BIL_PotentialCode_RefID = other_bill_position.gpos_id,
                                    Tenant_RefID = securityTicket.TenantID,
                                    IsDeleted    = false
                                }).Any();
                            }
                            else
                            {
                                update_bill_position_status = true;
                            }

                            if (update_bill_position_status)
                            {
                                bill_positions_to_update.Add(other_bill_position);
                            }
                        }
                    }

                    foreach (var case_bill_position in bill_positions_to_update)
                    {
                        var gpos_management_fee_property_value = ORM_BIL_BillPosition_PropertyValue.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_PropertyValue.Query()
                        {
                            BIL_BillPosition_RefID = case_bill_position.bill_position_id,
                            Tenant_RefID           = securityTicket.TenantID,
                            IsDeleted   = false,
                            PropertyKey = "mm.doc.connect.management.fee"
                        }).SingleOrDefault();

                        if (gpos_management_fee_property_value == null)
                        {
                            gpos_management_fee_property_value = new ORM_BIL_BillPosition_PropertyValue();
                            gpos_management_fee_property_value.BIL_BillPosition_RefID = case_bill_position.bill_position_id;
                            gpos_management_fee_property_value.PropertyKey            = "mm.doc.connect.management.fee";
                            gpos_management_fee_property_value.Tenant_RefID           = securityTicket.TenantID;
                        }

                        gpos_management_fee_property_value.PropertyValue          = Parameter.is_management_fee_waived ? "waived" : "deducted";
                        gpos_management_fee_property_value.Modification_Timestamp = DateTime.Now;

                        gpos_management_fee_property_value.Save(Connection, Transaction);
                    }
                }

                var submitted_case = Get_Submitted_Cases.GetSubmittedCaseforSubmittedCaseID(planned_action_id.ToString(), securityTicket);
                submitted_case.management_pauschale = Parameter.is_management_fee_waived ? "waived" : "deducted";

                submitted_cases.Add(submitted_case);
            }

            Add_New_Submitted_Case.Import_Submitted_Case_Data_to_ElasticDB(submitted_cases, securityTicket.TenantID.ToString());

            return(returnValue);

            #endregion UserCode
        }
Ejemplo n.º 7
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
        }