protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_WOctoSE_0938 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            var should_send_email = false;

            var treatment_year_start_date = cls_Get_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GTY_1125()
            {
                Date             = Parameter.treatment_date,
                LocalizationCode = Parameter.localization,
                PatientID        = Parameter.patient_id,
            }, securityTicket).Result;

            var treatment_year_length = cls_Get_TreatmentYearLength.Invoke(Connection, Transaction, new P_CAS_GTYL_1317()
            {
                Date      = Parameter.treatment_date,
                PatientID = Parameter.patient_id
            }, securityTicket).Result;

            var ops_in_treatment_year = cls_Get_OpDates_for_PatientID_and_LocalizationCode_in_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GOpDfPIDaLCiTY_1110()
            {
                LocalizationCode       = Parameter.localization,
                PatientID              = Parameter.patient_id,
                TreatmentYearStartDate = treatment_year_start_date,
                TreatmentYearEndDate   = treatment_year_start_date.AddDays(treatment_year_length - 1)
            }, securityTicket).Result;

            var existingBillPosition = cls_Get_Existing_OCT_BillPosition_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GEBPfPIDaLC_1803()
            {
                LocalizationCode = Parameter.localization,
                PatientID        = Parameter.patient_id
            }, securityTicket).Result;

            if (existingBillPosition != null && existingBillPosition.CaseID == Parameter.case_id)
            {
                var op_to_reassign_oct_to = ops_in_treatment_year.FirstOrDefault(t => t.CaseID != Parameter.case_id && ((!t.IsPerformed && !t.IsDeleted) || (t.IsPerformed && t.FsStatus != 8 && t.FsStatus != 11 && t.FsStatus != 17)));
                if (op_to_reassign_oct_to != null)
                {
                    var caseBillCode = new ORM_HEC_CAS_Case_BillCode();
                    caseBillCode.Load(Connection, Transaction, existingBillPosition.CaseBillCodeID);

                    caseBillCode.HEC_CAS_Case_RefID = op_to_reassign_oct_to.CaseID;
                    caseBillCode.Save(Connection, Transaction);
                }
                else
                {
                    var oct = Retrieve_Octs.GetOctsWhereFieldsHaveValues(new List <FieldValueParameter>()
                    {
                        new FieldValueParameter()
                        {
                            FieldName = "case_id", FieldValue = Parameter.case_id.ToString()
                        }
                    }, null, securityTicket.TenantID.ToString()).SingleOrDefault();

                    if (oct != null)
                    {
                        var oct_id             = Guid.Parse(oct.id);
                        var oct_planned_action = new ORM_HEC_ACT_PlannedAction();
                        oct_planned_action.Load(Connection, Transaction, oct_id);
                        oct_planned_action.IsCancelled = true;

                        oct_planned_action.Save(Connection, Transaction);
                    }
                }

                should_send_email = cls_Get_Active_NonError_OctBillPositionID_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GANEOctBPIDfCID_0925()
                {
                    CaseID = Parameter.case_id
                }, securityTicket).Result.Any();
            }

            if (should_send_email)
            {
                var performedOcts = cls_Get_PerformedOctDoctorData_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GPOctDDfCID_0935()
                {
                    CaseID = Parameter.case_id
                }, securityTicket).Result;

                if (performedOcts.Any())
                {
                    var mailToL = new List <String>();

                    var accountMails = cls_Get_All_Account_LoginEmails_Who_Receive_Notifications.Invoke(Connection, Transaction, securityTicket).Result.ToList();
                    foreach (var mail in accountMails)
                    {
                        mailToL.Add(mail.LoginEmail);
                    }

                    var mailToFromCompanySettings = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                    mailToL.Add(mailToFromCompanySettings);

                    var patient_details = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                    {
                        PatientID = Parameter.patient_id
                    }, securityTicket).Result;
                    var treatment_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                    {
                        DoctorID = Parameter.op_doctor_id
                    }, securityTicket).Result.First();
                    var appName        = WebConfigurationManager.AppSettings["mmAppUrl"];
                    var prefix         = HttpContext.Current.Request.Url.AbsoluteUri.Contains("https") ? "https://" : "http://";
                    var imageUrl       = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("api")) + "Content/images/logo.png";
                    var email_template = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/TreatmentCancelledFromSettlementPageOctSubmittedEmailTemplate .html"));

                    var     subjectsJson = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailSubjects.json"));
                    dynamic subjects     = JsonConvert.DeserializeObject(subjectsJson);
                    var     subjectMail  = subjects["TreatmentCancelledFromSettlementPageSubject"].ToString();

                    email_template = EmailTemplater.SetTemplateData(email_template, new
                    {
                        patient_first_name          = patient_details.patient_first_name,
                        patient_last_name           = patient_details.patient_last_name,
                        treatment_date              = Parameter.treatment_date.ToString("dd.MM.yyyy"),
                        treatment_doctor_title      = treatment_doctor_details.title,
                        treatment_doctor_first_name = treatment_doctor_details.first_name,
                        treatment_doctor_last_name  = treatment_doctor_details.last_name,
                        octs = performedOcts,
                        mmapp_treatment_page_url = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName + "/#/treatment",
                        medios_connect_logo_url  = imageUrl
                    }, "{{", "}}");

                    try
                    {
                        string mailFrom = WebConfigurationManager.AppSettings["mailFrom"];

                        var mailsDistinct = mailToL.Distinct().ToList();
                        foreach (var mailTo in mailsDistinct)
                        {
                            EmailNotificationSenderUtil.SendEmail(mailFrom, mailTo, subjectMail, email_template);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtils.Logger.LogDocAppInfo(new LogUtils.LogEntry(System.Reflection.MethodInfo.GetCurrentMethod(), ex, null, "Cancel case from settlement: Email sending failed."), "EmailExceptions");
                    }
                }
            }

            return(returnValue);

            #endregion UserCode
        }
Beispiel #2
0
        public static IEnumerable <IEnumerable <IElasticMapper> > GetUpdatedData(string index_name, string id, string type, string[] values)
        {
            var planning_cases  = new List <Case_Model>();
            var open_aftercares = new List <Aftercare_Model>();
            var error_correction_settlements = new List <Settlement_Model>();
            var error_correction_treatments  = new List <Submitted_Case_Model>();
            var patients        = new List <Patient_Model>();
            var patient_details = new List <PatientDetailViewModel>();
            var orders          = new List <Order_Model>();
            var octs            = new List <Oct_Model>();

            switch (type)
            {
            case "doctor":

                #region UPDATE PLANNING CASES
                var cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "treatment_doctor_id", index_name, "case");
                if (cases_from_elastic.Any())
                {
                    planning_cases = cases_from_elastic.Select(cas =>
                    {
                        cas.treatment_doctor_name = values[0];
                        cas.treatment_doctor_lanr = values[1];

                        return(cas);
                    }).ToList();
                }

                cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "aftercare_doctor_practice_id", index_name, "case");
                if (cases_from_elastic.Any())
                {
                    planning_cases.AddRange(cases_from_elastic.Select(cas =>
                    {
                        planning_cases.RemoveAll(pc => pc.id == cas.id);

                        cas.treatment_doctor_name = values[0];
                        cas.treatment_doctor_lanr = values[1];


                        cas.aftercare_name        = values[0];
                        cas.aftercare_doctor_lanr = values[1];

                        return(cas);
                    }).ToList());
                }
                #endregion

                #region UPDATE AFTERCARES
                var aftercares_from_elastic = Get_Cases.GetCasesWhereIDPresent <Aftercare_Model>(id, "treatment_doctor_id", index_name, "aftercare");
                if (aftercares_from_elastic.Any())
                {
                    open_aftercares = aftercares_from_elastic.Select(ac =>
                    {
                        ac.treatment_doctor_name = values[0];
                        ac.op_lanr = values[1];

                        return(ac);
                    }).ToList();
                }

                aftercares_from_elastic = Get_Cases.GetCasesWhereIDPresent <Aftercare_Model>(id, "aftercare_doctor_practice_id", index_name, "aftercare");
                if (aftercares_from_elastic.Any())
                {
                    open_aftercares.AddRange(aftercares_from_elastic.Select(ac =>
                    {
                        open_aftercares.RemoveAll(oac => oac.id == ac.id);

                        ac.treatment_doctor_name = values[0];
                        ac.ac_lanr = values[1];


                        ac.aftercare_doctor_name = values[0];

                        return(ac);
                    }).ToList());
                }
                #endregion

                #region UPDATE SETTLEMENTS IN ERROR CORRECTION
                var settlements_from_elastic = Get_Settlement.GetCasesWhereIDPresent(id, "treatment_doctor_id", index_name, "op");
                if (settlements_from_elastic.Any())
                {
                    error_correction_settlements = settlements_from_elastic.Select(cas =>
                    {
                        cas.doctor = values[0];
                        cas.lanr   = values[1];

                        return(cas);
                    }).ToList();
                }

                settlements_from_elastic = Get_Settlement.GetCasesWhereIDPresent(id, "aftercare_doctor_practice_id", index_name, "ac");
                if (settlements_from_elastic.Any())
                {
                    error_correction_settlements.AddRange(settlements_from_elastic.Select(cas =>
                    {
                        error_correction_settlements.RemoveAll(ecs => ecs.id == cas.id);

                        cas.doctor = values[0];
                        cas.lanr   = values[1];


                        cas.doctor = values[0];
                        cas.lanr   = values[1];

                        return(cas);
                    }).ToList());
                }
                #endregion

                #region UPDATE MM TREATMENTS IN ERROR CORRECTION
                var treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "doctor_id", index_name, "op");
                if (treatments_from_elastic.Any())
                {
                    error_correction_treatments = treatments_from_elastic.Select(cas =>
                    {
                        cas.doctor_name = values[0];
                        cas.doctor_lanr = values[1];

                        return(cas);
                    }).ToList();
                }

                treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "doctor_id", index_name, "ac");
                if (treatments_from_elastic.Any())
                {
                    error_correction_treatments.AddRange(treatments_from_elastic.Select(cas =>
                    {
                        error_correction_treatments.RemoveAll(ect => ect.id == cas.id);

                        cas.doctor_name = values[0];
                        cas.doctor_lanr = values[1];


                        cas.doctor_name = values[0];
                        cas.doctor_lanr = values[1];

                        return(cas);
                    }).ToList());
                }
                #endregion

                #region UPDATE ORDERS
                var orders_from_elastic = Get_Orders.GetOrdersWhereForIdAndOrdinal(id, "doctor_id", index_name);
                if (orders_from_elastic.Any())
                {
                    orders = orders_from_elastic.Select(ord =>
                    {
                        ord.treatment_doctor_name = values[0];
                        ord.lanr = values[1];

                        return(ord);
                    }).ToList();
                }
                #endregion

                #region UPDATE PATIENTS
                var patients_from_elastic = Retrieve_Patients.GetPatientsWhereIDPresent(id, "op_doctor_id", index_name);
                if (patients_from_elastic.Any())
                {
                    patients = patients_from_elastic.Select(patient =>
                    {
                        patient.last_first_op_doctor_name = values[0];
                        patient.op_doctor_lanr            = values[1];

                        return(patient);
                    }).ToList();
                }

                patients_from_elastic = Retrieve_Patients.GetPatientsWhereIDPresent(id, "ac_doctor_id", index_name);
                if (patients_from_elastic.Any())
                {
                    patients.AddRange(patients_from_elastic.Select(patient =>
                    {
                        patients.RemoveAll(pat => pat.id == patient.id);

                        patient.last_first_op_doctor_name = values[0];
                        patient.op_doctor_lanr            = values[1];
                        patient.last_first_ac_doctor_name = values[0];
                        patient.ac_doctor_lanr            = values[1];

                        return(patient);
                    }).ToList());
                }
                #endregion

                #region UPDATE PATIENT DETAILS
                var patients_details_from_elastic = Retrieve_Patients.GetPatientDetailsForIdAndOrdinal(id, "treatment_doctor_id", index_name);
                if (patients_details_from_elastic.Any())
                {
                    patient_details = patients_details_from_elastic.Select(patient =>
                    {
                        patient.doctor = values[0];

                        return(patient);
                    }).ToList();
                }

                patients_details_from_elastic = Retrieve_Patients.GetPatientDetailsForIdAndOrdinal(id, "aftercare_doctor_practice_id", index_name);
                if (patients_details_from_elastic.Any())
                {
                    patient_details.AddRange(patients_details_from_elastic.Select(patient =>
                    {
                        patient.doctor = values[0];

                        return(patient);
                    }).ToList());
                }
                #endregion

                #region UPDATE OCT

                octs.AddRange(Retrieve_Octs.GetOctsWhereFieldsHaveValues(new List <FieldValueParameter>()
                {
                    new FieldValueParameter()
                    {
                        FieldName = "oct_doctor_id", FieldValue = id
                    },
                    new FieldValueParameter()
                    {
                        FieldName = "treatment_doctor_id", FieldValue = id, Negation = true
                    }
                }, null, index_name)
                              .Select(t =>
                {
                    t.oct_doctor_name = values[0];

                    return(t);
                }).ToList());

                octs.AddRange(Retrieve_Octs.GetOctsWhereFieldsHaveValues(new List <FieldValueParameter>()
                {
                    new FieldValueParameter()
                    {
                        FieldName = "treatment_doctor_id", FieldValue = id
                    },
                    new FieldValueParameter()
                    {
                        FieldName = "oct_doctor_id", FieldValue = id, Negation = true
                    }
                }, null, index_name)
                              .Select(t =>
                {
                    t.treatment_doctor_name = values[0];

                    return(t);
                }).ToList());

                octs.AddRange(Retrieve_Octs.GetOctsWhereFieldsHaveValues(new List <FieldValueParameter>()
                {
                    new FieldValueParameter()
                    {
                        FieldName = "treatment_doctor_id", FieldValue = id
                    },
                    new FieldValueParameter()
                    {
                        FieldName = "oct_doctor_id", FieldValue = id
                    }
                }, null, index_name)
                              .Select(t =>
                {
                    t.oct_doctor_name       = values[0];
                    t.treatment_doctor_name = values[0];

                    return(t);
                }).ToList());

                #endregion

                #region UPDATE AC DOCTORS
                var types = Elastic_Utils.GetAllTypes(index_name);

                HashSet <string> last_used_types = new HashSet <string>();

                var     newTypes     = types.Replace(index_name, "allData");
                dynamic data         = JObject.Parse(newTypes);
                var     mappings     = data.allData.mappings;
                var     neededLength = Guid.Empty.ToString().Length + 5;
                var     elasticType  = "user_";

                foreach (var acType in mappings)
                {
                    if (acType.Name.Contains(elasticType) && acType.Name.Length == neededLength)
                    {
                        var dataForType = Get_Practices_and_Doctors.GetACDoctorsWhereIDPresent(id, "id", index_name, acType.Name);

                        foreach (var acDoc in dataForType)
                        {
                            acDoc.display_name = String.Format("{0} ({1})", values[0], values[1]);
                        }

                        var accountID = acType.Name.Split(new string[] { elasticType }, StringSplitOptions.None)[1];
                        UpdateAftercareDoctor(dataForType, index_name, accountID, elasticType);
                    }
                }
                ;
                #endregion

                break;

            case "practice":

                #region UPDATE PLANNING CASES
                var practice_cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "aftercare_doctors_practice_id", index_name, "case");
                if (practice_cases_from_elastic.Any())
                {
                    planning_cases = practice_cases_from_elastic.Select(cas =>
                    {
                        cas.aftercare_doctors_practice_name = values[0];
                        cas.aftercare_practice_bsnr         = values[1];

                        return(cas);
                    }).ToList();
                }

                practice_cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "aftercare_doctor_practice_id", index_name, "case");
                if (practice_cases_from_elastic.Any())
                {
                    planning_cases.AddRange(practice_cases_from_elastic.Select(cas =>
                    {
                        planning_cases.RemoveAll(pc => pc.id == cas.id);

                        cas.aftercare_doctors_practice_name = values[0];
                        cas.aftercare_practice_bsnr         = values[1];


                        cas.aftercare_name          = values[0];
                        cas.aftercare_practice_bsnr = values[1];

                        return(cas);
                    }).ToList());
                }
                #endregion

                #region UPDATE AFTERCARES
                var practice_aftercares_from_elastic = Get_Cases.GetCasesWhereIDPresent <Aftercare_Model>(id, "treatment_doctors_practice_id", index_name, "aftercare");
                if (practice_aftercares_from_elastic.Any())
                {
                    open_aftercares = practice_aftercares_from_elastic.Select(ac =>
                    {
                        ac.treatment_doctor_practice_name = values[0];
                        ac.bsnr = values[1];

                        return(ac);
                    }).ToList();
                }
                #endregion

                #region UPDATE MM TREATMENTS IN ERROR CORRECTION
                var practice_treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "practice_id", index_name);
                if (practice_treatments_from_elastic.Any())
                {
                    error_correction_treatments = practice_treatments_from_elastic.Select(cas =>
                    {
                        cas.practice_name = values[0];
                        cas.practice_bsnr = values[1];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE ORDERS
                var practice_orders_from_elastic = Get_Orders.GetOrdersWhereIDPresent(id, "practice_id", index_name);
                if (practice_orders_from_elastic.Any())
                {
                    orders = practice_orders_from_elastic.Select(ord =>
                    {
                        ord.treatment_doctor_practice_name = values[0];
                        ord.bsnr = values[1];

                        return(ord);
                    }).ToList();
                }
                #endregion

                #region UPDATE PATIENTS
                var pratice_patients_from_elastic = Retrieve_Patients.GetPatientsWhereIDPresent(id, "practice_id", index_name);
                if (pratice_patients_from_elastic.Any())
                {
                    patients = pratice_patients_from_elastic.Select(patient =>
                    {
                        patient.practice      = values[0];
                        patient.practice_bsnr = values[1];

                        return(patient);
                    }).ToList();
                }

                pratice_patients_from_elastic = Retrieve_Patients.GetPatientsWhereIDPresent(id, "ac_practice_id", index_name);
                if (pratice_patients_from_elastic.Any())
                {
                    patients.AddRange(pratice_patients_from_elastic.Select(patient =>
                    {
                        patients.RemoveAll(pat => pat.id == patient.id);

                        patient.practice      = values[0];
                        patient.practice_bsnr = values[1];


                        patient.ac_practice      = values[0];
                        patient.ac_practice_bsnr = values[1];

                        return(patient);
                    }).ToList());
                }
                #endregion

                break;

            case "patient":
                IFormatProvider culture = new System.Globalization.CultureInfo("de", true);

                #region UPDATE PLANNING CASES
                var patient_cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "patient_id", index_name, "case");
                if (patient_cases_from_elastic.Any())
                {
                    planning_cases = patient_cases_from_elastic.Select(cas =>
                    {
                        cas.patient_name             = values[0];
                        cas.patient_insurance_number = values[1];
                        cas.patient_birthdate        = DateTime.Parse(values[2], culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        cas.patient_birthdate_string = values[2];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE AFTERCARES
                var patient_aftercares_from_elastic = Get_Cases.GetCasesWhereIDPresent <Aftercare_Model>(id, "patient_id", index_name, "aftercare");
                if (patient_aftercares_from_elastic.Any())
                {
                    open_aftercares = patient_aftercares_from_elastic.Select(ac =>
                    {
                        ac.patient_name             = values[0];
                        ac.patient_insurance_number = values[1];
                        ac.patient_birthdate        = DateTime.Parse(values[2], culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        ac.patient_birthdate_string = values[2];

                        return(ac);
                    }).ToList();
                }
                #endregion

                #region UPDATE SETTLEMENTS IN ERROR CORRECTION
                var patient_settlements_from_elastic = Get_Settlement.GetCasesWhereIDPresent(id, "patient_id", index_name);
                if (patient_settlements_from_elastic.Any())
                {
                    error_correction_settlements = patient_settlements_from_elastic.Select(cas =>
                    {
                        cas.patient_full_name        = values[0];
                        cas.patient_insurance_number = values[1];
                        cas.birthday = values[2];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE MM TREATMENTS IN ERROR CORRECTION
                var patient_treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "patient_id", index_name);
                if (patient_treatments_from_elastic.Any())
                {
                    error_correction_treatments = patient_treatments_from_elastic.Select(cas =>
                    {
                        cas.patient_name             = values[0];
                        cas.patient_insurance_number = values[1];
                        cas.patient_birthdate        = DateTime.Parse(values[2], culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        cas.patient_birthdate_string = values[2];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE ORDERS
                var patient_orders_from_elastic = Get_Orders.GetOrdersWhereIDPresent(id, "patient_id", index_name);
                if (patient_orders_from_elastic.Any())
                {
                    orders = patient_orders_from_elastic.Select(ord =>
                    {
                        ord.patient_name             = values[0];
                        ord.patient_insurance_number = values[1];
                        ord.patient_birthdate        = DateTime.Parse(values[2], culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        ord.patient_birthdate_string = values[2];

                        return(ord);
                    }).ToList();
                }
                #endregion

                #region UPDATE OCT
                octs = Retrieve_Octs.GetOctsWhereFieldsHaveValues(new List <FieldValueParameter>()
                {
                    new FieldValueParameter()
                    {
                        FieldName = "patient_id", FieldValue = id
                    },
                    new FieldValueParameter()
                    {
                        FieldName = "status.lower_case_sort", FieldValue = "oct1"
                    },
                }, null, index_name)
                       .Select(t =>
                {
                    t.patient_name             = values[0];
                    t.patient_insurance_number = values[1];
                    t.patient_birthdate        = DateTime.Parse(values[2], culture, System.Globalization.DateTimeStyles.AssumeLocal);

                    return(t);
                }).ToList();
                #endregion

                break;

            case "drug":

                #region UPDATE PLANNING CASES
                var drug_cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "drug_id", index_name, "case");
                if (drug_cases_from_elastic.Any())
                {
                    planning_cases = drug_cases_from_elastic.Select(cas =>
                    {
                        cas.drug = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE SETTLEMENTS IN ERROR CORRECTION
                var drug_settlements_from_elastic = Get_Settlement.GetCasesWhereIDPresent(id, "drug_id", index_name);
                if (drug_settlements_from_elastic.Any())
                {
                    error_correction_settlements = drug_settlements_from_elastic.Select(cas =>
                    {
                        cas.drug = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE MM TREATMENTS IN ERROR CORRECTION
                var drug_treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "drug_id", index_name);
                if (drug_treatments_from_elastic.Any())
                {
                    error_correction_treatments = drug_treatments_from_elastic.Select(cas =>
                    {
                        cas.drug = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE ORDERS
                var drug_orders_from_elastic = Get_Orders.GetOrdersWhereIDPresent(id, "drug_id", index_name);
                if (drug_orders_from_elastic.Any())
                {
                    orders = drug_orders_from_elastic.Select(ord =>
                    {
                        ord.drug = values[0];

                        return(ord);
                    }).ToList();
                }
                #endregion

                #region UPDATE PATIENT DETAILS
                var drug_patients_details_from_elastic = Retrieve_Patients.GetPatientDetailsWhereIDPresent(id, "drug_id", index_name);
                if (drug_patients_details_from_elastic.Any())
                {
                    patient_details = drug_patients_details_from_elastic.Select(patient =>
                    {
                        patient.drug = values[0];
                        if (patient.detail_type == "order")
                        {
                            patient.diagnose_or_medication = values[0];
                        }

                        return(patient);
                    }).ToList();
                }
                #endregion

                break;

            case "diagnose":

                #region UPDATE PLANNING CASES
                var diagnose_cases_from_elastic = Get_Cases.GetCasesWhereIDPresent <Case_Model>(id, "diagnose_id", index_name, "case");
                if (diagnose_cases_from_elastic.Any())
                {
                    planning_cases = diagnose_cases_from_elastic.Select(cas =>
                    {
                        cas.diagnose = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE SETTLEMENTS IN ERROR CORRECTION
                var diagnose_settlements_from_elastic = Get_Settlement.GetCasesWhereIDPresent(id, "diagnose_id", index_name);
                if (diagnose_settlements_from_elastic.Any())
                {
                    error_correction_settlements = diagnose_settlements_from_elastic.Select(cas =>
                    {
                        cas.diagnose = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE MM TREATMENTS IN ERROR CORRECTION
                var diagnose_treatments_from_elastic = Get_Cases.GetSubmittedCasesInErrorCorrectionAndWhereIDPresent(id, "diagnose_id", index_name);
                if (diagnose_treatments_from_elastic.Any())
                {
                    error_correction_treatments = diagnose_treatments_from_elastic.Select(cas =>
                    {
                        cas.diagnose = values[0];

                        return(cas);
                    }).ToList();
                }
                #endregion

                #region UPDATE ORDERS
                var diagnose_orders_from_elastic = Get_Orders.GetOrdersWhereIDPresent(id, "diagnose_id", index_name);
                if (diagnose_orders_from_elastic.Any())
                {
                    orders = diagnose_orders_from_elastic.Select(ord =>
                    {
                        ord.diagnose = values[0];

                        return(ord);
                    }).ToList();
                }
                #endregion

                #region UPDATE PATIENT DETAILS
                var diagnose_patients_details_from_elastic = Retrieve_Patients.GetPatientDetailsWhereIDPresent(id, "diagnose_id", index_name);
                if (diagnose_patients_details_from_elastic.Any())
                {
                    patient_details = diagnose_patients_details_from_elastic.Select(patient =>
                    {
                        if (patient.detail_type == "op" || patient.detail_type == "ac")
                        {
                            patient.diagnose_or_medication = values[0];
                        }

                        return(patient);
                    }).ToList();
                }
                #endregion

                break;

            default:
                break;
            }

            return(new List <IEnumerable <IElasticMapper> >()
            {
                planning_cases,
                open_aftercares,
                error_correction_settlements,
                error_correction_treatments,
                orders,
                patients,
                patient_details,
                octs
            });
        }
Beispiel #3
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_HOCT_1013 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            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 elastic_index = securityTicket.TenantID.ToString();

            var oct_performed_action_type_id = cls_Get_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GATID_1514()
            {
                action_type_gpmid = EActionType.PerformedOct.Value()
            }, securityTicket).Result;

            var oct_doctor = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                HEC_DoctorID = Parameter.oct_doctor_id, Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).SingleOrDefault();
            var patient_practice_name = cls_Get_Patient_PracticeName_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPPNfPID_1131()
            {
                PatientID = Parameter.patient_id
            }, securityTicket).Result;

            var current_treatment_year_start_date = DateTime.MaxValue;

            if (oct_doctor != null)
            {
                current_treatment_year_start_date = cls_Get_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GTY_1125()
                {
                    Date             = Parameter.treatment_date,
                    LocalizationCode = Parameter.localization,
                    PatientID        = Parameter.patient_id,
                }, securityTicket).Result;
            }
            else
            {
                current_treatment_year_start_date = cls_Get_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GTY_1125()
                {
                    Date             = Parameter.treatment_date,
                    LocalizationCode = Parameter.localization,
                    PatientID        = Parameter.patient_id
                }, securityTicket).Result;
            }
            var treatment_year_length = cls_Get_TreatmentYearLength.Invoke(Connection, Transaction, new P_CAS_GTYL_1317()
            {
                Date      = Parameter.treatment_date,
                PatientID = Parameter.patient_id
            }, securityTicket).Result;

            var current_treatment_year_end_date = current_treatment_year_start_date.AddDays(treatment_year_length - 1);

            var oct_gpos_ids = cls_Get_GposIDs_for_GposType.Invoke(Connection, Transaction, new P_MD_GGpoIDsfGposT_1145()
            {
                GposType = EGposType.Oct.Value()
            }, securityTicket).Result;
            if (!oct_gpos_ids.Any())
            {
                return(returnValue);
            }

            var last_potential_consent = cls_Get_Patient_Consents_before_Date_and_GposIDs.Invoke(Connection, Transaction, new P_PA_GPCbDaGposIDs_1154()
            {
                Date      = Parameter.treatment_date.Date,
                GposIDs   = oct_gpos_ids.Select(t => t.GposID).ToArray(),
                PatientID = Parameter.patient_id
            }, securityTicket).Result.FirstOrDefault(t => t.consent_valid_from.Date <= Parameter.treatment_date.Date);

            var latest_oct_planned_actions = cls_Get_Latest_PlannedActionID_for_PatientID_ActionTypeID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GLPAIDfPIDATIDaLC_1545()
            {
                ActionTypeID     = oct_planned_action_type_id,
                LocalizationCode = Parameter.localization,
                PatientID        = Parameter.patient_id
            }, securityTicket).Result;

            if (last_potential_consent == null && Parameter.oct_doctor_id != Guid.Empty && latest_oct_planned_actions.Any(t => t.OpDate >= current_treatment_year_start_date.Date && t.OpDate < current_treatment_year_start_date.AddDays(treatment_year_length).Date))
            {
                var latest_oct_planned_action_id = latest_oct_planned_actions.FirstOrDefault(t => t.CaseID != Parameter.case_id && t.OpDate >= current_treatment_year_start_date.Date && t.OpDate < current_treatment_year_start_date.AddDays(treatment_year_length).Date);
                if (latest_oct_planned_action_id == null)
                {
                    latest_oct_planned_action_id = latest_oct_planned_actions.FirstOrDefault(t => t.CaseID == Parameter.case_id && t.OpDate >= current_treatment_year_start_date.Date && t.OpDate < current_treatment_year_start_date.AddDays(treatment_year_length).Date);
                }
                var latest_oct_planned_action = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                {
                    HEC_ACT_PlannedActionID = latest_oct_planned_action_id.PlannedActionID
                }).Single();
            }
            else
            {
                var case_properties = cls_Get_Case_Properties_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCPfCID_1204()
                {
                    CaseID = Parameter.case_id
                }, securityTicket).Result;

                var oct_planned_action_id = cls_Get_Latest_PlannedActionID_for_CaseID_and_ActionTypeID.Invoke(Connection, Transaction, new P_CAS_GLPAIDfCIDaATID_1635()
                {
                    ActionTypeID = oct_planned_action_type_id,
                    CaseID       = Parameter.case_id
                }, securityTicket).Result;

                #region Case creation
                if (!Parameter.is_submit)
                {
                    var case_fs_statuses = cls_Get_Case_TransmitionCode_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCTCfCID_1427()
                    {
                        CaseID = Parameter.case_id
                    }, securityTicket).Result;
                    var op_submitted = case_fs_statuses.Any(t => t.gpos_type == EGposType.Operation.Value());

                    var latest_oct_planned_action_id = cls_Get_Latest_PlannedActionID_for_PatientID_ActionTypeID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GLPAIDfPIDATIDaLC_1545()
                    {
                        ActionTypeID     = oct_planned_action_type_id,
                        LocalizationCode = Parameter.localization,
                        PatientID        = Parameter.patient_id
                    }, securityTicket).Result.FirstOrDefault(t => t.CaseID != Parameter.case_id && t.OpDate >= current_treatment_year_start_date.Date && t.OpDate < current_treatment_year_start_date.AddDays(treatment_year_length).Date);

                    var properties_to_delete = case_properties.Where(t => t.property_gpmid == ECaseProperty.WithdrawOct.Value() || t.property_gpmid == ECaseProperty.SubmitOctUntilDate.Value());
                    if (Parameter.withdraw_oct && latest_oct_planned_action_id != null)
                    {
                        var latest_oct_planned_action = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                        {
                            HEC_ACT_PlannedActionID = latest_oct_planned_action_id.PlannedActionID
                        }).Single();

                        if (Parameter.submit_oct_until_date != DateTime.MinValue)
                        {
                            cls_Save_Case_Property.Invoke(Connection, Transaction, new P_CAS_SCP_1308()
                            {
                                case_id               = Parameter.case_id,
                                property_gpm_id       = ECaseProperty.SubmitOctUntilDate.Value(),
                                property_name         = "Submit OCT until date",
                                property_string_value = String.Format("{0};{1};{2};{3}", Parameter.submit_oct_until_date.ToString("yyyy-MM-ddTHH:mm:ss"), latest_oct_planned_action.ToBePerformedBy_BusinessParticipant_RefID, Parameter.localization, latest_oct_planned_action.HEC_ACT_PlannedActionID)
                            }, securityTicket);

                            properties_to_delete = properties_to_delete.Where(t => t.property_gpmid == ECaseProperty.WithdrawOct.Value()).ToList();
                        }
                        else if (Parameter.withdraw_oct)
                        {
                            cls_Save_Case_Property.Invoke(Connection, Transaction, new P_CAS_SCP_1308()
                            {
                                case_id               = Parameter.case_id,
                                property_name         = "Withdraw OCT",
                                property_gpm_id       = ECaseProperty.WithdrawOct.Value(),
                                property_string_value = String.Format("{0}", latest_oct_planned_action.ToBePerformedBy_BusinessParticipant_RefID.ToString())
                            }, securityTicket);

                            properties_to_delete = properties_to_delete.Where(t => t.property_gpmid == ECaseProperty.SubmitOctUntilDate.Value()).ToList();
                        }
                    }

                    foreach (var prop in properties_to_delete)
                    {
                        ORM_HEC_CAS_Case_UniversalPropertyValue.Query.SoftDelete(Connection, Transaction, new ORM_HEC_CAS_Case_UniversalPropertyValue.Query()
                        {
                            HEC_CAS_Case_UniversalPropertyValueID = prop.id
                        });
                    }

                    if (!op_submitted || Parameter.is_documentation)
                    {
                        if (oct_planned_action_id != null)
                        {
                            var latest_oct_planned_action = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                            {
                                HEC_ACT_PlannedActionID = oct_planned_action_id.PlannedActionID
                            }).Single();

                            if (Parameter.oct_doctor_id == Guid.Empty)
                            {
                                latest_oct_planned_action.IsDeleted = true;
                            }
                            else
                            {
                                latest_oct_planned_action.ToBePerformedBy_BusinessParticipant_RefID = oct_doctor.BusinessParticipant_RefID;
                            }

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

                            returnValue.Result = latest_oct_planned_action.HEC_ACT_PlannedActionID;

                            #region localization changed
                            if (Parameter.localization_changed)
                            {
                                var old_localization = Parameter.localization == "L" ? "R" : "L";

                                var latest_new_localization_oct_bill_position = cls_Get_Existing_OCT_BillPosition_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GEBPfPIDaLC_1803()
                                {
                                    LocalizationCode = Parameter.localization,
                                    PatientID        = Parameter.patient_id
                                }, securityTicket).Result;

                                var latest_old_localization_op = cls_Get_OpDates_for_PatientID_and_LocalizationCode_in_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GOpDfPIDaLCiTY_1110()
                                {
                                    LocalizationCode     = old_localization,
                                    PatientID            = Parameter.patient_id,
                                    TreatmentYearEndDate = DateTime.Now
                                }, securityTicket).Result.FirstOrDefault();

                                if (latest_new_localization_oct_bill_position != null && latest_new_localization_oct_bill_position.CaseID == Parameter.case_id)
                                {
                                    if (latest_old_localization_op == null)
                                    {
                                        // check if case has pending oct
                                        var case_has_pending_oct = cls_Get_CaseIDs_with_Pending_Octs_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GCIDswPOctsfPIDaLC_1103()
                                        {
                                            LocalizationCode = Parameter.localization,
                                            PatientID        = Parameter.patient_id
                                        }, securityTicket).Result.Any(t => t.case_id == Parameter.case_id);

                                        if (case_has_pending_oct)
                                        {
                                            throw new Exception(String.Format("Case has a pending OCT attached and there isn't another IVOM to transfer OCT to. Localization cannot be changed. Case id: {0}", Parameter.case_id));
                                        }
                                    }
                                    else
                                    {
                                        var case_details = cls_Get_Case_Details_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCDfCID_1435()
                                        {
                                            CaseID = latest_old_localization_op.CaseID
                                        }, securityTicket).Result;

                                        cls_Calculate_Case_GPOS.Invoke(Connection, Transaction, new P_CAS_CCGPOS_1000()
                                        {
                                            case_id        = latest_old_localization_op.CaseID,
                                            diagnose_id    = case_details.diagnose_id,
                                            drug_id        = case_details.drug_id,
                                            patient_id     = case_details.patient_id,
                                            localization   = case_details.localization,
                                            treatment_date = case_details.treatment_date,
                                            oct_doctor_id  = Parameter.oct_doctor_id
                                        }, securityTicket);
                                    }
                                }

                                var new_localization_oct_bill_position = cls_Get_Existing_OCT_BillPosition_for_PatientID_and_LocalizationCode_where_not_CaseID.Invoke(Connection, Transaction, new P_CAS_GEBPfPIDaLCwnCID_1438()
                                {
                                    CaseID           = Parameter.case_id,
                                    PatientID        = Parameter.patient_id,
                                    LocalizationCode = Parameter.localization
                                }, securityTicket).Result;

                                if (new_localization_oct_bill_position != null)
                                {
                                    cls_Delete_BillingData_for_BillPositionID.Invoke(Connection, Transaction, new P_CAS_DBDfHBPID_1549()
                                    {
                                        bill_position_id = new_localization_oct_bill_position.BillPositionID
                                    }, securityTicket);
                                }
                            }
                            #endregion
                        }
                        else if (Parameter.oct_doctor_id != Guid.Empty)
                        {
                            var existing_rejection_properties = cls_Get_Localizations_where_Oct_Rejected.Invoke(Connection, Transaction, new P_CAS_GLwOctR_1026()
                            {
                                PatientID             = Parameter.patient_id,
                                RejectedOctPropertyID = ECaseProperty.HasRejectedOct.Value()
                            }, securityTicket).Result;

                            foreach (var existing_rejection_property in existing_rejection_properties.Where(t => t.localization == Parameter.localization))
                            {
                                ORM_HEC_CAS_Case_UniversalPropertyValue.Query.SoftDelete(Connection, Transaction, new ORM_HEC_CAS_Case_UniversalPropertyValue.Query()
                                {
                                    HEC_CAS_Case_UniversalPropertyValueID = existing_rejection_property.property_id,
                                    Tenant_RefID = securityTicket.TenantID,
                                    IsDeleted    = false
                                });
                            }

                            returnValue = cls_Create_OCT.Invoke(Connection, Transaction, new P_CAS_COCT_1703()
                            {
                                case_id            = Parameter.case_id,
                                oct_action_type_id = oct_planned_action_type_id,
                                oct_bpt_id         = oct_doctor.BusinessParticipant_RefID,
                                patient_id         = Parameter.patient_id,
                                treatment_date     = Parameter.treatment_date,
                                practice_id        = Parameter.oct_doctor_practice_id
                            }, securityTicket);

                            var existingBillPosition = cls_Get_Existing_OCT_BillPosition_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GEBPfPIDaLC_1803()
                            {
                                LocalizationCode = Parameter.localization,
                                PatientID        = Parameter.patient_id
                            }, securityTicket).Result;

                            if (existingBillPosition == null)
                            {
                                cls_Calculate_Case_GPOS.Invoke(Connection, Transaction, new P_CAS_CCGPOS_1000()
                                {
                                    case_id        = Parameter.case_id,
                                    diagnose_id    = Parameter.diagnose_id,
                                    drug_id        = Parameter.drug_id,
                                    patient_id     = Parameter.patient_id,
                                    localization   = Parameter.localization,
                                    treatment_date = Parameter.treatment_date,
                                    oct_doctor_id  = Parameter.oct_doctor_id
                                }, securityTicket);
                            }
                            else
                            {
                                cls_Delete_BillingData_for_BillPositionID.Invoke(Connection, Transaction, new P_CAS_DBDfHBPID_1549()
                                {
                                    bill_position_id = existingBillPosition.BillPositionID
                                }, securityTicket);

                                var isAutoGenerated = cls_Get_CasePropertyValue_for_CaseIDs_and_CasePropertyGpmID.Invoke(Connection, Transaction, new P_CAS_GCPVfCIDsaCGpmID_0832()
                                {
                                    CaseIDs        = new Guid[] { existingBillPosition.CaseID },
                                    IncludeDeleted = true,
                                    PropertyGpmID  = ECaseProperty.MissingIvom.Value()
                                }, securityTicket).Result.Any();

                                var octIds = new List <Guid>();
                                if (isAutoGenerated)
                                {
                                    var caseBillCodeIds = cls_Get_CaseBillCodeIDs_for_GposType_and_CaseID.Invoke(Connection, Transaction, new P_CAS_GCBCIDsfGposTaCID_1622()
                                    {
                                        CaseID      = existingBillPosition.CaseID,
                                        OctGposType = EGposType.Oct.Value()
                                    }, securityTicket).Result;

                                    foreach (var caseBillCodeId in caseBillCodeIds)
                                    {
                                        var caseBillCode = new ORM_HEC_CAS_Case_BillCode();
                                        caseBillCode.Load(Connection, Transaction, caseBillCodeId.HEC_CAS_Case_BillCodeID);

                                        caseBillCode.HEC_CAS_Case_RefID     = Parameter.case_id;
                                        caseBillCode.Modification_Timestamp = DateTime.Now;

                                        caseBillCode.Save(Connection, Transaction);
                                    }

                                    var relevantActions = ORM_HEC_CAS_Case_RelevantPlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_CAS_Case_RelevantPlannedAction.Query()
                                    {
                                        Case_RefID   = existingBillPosition.CaseID,
                                        Tenant_RefID = securityTicket.TenantID,
                                        IsDeleted    = false
                                    });

                                    foreach (var relevantAction in relevantActions)
                                    {
                                        relevantAction.Case_RefID             = Parameter.case_id;
                                        relevantAction.Modification_Timestamp = DateTime.Now;

                                        relevantAction.Save(Connection, Transaction);

                                        octIds.Add(relevantAction.PlannedAction_RefID);
                                    }
                                }

                                cls_Calculate_Case_GPOS.Invoke(Connection, Transaction, new P_CAS_CCGPOS_1000()
                                {
                                    case_id        = Parameter.case_id,
                                    diagnose_id    = Parameter.diagnose_id,
                                    drug_id        = Parameter.drug_id,
                                    patient_id     = Parameter.patient_id,
                                    localization   = Parameter.localization,
                                    treatment_date = Parameter.treatment_date,
                                    oct_doctor_id  = Parameter.oct_doctor_id
                                }, securityTicket);
                            }
                        }
                    }
                    else if (Parameter.localization_changed)
                    {
                        var old_localization = Parameter.localization == "L" ? "R" : "L";

                        #region OCT e-mail
                        var patient_consent_valid_for_months_parameter = cls_Get_ConsentValidForMonths_for_LatestConsent_before_TreatmentDate_for_PatientID.Invoke(Connection, Transaction, new P_PA_GCVfMfLCbTDfPID_0930()
                        {
                            PatientID     = Parameter.patient_id,
                            TreatmentDate = Parameter.treatment_date.Date
                        }, securityTicket).Result;

                        var performedOcts = cls_Get_NonCancelledOcts_in_OpRenewedConsentTimespan.Invoke(Connection, Transaction, new P_CAS_GNCOctsiOPRCT_1416()
                        {
                            PatientID = Parameter.patient_id,
                            PlannedOctActionTypeID = oct_planned_action_type_id,
                            ConsentStart           = Parameter.treatment_date.Date,
                            ConsentEnd             = Parameter.treatment_date.Date.AddMonths(patient_consent_valid_for_months_parameter != null && patient_consent_valid_for_months_parameter.consent_valid_for_months < 200000 ? Convert.ToInt32(patient_consent_valid_for_months_parameter.consent_valid_for_months) : 12)
                        }, securityTicket).Result.Where(t => t.localization == old_localization).ToList();

                        if (performedOcts.Any())
                        {
                            var mailToL = new List <String>();

                            var accountMails = cls_Get_All_Account_LoginEmails_Who_Receive_Notifications.Invoke(Connection, Transaction, securityTicket).Result.ToList();
                            foreach (var mail in accountMails)
                            {
                                mailToL.Add(mail.LoginEmail);
                            }

                            var mailToFromCompanySettings = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                            mailToL.Add(mailToFromCompanySettings);

                            var appName        = WebConfigurationManager.AppSettings["mmAppUrl"];
                            var prefix         = HttpContext.Current.Request.Url.AbsoluteUri.Contains("https") ? "https://" : "http://";
                            var imageUrl       = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("api")) + "Content/images/logo.png";
                            var email_template = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/TreatmentCancelledFromSettlementPageOctSubmittedEmailTemplate .html"));

                            var     subjectsJson = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailSubjects.json"));
                            dynamic subjects     = JsonConvert.DeserializeObject(subjectsJson);
                            var     subjectMail  = subjects["TreatmentCancelledFromSettlementPageSubject"].ToString();

                            var patient_information = cls_Get_Patient_Details_for_PatientID.Invoke(Connection, Transaction, new P_P_PA_GPDfPID_1124()
                            {
                                PatientID = Parameter.patient_id
                            }, securityTicket).Result;
                            var treatment_doctor_details = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                            {
                                DoctorID = Parameter.treatment_doctor_id
                            }, securityTicket).Result.First();

                            email_template = EmailTemplater.SetTemplateData(email_template, new
                            {
                                patient_first_name          = patient_information.patient_first_name,
                                patient_last_name           = patient_information.patient_last_name,
                                treatment_date              = Parameter.treatment_date.ToString("dd.MM.yyyy"),
                                treatment_doctor_title      = treatment_doctor_details.title,
                                treatment_doctor_first_name = treatment_doctor_details.first_name,
                                treatment_doctor_last_name  = treatment_doctor_details.last_name,
                                octs = performedOcts,
                                mmapp_treatment_page_url = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName + "/#/treatment",
                                medios_connect_logo_url  = imageUrl
                            }, "{{", "}}");

                            try
                            {
                                string mailFrom = WebConfigurationManager.AppSettings["mailFrom"];

                                var mailsDistinct = mailToL.Distinct().ToList();
                                foreach (var mailTo in mailsDistinct)
                                {
                                    EmailNotificationSenderUtil.SendEmail(mailFrom, mailTo, subjectMail, email_template);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogUtils.Logger.LogDocAppInfo(new LogUtils.LogEntry(System.Reflection.MethodInfo.GetCurrentMethod(), ex, null, "Cancel case from settlement: Email sending failed."), "EmailExceptions");
                            }
                        }
                        #endregion

                        #region OCT withdrawal
                        var existing_open_bill_position = cls_Get_Existing_OCT_BillPosition_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GEBPfCID_1522()
                        {
                            CaseID = Parameter.case_id
                        }, securityTicket).Result;

                        if (existing_open_bill_position != null)
                        {
                            var non_performed_oct = cls_Get_NonPerformed_Oct_for_CaseID_and_PlannedActionTypeID.Invoke(Connection, Transaction, new P_CAS_GNPOctfCIDaPATID_1240()
                            {
                                CaseID = Parameter.case_id,
                                OctPlannedActionTypeID = oct_planned_action_type_id
                            }, securityTicket).Result;

                            var oct_planned_action = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                            {
                                HEC_ACT_PlannedActionID = non_performed_oct.action_id
                            }).Single();

                            oct_planned_action.IsCancelled            = true;
                            oct_planned_action.Modification_Timestamp = DateTime.Now;
                            oct_planned_action.Save(Connection, Transaction);

                            var new_id = cls_Create_OCT.Invoke(Connection, Transaction, new P_CAS_COCT_1703()
                            {
                                case_id            = Parameter.case_id,
                                oct_action_type_id = oct_planned_action_type_id,
                                oct_bpt_id         = oct_doctor.BusinessParticipant_RefID,
                                patient_id         = Parameter.patient_id,
                                practice_id        = Parameter.oct_doctor_practice_id,
                                treatment_date     = Parameter.treatment_date
                            }, securityTicket).Result;
                        }
                        #endregion
                    }
                }
                #endregion

                #region Case submission
                else
                {
                    var existingBillPosition = cls_Get_Existing_OCT_BillPosition_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GEBPfPIDaLC_1803()
                    {
                        LocalizationCode = Parameter.localization,
                        PatientID        = Parameter.patient_id
                    }, securityTicket).Result;

                    if (existingBillPosition != null)
                    {
                        var oct_planned_actions = cls_Get_Latest_PlannedActionID_for_PatientID_ActionTypeID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GLPAIDfPIDATIDaLC_1545()
                        {
                            ActionTypeID     = oct_planned_action_type_id,
                            PatientID        = Parameter.patient_id,
                            LocalizationCode = Parameter.localization
                        }, securityTicket).Result;
                        var oct = new Oct_Model();

                        #region Magic
                        // don't ask
                        var i = 0;
                        do
                        {
                            var oct_planned_action = oct_planned_actions[i++];
                            oct = Retrieve_Octs.GetOctForID(oct_planned_action.PlannedActionID.ToString(), elastic_index);
                            returnValue.Result = oct_planned_action.PlannedActionID;
                        } while (i < oct_planned_actions.Length && oct == null);
                        #endregion

                        if (oct != null)
                        {
                            if (case_properties.Any(t => t.property_gpmid == ECaseProperty.WithdrawOct.Value() || t.property_gpmid == ECaseProperty.SubmitOctUntilDate.Value()))
                            {
                                var withdraw_oct_property = case_properties.SingleOrDefault(t => t.property_gpmid == ECaseProperty.WithdrawOct.Value());
                                if (withdraw_oct_property != null)
                                {
                                    var doctor_whose_oct_is_withdrawn_bpt_id = Guid.Parse(withdraw_oct_property.string_value);
                                    var planned_oct_to_withdraw = oct_planned_actions.First(t => t.CaseID != Parameter.case_id && t.DoctorBptID == doctor_whose_oct_is_withdrawn_bpt_id);
                                    var planned_oct_action      = new ORM_HEC_ACT_PlannedAction();
                                    planned_oct_action.Load(Connection, Transaction, planned_oct_to_withdraw.PlannedActionID);
                                    planned_oct_action.IsCancelled            = true;
                                    planned_oct_action.Modification_Timestamp = DateTime.Now;

                                    planned_oct_action.Save(Connection, Transaction);
                                }
                            }
                            else
                            {
                                var oct_doctor_bpt_id = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
                                {
                                    HEC_DoctorID = Parameter.oct_doctor_id
                                }).Single().BusinessParticipant_RefID;
                                var oct_planned = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                                {
                                    HEC_ACT_PlannedActionID = returnValue.Result
                                }).Single();
                                oct_planned.ToBePerformedBy_BusinessParticipant_RefID = oct_doctor_bpt_id;
                                oct_planned.Modification_Timestamp = DateTime.Now;

                                oct_planned.Save(Connection, Transaction);

                                if (oct.status == "OCT6")
                                {
                                    var case_with_pending_oct = cls_Get_CaseIDs_with_Pending_Octs_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GCIDswPOctsfPIDaLC_1103()
                                    {
                                        LocalizationCode = Parameter.localization,
                                        PatientID        = Parameter.patient_id
                                    }, securityTicket).Result.SingleOrDefault();

                                    if (case_with_pending_oct != null)
                                    {
                                        var fs_status = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, new ORM_BIL_BillPosition_TransmitionStatus.Query()
                                        {
                                            BIL_BillPosition_TransmitionStatusID = case_with_pending_oct.fs_status_id
                                        }).Single();
                                        fs_status.IsActive = false;
                                        fs_status.Modification_Timestamp = DateTime.Now;

                                        fs_status.Save(Connection, Transaction);

                                        var new_fs_status = new ORM_BIL_BillPosition_TransmitionStatus();
                                        new_fs_status.IsActive = true;
                                        new_fs_status.IsTransmitionStatusManuallySet = false;
                                        new_fs_status.BillPosition_RefID             = fs_status.BillPosition_RefID;
                                        new_fs_status.Modification_Timestamp         = DateTime.Now;
                                        new_fs_status.Tenant_RefID         = securityTicket.TenantID;
                                        new_fs_status.TransmissionDataXML  = fs_status.TransmissionDataXML;
                                        new_fs_status.TransmitionCode      = 1;
                                        new_fs_status.TransmitionStatusKey = "oct";
                                        new_fs_status.TransmittedOnDate    = DateTime.Now;

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

            return(returnValue);

            #endregion UserCode
        }