Beispiel #1
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_CAS_CCFSP_1751 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
            var returnValue = new FR_Guid();
            var mailSent    = false;

            bool isACCanceled = false;
            Guid aftercareID  = Guid.Empty;
            var  gpos_type    = EGposType.Oct.Value();
            if (Parameter.caseType == "op")
            {
                gpos_type = EGposType.Operation.Value();
            }
            else if (Parameter.caseType == "ac")
            {
                gpos_type = EGposType.Aftercare.Value();
            }

            var case_to_submit = cls_Get_Case_Details_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCDfCID_1435()
            {
                CaseID = Parameter.case_id
            }, securityTicket).Result;
            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 aftercare_practice_details = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
            {
                PracticeID = case_to_submit.aftercare_doctors_practice_id
            }, securityTicket).Result.FirstOrDefault();
            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 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 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 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();

            if (Parameter.caseType == "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 current_case_status = cls_Get_Case_TransmitionCode_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GCTCfCID_1427()
            {
                CaseID = Parameter.case_id
            }, securityTicket).Result.FirstOrDefault(st => st.gpos_type == gpos_type && st.fs_status != 8 && st.fs_status != 17 && st.fs_status != 11);
            if (current_case_status == null)
            {
                throw new Exception(String.Format("Current FS status not found for case id: {0}, planned action id: {1}, case type: {2}", Parameter.case_id, Parameter.planned_action_id, Parameter.caseType));
            }
            var current_status = "FS" + current_case_status.fs_status;

            if (Parameter.caseType == "op")
            {
                var bill_positions = cls_Get_BillPositionIDs_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GBPIDsfCID_0928()
                {
                    CaseID = Parameter.case_id
                }, securityTicket).Result;

                #region CHANGE TREATMENT STATUS
                foreach (var bill_position in bill_positions)
                {
                    ORM_BIL_BillPosition_TransmitionStatus.Query transmition_statusQ = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                    transmition_statusQ.BillPosition_RefID   = bill_position.bill_position_id;
                    transmition_statusQ.TransmitionStatusKey = "treatment";
                    transmition_statusQ.Tenant_RefID         = securityTicket.TenantID;
                    transmition_statusQ.IsDeleted            = false;
                    transmition_statusQ.IsActive             = true;

                    var transmition_status = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, transmition_statusQ).SingleOrDefault();
                    if (transmition_status != null && transmition_status.TransmitionCode != 8 && transmition_status.TransmitionCode != 11)
                    {
                        transmition_status.IsActive = false;
                        transmition_status.Modification_Timestamp = DateTime.Now;
                        transmition_status.Save(Connection, Transaction);

                        ORM_BIL_BillPosition_TransmitionStatus position_status = new ORM_BIL_BillPosition_TransmitionStatus();
                        position_status.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                        position_status.BillPosition_RefID     = bill_position.bill_position_id;
                        position_status.Creation_Timestamp     = DateTime.Now;
                        position_status.IsActive               = true;
                        position_status.PrimaryComment         = Parameter.reasonForCancelation;
                        position_status.Modification_Timestamp = DateTime.Now;
                        position_status.TransmitionCode        = transmition_status.TransmitionCode != 2 ? 8 : 11;
                        position_status.TransmittedOnDate      = DateTime.Now;
                        position_status.Tenant_RefID           = securityTicket.TenantID;
                        position_status.TransmitionStatusKey   = "treatment";

                        #region CREATE SNAPSHOT
                        DateTime today = DateTime.Today;
                        int      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 = GenericUtils.GetDoctorName(treatment_doctor_details),
                            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)
                        {
                            position_status.TransmissionDataXML = snapshot.XmlFileString;
                        }

                        #endregion

                        position_status.Save(Connection, Transaction);

                        current_status = "FS" + position_status.TransmitionCode;
                    }
                }

                #region Aftercare e-mail
                var aftercarePlannedAction = cls_Get_Aftercare_Planned_Action_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GAPAfCID_0959 {
                    CaseID = Parameter.case_id
                }, securityTicket).Result;

                if (aftercarePlannedAction != null)
                {
                    var originalAftercarePlannedAction = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query {
                        HEC_ACT_PlannedActionID = aftercarePlannedAction.planned_action_id, Tenant_RefID = securityTicket.TenantID, IsDeleted = false, IsCancelled = false
                    }).SingleOrDefault();

                    if (originalAftercarePlannedAction != null)
                    {
                        if (!originalAftercarePlannedAction.IsPerformed)
                        {
                            originalAftercarePlannedAction.IsCancelled = true;
                            originalAftercarePlannedAction.Save(Connection, Transaction);
                            isACCanceled = true;
                            aftercareID  = originalAftercarePlannedAction.HEC_ACT_PlannedActionID;
                        }
                        else
                        {
                            if (!mailSent)
                            {
                                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);
                                }
                                //  mailToL.Add(emailTo);
                                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/TreatmentCancelledFromSettlementPageEmailTemplate.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              = case_to_submit.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,
                                    aftercare_doctor_title      = aftercare_doctor_details.title,
                                    doctors_comment             = Parameter.reasonForCancelation,
                                    aftercare_doctor_first_name = aftercare_doctor_details.first_name,
                                    aftercare_doctor_last_name  = aftercare_doctor_details.last_name,
                                    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);
                                    }
                                    mailSent = true;
                                }
                                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 e-mail
                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 patient_consent_valid_for_months_parameter = cls_Get_ConsentValidForMonths_for_LatestConsent_before_TreatmentDate_for_PatientID.Invoke(Connection, Transaction, new P_PA_GCVfMfLCbTDfPID_0930()
                {
                    PatientID     = case_to_submit.patient_id,
                    TreatmentDate = case_to_submit.treatment_date.Date
                }, securityTicket).Result;

                var performedOcts = cls_Get_NonCancelledOcts_in_OpRenewedConsentTimespan.Invoke(Connection, Transaction, new P_CAS_GNCOctsiOPRCT_1416()
                {
                    PatientID = case_to_submit.patient_id,
                    PlannedOctActionTypeID = oct_planned_action_type_id,
                    ConsentStart           = case_to_submit.treatment_date.Date,
                    ConsentEnd             = case_to_submit.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;

                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();

                    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              = case_to_submit.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,
                        doctors_comment          = Parameter.reasonForCancelation,
                        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);
                        }
                        mailSent = true;
                    }
                    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 treatment_year_start_date = cls_Get_TreatmentYear.Invoke(Connection, Transaction, new P_CAS_GTY_1125()
                {
                    Date             = case_to_submit.treatment_date,
                    LocalizationCode = case_to_submit.localization,
                    PatientID        = case_to_submit.patient_id
                }, securityTicket).Result;

                var treatment_year_length = cls_Get_TreatmentYearLength.Invoke(Connection, Transaction, new P_CAS_GTYL_1317()
                {
                    Date      = case_to_submit.treatment_date,
                    PatientID = case_to_submit.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       = case_to_submit.localization,
                    PatientID              = case_to_submit.patient_id,
                    TreatmentYearStartDate = treatment_year_start_date,
                    TreatmentYearEndDate   = treatment_year_start_date.AddDays(treatment_year_length - 1)
                }, securityTicket).Result;

                if (!ops_in_treatment_year.Any(t => t.CaseID != Parameter.case_id && ((!t.IsPerformed && !t.IsDeleted) || (t.IsPerformed && t.FsStatus != 8 && t.FsStatus != 11 && t.FsStatus != 17))))
                {
                    foreach (var potential_op in ops_in_treatment_year)
                    {
                        var non_performed_oct = cls_Get_NonPerformed_Oct_for_CaseID_and_PlannedActionTypeID.Invoke(Connection, Transaction, new P_CAS_GNPOctfCIDaPATID_1240()
                        {
                            CaseID = potential_op.CaseID,
                            OctPlannedActionTypeID = oct_planned_action_type_id
                        }, securityTicket).Result;

                        if (non_performed_oct != null)
                        {
                            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);

                            break;
                        }
                    }
                }
                #endregion

                #endregion
            }
            else if (Parameter.caseType == "oct")
            {
                #region CHANGE OCT STATUS
                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 oct_performed_data = cls_Get_PerformedActionDate_for_PlannedActionID.Invoke(Connection, Transaction, new P_CAS_GPADfPAID_1613()
                {
                    ActionID = Parameter.planned_action_id
                }, securityTicket).Result;

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

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

                var relevant_actions = cls_Get_RelevantActionIDs_for_PatientID_and_LocalizationCode.Invoke(Connection, Transaction, new P_CAS_GRAIDsfPIDaLC_1011()
                {
                    ActionTypeID           = oct_planned_action_type_id,
                    PatientID              = case_to_submit.patient_id,
                    LocalizationCode       = oct_performed_data.localization,
                    TreatmentYearStartDate = treatment_year_start_date,
                    TreatmentYearEndDate   = treatment_year_start_date.AddDays(treatment_year_length - 1)
                }, securityTicket).Result;

                var case_ids       = relevant_actions.Select(t => t.case_id).ToArray();
                var bill_positions = cls_Get_BillPositionIDs_for_CaseIDs_and_GposType.Invoke(Connection, Transaction, new P_CAS_GBPIDsfCIDsaGposT_1018()
                {
                    CaseIDs  = case_ids,
                    GposType = EGposType.Oct.Value()
                }, securityTicket).Result;

                for (var i = 0; i < relevant_actions.Length; i++)
                {
                    var relevant_action = relevant_actions[i];
                    if (relevant_action.action_id == Parameter.planned_action_id)
                    {
                        var bill_position = bill_positions[i];
                        ORM_BIL_BillPosition_TransmitionStatus.Query transmition_statusQ = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                        transmition_statusQ.BillPosition_RefID   = bill_position.bill_position_id;
                        transmition_statusQ.TransmitionStatusKey = "oct";
                        transmition_statusQ.Tenant_RefID         = securityTicket.TenantID;
                        transmition_statusQ.IsDeleted            = false;
                        transmition_statusQ.IsActive             = true;

                        var transmition_status = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, transmition_statusQ).SingleOrDefault();
                        if (transmition_status != null && transmition_status.TransmitionCode != 8 && transmition_status.TransmitionCode != 11 && transmition_status.TransmitionCode != 17)
                        {
                            transmition_status.IsActive = false;
                            transmition_status.Modification_Timestamp = DateTime.Now;
                            transmition_status.Save(Connection, Transaction);

                            ORM_BIL_BillPosition_TransmitionStatus position_status = new ORM_BIL_BillPosition_TransmitionStatus();
                            position_status.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                            position_status.BillPosition_RefID     = bill_position.bill_position_id;
                            position_status.Creation_Timestamp     = DateTime.Now;
                            position_status.IsActive               = true;
                            position_status.PrimaryComment         = Parameter.reasonForCancelation;
                            position_status.Modification_Timestamp = DateTime.Now;
                            position_status.TransmitionCode        = transmition_status.TransmitionCode != 2 ? 8 : 11;
                            position_status.TransmittedOnDate      = DateTime.Now;
                            position_status.Tenant_RefID           = securityTicket.TenantID;
                            position_status.TransmitionStatusKey   = "oct";

                            #region CREATE SNAPSHOT
                            DateTime today = DateTime.Today;
                            int      age   = today.Year - patient_details.birthday.Year;
                            if (patient_details.birthday > today.AddYears(-age))
                            {
                                age--;
                            }
                            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 snapshot = cls_Create_XML_for_Immutable_Fields.Invoke(Connection, Transaction, new P_CAS_CXFIF_0830()
                            {
                                DiagnosisCatalogCode             = diagnose_details.diagnose_icd_10,
                                DiagnosisCatalogName             = diagnose_details.catalog_display_name,
                                DiagnosisName                    = diagnose_details.diagnose_name,
                                IFPerformedMedicalPracticeName   = oct_doctor_details != null ? oct_doctor_details.practice : null,
                                IFPerformedResponsibleBPFullName = oct_doctor_details != null ? GenericUtils.GetDoctorName(oct_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)
                            {
                                position_status.TransmissionDataXML = snapshot.XmlFileString;
                            }

                            #endregion

                            position_status.Save(Connection, Transaction);
                            current_status = "FS" + position_status.TransmitionCode;
                        }

                        break;
                    }
                }
                #endregion
            }
            else
            {
                var bill_positions = cls_Get_BillPositionIDs_for_CaseID.Invoke(Connection, Transaction, new P_CAS_GBPIDsfCID_0928()
                {
                    CaseID = Parameter.case_id
                }, securityTicket).Result;

                foreach (var bill_position in bill_positions)
                {
                    #region CHANGE AFTERCARE STATUS
                    ORM_BIL_BillPosition_TransmitionStatus.Query transmition_statusQ = new ORM_BIL_BillPosition_TransmitionStatus.Query();
                    transmition_statusQ.BillPosition_RefID   = bill_position.bill_position_id;
                    transmition_statusQ.TransmitionStatusKey = "aftercare";
                    transmition_statusQ.Tenant_RefID         = securityTicket.TenantID;
                    transmition_statusQ.IsDeleted            = false;
                    transmition_statusQ.IsActive             = true;

                    var transmition_status = ORM_BIL_BillPosition_TransmitionStatus.Query.Search(Connection, Transaction, transmition_statusQ).SingleOrDefault();
                    if (transmition_status != null && transmition_status.TransmitionCode != 8 && transmition_status.TransmitionCode != 11 && transmition_status.TransmitionCode != 17)
                    {
                        transmition_status.IsActive = false;
                        transmition_status.Modification_Timestamp = DateTime.Now;
                        transmition_status.Save(Connection, Transaction);

                        ORM_BIL_BillPosition_TransmitionStatus position_status = new ORM_BIL_BillPosition_TransmitionStatus();
                        position_status.BIL_BillPosition_TransmitionStatusID = Guid.NewGuid();
                        position_status.BillPosition_RefID     = bill_position.bill_position_id;
                        position_status.Creation_Timestamp     = DateTime.Now;
                        position_status.IsActive               = true;
                        position_status.PrimaryComment         = Parameter.reasonForCancelation;
                        position_status.Modification_Timestamp = DateTime.Now;
                        position_status.TransmitionCode        = transmition_status.TransmitionCode != 2 ? 8 : 11;
                        position_status.TransmittedOnDate      = DateTime.Now;
                        position_status.Tenant_RefID           = securityTicket.TenantID;
                        position_status.TransmitionStatusKey   = "aftercare";

                        #region CREATE SNAPSHOT
                        DateTime today = DateTime.Today;
                        int      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.diagnose_icd_10,
                            DiagnosisCatalogName             = diagnose_details.catalog_display_name,
                            DiagnosisName                    = diagnose_details.diagnose_name,
                            IFPerformedMedicalPracticeName   = treatment_practice_details.practice_name,
                            IFPerformedResponsibleBPFullName = GenericUtils.GetDoctorName(treatment_doctor_details),
                            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)
                        {
                            position_status.TransmissionDataXML = snapshot.XmlFileString;
                        }

                        #endregion

                        position_status.Save(Connection, Transaction);
                        current_status = "FS" + position_status.TransmitionCode;
                    }

                    #endregion
                }
            }

            #region Send e-mail
            if (current_case_status != null && current_case_status.fs_status != 1 && !mailSent)
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
                List <String> 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);
                }

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

                string 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/AftercareCancelledFromSettlementPageEmailTemplate.html"));

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

                email_template = EmailTemplater.SetTemplateData(email_template, new
                {
                    case_type                = Parameter.caseType == "op" ? "Behandlung" : Parameter.caseType == "ac" ? "Nachsorge" : "OCT",
                    patient_first_name       = patient_details.patient_first_name,
                    patient_last_name        = patient_details.patient_last_name,
                    treatment_date           = case_to_submit.treatment_date.ToString("dd.MM.yyyy"),
                    doctor_title             = Parameter.caseType == "op" || Parameter.caseType == "oct" ? treatment_doctor_details.title : aftercare_doctor_details.title,
                    doctor_first_name        = Parameter.caseType == "op" || Parameter.caseType == "oct" ? treatment_doctor_details.first_name : aftercare_doctor_details.first_name,
                    doctor_last_name         = Parameter.caseType == "op" || Parameter.caseType == "oct" ? treatment_doctor_details.last_name : aftercare_doctor_details.last_name,
                    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 treatment/aftercare from settlement: Email sending failed."), "EmailExceptions");
                }
            }
            #endregion

            returnValue.Result = case_to_submit.patient_id;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #2
0
        protected static FR_String Execute(DbConnection Connection, DbTransaction Transaction, P_OR_SOtMM_1311 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_String();
            //Put your code here

            var data = cls_Get_Account_Information_with_PracticeID.Invoke(Connection, Transaction, securityTicket).Result;

            var isNewPharmacy = Parameter.Order.default_pharmacy == Guid.Empty;

            var current_order_status      = isNewPharmacy ? "MO10" : "MO1";
            var current_order_status_code = isNewPharmacy ? 10 : 1;

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

            var practice_info = cls_Get_Practice_Details_for_Report.Invoke(Connection, Transaction, new P_DO_GPDFR_0840()
            {
                PracticeID = data.PracticeID
            }, securityTicket).Result;

            var trigger_acc = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
            {
                USR_AccountID = securityTicket.AccountID
            }).Single();
            var culture            = new CultureInfo("de", true);
            var delivery_date      = DateTime.ParseExact(Parameter.Order.delivery_date, "dd.MM.yyyy", culture);
            var delivery_date_from = DateTime.ParseExact(Parameter.Order.delivery_date_from, "HH:mm", culture);
            delivery_date_from = delivery_date.AddHours(delivery_date_from.Hour).AddMinutes(delivery_date_from.Minute);
            var delivery_date_to = DateTime.ParseExact(Parameter.Order.delivery_date_to, "HH:mm", culture);
            delivery_date_to = delivery_date.AddHours(delivery_date_to.Hour).AddMinutes(delivery_date_to.Minute);
            var drug_names   = new List <string>();
            var cmn_products = ORM_CMN_PRO_Product.Query.Search(Connection, Transaction, new ORM_CMN_PRO_Product.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            });
            var hec_products = ORM_HEC_Product.Query.Search(Connection, Transaction, new ORM_HEC_Product.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            });
            var drugs = cls_Get_Drug_Details_on_Tenant.Invoke(Connection, Transaction, securityTicket).Result;

            #region save and get pharmacy
            if (isNewPharmacy)
            {
                Parameter.Order.default_pharmacy = cls_Save_Pharmacy.Invoke(Connection, Transaction, new P_PH_SP_1124
                {
                    Pharmacy = new Pharmacy.Model.Pharmacy(Guid.Empty, Parameter.Order.pharmacy_name, String.Empty, String.Empty,
                                                           String.Empty, Parameter.Order.pharmacy_street, Parameter.Order.pharmacy_street_number, Parameter.Order.pharmacy_zip_code,
                                                           Parameter.Order.pharmacy_town, true, String.Empty)
                }, securityTicket).Result;
            }

            var pharmacy = cls_Get_Pharmacy_for_PharmacyID.Invoke(Connection, Transaction, new P_PH_GPfPID_1535
            {
                PharmacyID = Parameter.Order.default_pharmacy
            }, securityTicket).Result;
            #endregion

            var ordersForReport = new List <ReportOrderItem>();

            foreach (var order_id in Parameter.Order.order_ids)
            {
                #region Status
                var header = ORM_ORD_PRC_ProcurementOrder_Header.Query.Search(Connection, Transaction, new ORM_ORD_PRC_ProcurementOrder_Header.Query()
                {
                    ORD_PRC_ProcurementOrder_HeaderID = order_id,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();

                header.ProcurementOrder_Supplier_RefID = pharmacy != null ? pharmacy.CompanyBPID : Guid.Empty;

                var header_comment = new ORM_ORD_PRC_ProcurementOrder_Note();
                header_comment.Comment      = Parameter.Order.comment;
                header_comment.Title        = "Order comment";
                header_comment.Tenant_RefID = securityTicket.TenantID;
                header_comment.ORD_PRC_ProcurementOrder_Header_RefID = order_id;

                header_comment.Save(Connection, Transaction);

                ORM_ORD_PRC_ProcurementOrder_Position.Query order_positionQ = new ORM_ORD_PRC_ProcurementOrder_Position.Query();
                order_positionQ.Tenant_RefID = securityTicket.TenantID;
                order_positionQ.IsDeleted    = false;
                order_positionQ.ProcurementOrder_Header_RefID = order_id;
                var order_position   = ORM_ORD_PRC_ProcurementOrder_Position.Query.Search(Connection, Transaction, order_positionQ).SingleOrDefault();
                var position_comment = order_position != null ? order_position.Position_Comment ?? String.Empty : String.Empty;

                var drug_order_status = new ORM_ORD_PRC_ProcurementOrder_Status();
                drug_order_status.GlobalPropertyMatchingID = String.Format("mm.doc.connect.drug.order.status.{0}", current_order_status.ToLower());
                drug_order_status.Status_Code  = current_order_status_code;
                drug_order_status.Tenant_RefID = securityTicket.TenantID;
                drug_order_status.Status_Name  = new Dict(ORM_ORD_PRC_ProcurementOrder_Status.TableName);
                foreach (var lang in all_languages)
                {
                    drug_order_status.Status_Name.AddEntry(lang.CMN_LanguageID, current_order_status);
                }
                drug_order_status.Save(Connection, Transaction);

                var drug_order_status_history = new ORM_ORD_PRC_ProcurementOrder_StatusHistory();
                drug_order_status_history.ProcurementOrder_Header_RefID = header.ORD_PRC_ProcurementOrder_HeaderID;
                drug_order_status_history.ProcurementOrder_Status_RefID = drug_order_status.ORD_PRC_ProcurementOrder_StatusID;
                drug_order_status_history.Tenant_RefID     = securityTicket.TenantID;
                drug_order_status_history.IsStatus_Created = true;
                drug_order_status_history.TriggeredAt_Date = DateTime.Now;
                drug_order_status_history.TriggeredBy_BusinessParticipant_RefID = trigger_acc.BusinessParticipant_RefID;
                drug_order_status_history.Save(Connection, Transaction);

                header.Current_ProcurementOrderStatus_RefID = drug_order_status.ORD_PRC_ProcurementOrder_StatusID;
                header.Save(Connection, Transaction);
                #endregion Status

                var ord_drug_order = ORM_ORD_PRC_ProcurementOrder_Position.Query.Search(Connection, Transaction, new ORM_ORD_PRC_ProcurementOrder_Position.Query()
                {
                    ProcurementOrder_Header_RefID = order_id,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();


                ord_drug_order.Position_RequestedDateOfDelivery       = delivery_date.Date;
                ord_drug_order.RequestedDateOfDelivery_TimeFrame_From = delivery_date_from;
                ord_drug_order.RequestedDateOfDelivery_TimeFrame_To   = delivery_date_to;
                ord_drug_order.Save(Connection, Transaction);

                var hec_drug_order = ORM_HEC_PRC_ProcurementOrder_Position.Query.Search(Connection, Transaction, new ORM_HEC_PRC_ProcurementOrder_Position.Query()
                {
                    Ext_ORD_PRC_ProcurementOrder_Position_RefID = ord_drug_order.ORD_PRC_ProcurementOrder_PositionID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();

                var drug_id = ORM_HEC_ACT_PlannedAction_PotentialProcedure_RequiredProduct.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction_PotentialProcedure_RequiredProduct.Query()
                {
                    BoundTo_HealthcareProcurementOrderPosition_RefID = hec_drug_order.HEC_PRC_ProcurementOrder_PositionID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single().HealthcareProduct_RefID;

                var drugName = drugs.First(t => t.DrugID == drug_id).DrugName;
                drug_names.Add(drugName);

                if (Parameter.Order.doctor_id != Guid.Empty)
                {
                    var authorizing_doctor_details = cls_Get_Doctor_BasicInformation_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDBIfDID_1034()
                    {
                        DoctorID = Parameter.Order.doctor_id
                    }, securityTicket).Result;

                    hec_drug_order.Clearing_Doctor_RefID      = Parameter.Order.doctor_id;
                    hec_drug_order.ClearingDoctor_DisplayName = GenericUtils.GetDoctorName(authorizing_doctor_details);
                    hec_drug_order.Save(Connection, Transaction);
                }

                var shipping_address = new ORM_CMN_UniversalContactDetail();
                shipping_address.Modification_Timestamp = DateTime.Now;
                shipping_address.Tenant_RefID           = securityTicket.TenantID;
                shipping_address.Street_Name            = Parameter.Order.street;
                shipping_address.Street_Number          = Parameter.Order.number;
                shipping_address.ZIP  = Parameter.Order.zip;
                shipping_address.Town = Parameter.Order.city;
                shipping_address.CompanyName_Line1 = Parameter.Order.receiver;
                shipping_address.Save(Connection, Transaction);

                var ord_drug_order_header = new ORM_ORD_PRC_ProcurementOrder_Header();
                ord_drug_order_header.Load(Connection, Transaction, ord_drug_order.ProcurementOrder_Header_RefID);
                ord_drug_order_header.ShippingAddressUCD_RefID        = shipping_address.CMN_UniversalContactDetailID;
                ord_drug_order_header.Modification_Timestamp          = DateTime.Now;
                ord_drug_order_header.ProcurementOrder_Supplier_RefID = pharmacy != null ? pharmacy.CompanyBPID : Guid.Empty;
                ord_drug_order_header.Save(Connection, Transaction);


                ordersForReport.Add(new ReportOrderItem
                {
                    Name            = drugName,
                    PositionComment = position_comment,
                    Patient         = new ReportOrderPatientInformation
                    {
                        PatientID = hec_drug_order.OrderedFor_Patient_RefID,
                        FeeWaived = hec_drug_order.IsOrderForPatient_PatientFeeWaived
                    }
                });
            }

            #region Send e-mail if urgent order

            var defaultshippingDateOffset = cls_Get_Practice_PropertyValue_for_PropertyName_and_PracticeID.Invoke(Connection, Transaction, new P_DO_GPPVfPNaPID_0916()
            {
                PracticeID   = data.PracticeID,
                PropertyName = "Default Shipping Date Offset"
            }, securityTicket).Result.NumericValue;

            var company_settings = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result;
            var ordernum         = company_settings.ImmediateOrderInterval;

            if (delivery_date > DateTime.Now.AddDays(-defaultshippingDateOffset).AddMinutes(ordernum))
            {
                try
                {
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
                    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 = company_settings.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/UrgentOrderEmailTemplate.html"));

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

                    email_template = EmailTemplater.SetTemplateData(email_template, new
                    {
                        orders = drug_names.Select(t => new
                        {
                            order_date_time_from = delivery_date_from.ToString("dd.MM.yyyy HH:mm"),
                            order_date_time_to   = delivery_date_to.ToString("HH:mm"),
                            name      = data.AccountInformation.name,
                            drug_name = t
                        }),
                        mmapp_dashboard_url     = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                        medios_connect_logo_url = imageUrl
                    }, "{{", "}}");

                    var 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, "Urgent order: Email sending failed."), "EmailExceptions");
                }
            }

            #endregion SEND MAIL URGENT ORDER

            #region Update case order number
            var case_order_number = cls_Save_Case_Order_Number_for_OrderIDs.Invoke(Connection, Transaction, new P_CAS_SCONfOID_1442
            {
                order_ids     = Parameter.Order.order_ids.ToArray(),
                practice_bsnr = practice_info.BSNR
            }, securityTicket).Result;
            #endregion

            #region Create PDF report
            if (isNewPharmacy)
            {
                #region patient information
                var patients_info = cls_Get_Patient_Details_for_PatientIDs.Invoke(Connection, Transaction, new P_PA_GPDfPIDs_1354
                {
                    PatientIDs = ordersForReport.Select(x => x.Patient).Select(x => x.PatientID).Distinct().ToArray()
                }, securityTicket).Result;

                foreach (var order in ordersForReport)
                {
                    var patient_info = patients_info.Single(x => x.PatientID == order.Patient.PatientID);

                    order.Patient.FirstName       = patient_info.FirstName;
                    order.Patient.LastName        = patient_info.LastName;
                    order.Patient.BirthDate       = patient_info.BirthDate;
                    order.Patient.Hip             = patient_info.HipName;
                    order.Patient.InsuranceStatus = patient_info.InsuranceStatus;
                }
                #endregion

                #region Repack data for report
                var orderPdfReport  = new OrderPdfReportGenerator();
                var reportOrderInfo = new ReportOrderInformation
                {
                    DeliveryDate     = delivery_date,
                    DeliveryTimeFrom = delivery_date_from,
                    DeliveryTimeTo   = delivery_date_to,
                    CreationDate     = DateTime.Now,
                    OrderNumber      = case_order_number,
                    HeaderComment    = Parameter.Order.comment ?? String.Empty,
                    OrderedDrugs     = ordersForReport,
                };
                var reportPractice = new OrderParticipantInformation
                {
                    City   = practice_info.City,
                    Email  = practice_info.Contact_Email,
                    Name   = practice_info.Name,
                    Number = practice_info.Street_Number,
                    Phone  = practice_info.Contact_Telephone,
                    Street = practice_info.Street_Name,
                    Zip    = practice_info.ZIP
                };
                var reportPharmacy = new OrderParticipantInformation
                {
                    Name   = pharmacy.PharmacyName,
                    Street = pharmacy.Street_Name,
                    Number = pharmacy.Street_Number,
                    Zip    = pharmacy.ZIP,
                    City   = pharmacy.Town,
                    Email  = pharmacy.Contact_Email,
                    Phone  = pharmacy.Contact_Telephone
                };
                #endregion

                var bytes = orderPdfReport.Generate(
                    new Model.OrderReportParameters
                {
                    Orders   = reportOrderInfo,
                    Pharmacy = reportPharmacy,
                    Practice = reportPractice
                },
                    HttpContext.Current.Server.MapPath("~/ReportContent/SubmitOrderPdfReportContent.xml")
                    );

                var _providerFactory = ProviderFactory.Instance;
                var documentProvider = _providerFactory.CreateDocumentServiceProvider();
                var fileName         = String.Format("{0}-{1}-{2}.pdf", "Submited Orders", pharmacy.PharmacyName, DateTime.Now.ToString("dd.MM.yyyy HH:mm"));
                var documentID       = documentProvider.UploadDocument(bytes, fileName, securityTicket.SessionTicket, HttpContext.Current.Request.UserHostAddress);
                var reportURL        = documentProvider.GenerateDownloadLink(documentID, securityTicket.SessionTicket, true, true);

                var parameterDoc = new P_OR_UOPDFR_1049();

                parameterDoc.DocumentID      = documentID;
                parameterDoc.Mime            = UtilMethods.GetMimeType(fileName);
                parameterDoc.DocumentName    = fileName;
                parameterDoc.CaseOrderNumber = case_order_number;
                parameterDoc.OrderIDs        = Parameter.Order.order_ids.ToArray();

                cls_Upload_Order_PDF_Report.Invoke(Connection, Transaction, parameterDoc, securityTicket);

                returnValue.Result = reportURL;
            }
            #endregion

            return(returnValue);

            #endregion UserCode
        }
Beispiel #3
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_MD_SAU_1236 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
            IAccountServiceProvider accountService;
            var _providerFactory = ProviderFactory.Instance;
            accountService = _providerFactory.CreateAccountServiceProvider();

            var accId = Guid.NewGuid();
            if (Parameter.UserID == Guid.Empty)
            {
                if (!String.IsNullOrEmpty(Parameter.LoginEmail))
                {
                    string[] stringUser  = Parameter.LoginEmail.Split('@');
                    string   usernameStr = stringUser[0];

                    Person UserAccount = new Person();
                    UserAccount.FirstName = Parameter.FirstName;
                    UserAccount.LastName  = Parameter.LastName;
                    UserAccount.Title     = string.IsNullOrEmpty(Parameter.Title) ? "" : Parameter.Title;
                    Account account = new Account();
                    account.Person       = UserAccount;
                    account.ID           = accId;
                    account.TenantID     = securityTicket.TenantID;
                    account.Email        = Parameter.LoginEmail;
                    account.PasswordHash = Parameter.inPassword;
                    account.Username     = usernameStr;
                    account.AccountType  = EAccountType.Standard;
                    account.Verified     = true;
                    accountService.CreateAccount(account, securityTicket.SessionTicket);
                    accountService.VerifyAccount(account.ID);

                    try
                    {
                        string emailTo  = Parameter.LoginEmail;
                        string 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/NewUserTemplate.html"));
                        var     subjectsJson   = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailSubjects.json"));
                        dynamic subjects       = Newtonsoft.Json.JsonConvert.DeserializeObject(subjectsJson);
                        var     subjectMail    = subjects["NewUserSubject"].ToString();

                        email_template = EmailTemplater.SetTemplateData(email_template, new
                        {
                            first_name = Parameter.FirstName,
                            salutation = Parameter.Salutation,
                            last_name  = Parameter.LastName,
                            title      = Parameter.Title,
                            password   = Parameter.inPasswordMail,
                            mm_app_url = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                            medios_connect_logo_url = imageUrl
                        }, "{{", "}}");

                        //string mailFrom = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                        string mailFrom = WebConfigurationManager.AppSettings["mailFrom"];
                        EmailNotificationSenderUtil.SendEmail(mailFrom, emailTo, subjectMail, email_template);
                    }
                    catch (Exception ex)
                    {
                        LogUtils.Logger.LogDocAppInfo(new LogUtils.LogEntry(System.Reflection.MethodInfo.GetCurrentMethod(), ex, null, "Add new user: Email sending failed."), "EmailExceptions");
                    }
                    var userAccountInfo = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                    {
                        IsDeleted     = false,
                        Tenant_RefID  = securityTicket.TenantID,
                        USR_AccountID = accId
                    }).Single();


                    var businesParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_BPT_BusinessParticipantID = userAccountInfo.BusinessParticipant_RefID
                    }).SingleOrDefault();
                    if (businesParticipant != null)
                    {
                        businesParticipant.DisplayName = Parameter.FirstName + " " + Parameter.LastName;
                        businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                        businesParticipant.IsNaturalPerson        = true;
                        businesParticipant.Modification_Timestamp = DateTime.Now;
                        businesParticipant.Save(Connection, Transaction);

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

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

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

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

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

                        var accountAppSettings = new ORM_USR_Account_ApplicationSetting();
                        accountAppSettings.IsDeleted          = false;
                        accountAppSettings.Account_RefID      = accId;
                        accountAppSettings.Creation_Timestamp = DateTime.Now;
                        accountAppSettings.Tenant_RefID       = securityTicket.TenantID;
                        accountAppSettings.ItemValue          = Parameter.ReceiveNotification.ToString();
                        accountAppSettings.ApplicationSetting_Definition_RefID = Guid.NewGuid();
                        accountAppSettings.Save(Connection, Transaction);

                        var accountAppSettingsDefinitions = new ORM_USR_Account_ApplicationSetting_Definition();
                        accountAppSettingsDefinitions.IsDeleted          = false;
                        accountAppSettingsDefinitions.Tenant_RefID       = securityTicket.TenantID;
                        accountAppSettingsDefinitions.Creation_Timestamp = DateTime.Now;
                        accountAppSettingsDefinitions.USR_Account_ApplicationSetting_DefinitionID = accountAppSettings.ApplicationSetting_Definition_RefID;
                        accountAppSettingsDefinitions.ItemKey = "ReceiveNotification";
                        accountAppSettingsDefinitions.Save(Connection, Transaction);
                    }
                }
            }
            else
            { //Edit existing user
                accId = Parameter.UserID;
                var userAccountInfo = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                {
                    IsDeleted     = false,
                    Tenant_RefID  = securityTicket.TenantID,
                    USR_AccountID = Parameter.UserID
                }).Single();

                var businesParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    CMN_BPT_BusinessParticipantID = userAccountInfo.BusinessParticipant_RefID
                }).SingleOrDefault();
                if (businesParticipant != null)
                {
                    businesParticipant.DisplayName            = Parameter.FirstName + " " + Parameter.LastName;
                    businesParticipant.Modification_Timestamp = DateTime.Now;
                    businesParticipant.Save(Connection, Transaction);

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query()
                    {
                        IsDeleted            = false,
                        Tenant_RefID         = securityTicket.TenantID,
                        CMN_PER_PersonInfoID = businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID
                    }).SingleOrDefault();
                    if (personInfo != null)
                    {
                        personInfo.FirstName          = Parameter.FirstName;
                        personInfo.LastName           = Parameter.LastName;
                        personInfo.Salutation_General = Parameter.Salutation;
                        personInfo.Title = Parameter.Title;
                        personInfo.Save(Connection, Transaction);


                        var phone = cls_Get_Communication_Contact_Info_for_User_Person_Info.Invoke(Connection, Transaction, new P_MD_GCCIFUPID_1716()
                        {
                            CommunicationType = "Phone", PersonRefID = personInfo.CMN_PER_PersonInfoID
                        }, securityTicket).Result;
                        if (phone != null)
                        {
                            var communicationContact = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, new ORM_CMN_PER_CommunicationContact.Query()
                            {
                                IsDeleted        = false,
                                Tenant_RefID     = securityTicket.TenantID,
                                PersonInfo_RefID = businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID,
                                CMN_PER_CommunicationContactID = phone.CMN_PER_CommunicationContactID
                            }).SingleOrDefault();
                            communicationContact.Content = Parameter.Phone;
                            communicationContact.Save(Connection, Transaction);
                        }
                        else
                        {
                            var communicationContactPhone = new ORM_CMN_PER_CommunicationContact();
                            communicationContactPhone.IsDeleted              = false;
                            communicationContactPhone.Contact_Type           = Guid.NewGuid();
                            communicationContactPhone.Tenant_RefID           = securityTicket.TenantID;
                            communicationContactPhone.Modification_Timestamp = DateTime.Now;
                            communicationContactPhone.PersonInfo_RefID       = businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                            communicationContactPhone.Content = Parameter.Phone;
                            communicationContactPhone.Save(Connection, Transaction);

                            var communicationContactTypePhone = new ORM_CMN_PER_CommunicationContact_Type();
                            communicationContactTypePhone.IsDeleted    = false;
                            communicationContactTypePhone.Tenant_RefID = securityTicket.TenantID;
                            communicationContactTypePhone.CMN_PER_CommunicationContact_TypeID = communicationContactPhone.Contact_Type;
                            communicationContactTypePhone.Type = "Phone";
                            communicationContactTypePhone.Save(Connection, Transaction);
                        }


                        var email = cls_Get_Communication_Contact_Info_for_User_Person_Info.Invoke(Connection, Transaction, new P_MD_GCCIFUPID_1716()
                        {
                            CommunicationType = "Email", PersonRefID = personInfo.CMN_PER_PersonInfoID
                        }, securityTicket).Result;
                        if (email != null)
                        {
                            var communicationContact = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, new ORM_CMN_PER_CommunicationContact.Query()
                            {
                                IsDeleted        = false,
                                Tenant_RefID     = securityTicket.TenantID,
                                PersonInfo_RefID = businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID,
                                CMN_PER_CommunicationContactID = email.CMN_PER_CommunicationContactID
                            }).SingleOrDefault();
                            communicationContact.Content = Parameter.Email;
                            communicationContact.Save(Connection, Transaction);
                        }
                        else
                        {
                            var communicationContactPhone = new ORM_CMN_PER_CommunicationContact();
                            communicationContactPhone.IsDeleted              = false;
                            communicationContactPhone.Contact_Type           = Guid.NewGuid();
                            communicationContactPhone.Tenant_RefID           = securityTicket.TenantID;
                            communicationContactPhone.Modification_Timestamp = DateTime.Now;
                            communicationContactPhone.PersonInfo_RefID       = businesParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                            communicationContactPhone.Content = Parameter.Email;
                            communicationContactPhone.Save(Connection, Transaction);

                            var communicationContactTypePhone = new ORM_CMN_PER_CommunicationContact_Type();
                            communicationContactTypePhone.IsDeleted    = false;
                            communicationContactTypePhone.Tenant_RefID = securityTicket.TenantID;
                            communicationContactTypePhone.CMN_PER_CommunicationContact_TypeID = communicationContactPhone.Contact_Type;
                            communicationContactTypePhone.Type = "Email";
                            communicationContactTypePhone.Save(Connection, Transaction);
                        }
                    }

                    var appSettings = ORM_USR_Account_ApplicationSetting.Query.Search(Connection, Transaction, new ORM_USR_Account_ApplicationSetting.Query()
                    {
                        IsDeleted     = false,
                        Tenant_RefID  = securityTicket.TenantID,
                        Account_RefID = accId
                    }).SingleOrDefault();

                    if (appSettings == null)
                    {
                        var accountAppSettings = new ORM_USR_Account_ApplicationSetting();
                        accountAppSettings.IsDeleted          = false;
                        accountAppSettings.Account_RefID      = accId;
                        accountAppSettings.Creation_Timestamp = DateTime.Now;
                        accountAppSettings.Tenant_RefID       = securityTicket.TenantID;
                        accountAppSettings.ItemValue          = Parameter.ReceiveNotification.ToString();
                        accountAppSettings.ApplicationSetting_Definition_RefID = Guid.NewGuid();
                        accountAppSettings.Save(Connection, Transaction);

                        var accountAppSettingsDefinitions = new ORM_USR_Account_ApplicationSetting_Definition();
                        accountAppSettingsDefinitions.IsDeleted          = false;
                        accountAppSettingsDefinitions.Tenant_RefID       = securityTicket.TenantID;
                        accountAppSettingsDefinitions.Creation_Timestamp = DateTime.Now;
                        accountAppSettingsDefinitions.USR_Account_ApplicationSetting_DefinitionID = accountAppSettings.ApplicationSetting_Definition_RefID;
                        accountAppSettingsDefinitions.ItemKey = "ReceiveNotification";
                        accountAppSettingsDefinitions.Save(Connection, Transaction);
                    }
                    else
                    {
                        appSettings.ItemValue = Parameter.ReceiveNotification.ToString();
                        appSettings.Save(Connection, Transaction);
                    }

                    var accountStatus = accountService.GetAccountStatusHistory(securityTicket.TenantID, Parameter.UserID).OrderBy(sth => sth.CreationTimestamp).Reverse().FirstOrDefault();
                    if (Parameter.isDeactivated == true)
                    {
                        if (accountStatus.Status != EAccountStatus.BANNED)
                        {
                            accountService.BanAccount(Parameter.UserID, "Konto wurde vom Administrator deaktiviert");
                        }
                    }
                    else
                    {
                        if (accountStatus.Status == EAccountStatus.BANNED)
                        {
                            accountService.UnbanAccount(Parameter.UserID);
                        }
                    }
                }
            }
            P_MD_SPtMU_1433 PSaveUserPermisions = new P_MD_SPtMU_1433();
            PSaveUserPermisions.AccountID = accId;
            PSaveUserPermisions.Role      = Parameter.isAdmin ? Properties.Settings.Default.MasterAccountMMApp : Properties.Settings.Default.RegularAccountMMApp;
            PSaveUserPermisions.GroupName = Properties.Settings.Default.MMAppGroup;
            cls_Save_Permisions_to_User.Invoke(Connection, Transaction, PSaveUserPermisions, securityTicket);
            return(returnValue);

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

            #region EMAIL
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");

            string        urlMM        = System.Configuration.ConfigurationManager.AppSettings["mmdocconnect.dashboard.url"];
            List <String> 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);
            }

            string 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/NewTemporaryDoctorEmailTemplate.html"));
            var     subjectsJson   = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailSubjects.json"));
            dynamic subjects       = Newtonsoft.Json.JsonConvert.DeserializeObject(subjectsJson);
            var     subjectMail    = subjects["NewTemporaryDoctorSubject"].ToString();

            email_template = EmailTemplater.SetTemplateData(email_template, new
            {
                name                    = Parameter.name,
                street                  = String.IsNullOrEmpty(Parameter.street) ? "-" : Parameter.street,
                house_number            = String.IsNullOrEmpty(Parameter.house_number) ? "-" : Parameter.house_number,
                zip                     = String.IsNullOrEmpty(Parameter.zip) ? "-" : Parameter.zip,
                city                    = String.IsNullOrEmpty(Parameter.city) ? "-" : Parameter.city,
                phone                   = String.IsNullOrEmpty(Parameter.phone) ? "-" : Parameter.phone,
                fax                     = String.IsNullOrEmpty(Parameter.fax) ? "-" : Parameter.fax,
                email                   = String.IsNullOrEmpty(Parameter.email) ? "-" : Parameter.email,
                comment                 = String.IsNullOrEmpty(Parameter.comment) ? "-" : Parameter.comment,
                doc_app_url             = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                medios_connect_logo_url = imageUrl
            }, "{{", "}}");

            try
            {
                // string mailFrom = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                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, "Temporary doctor creation: Email sending failed."), "EmailExceptions");
            }
            #endregion

            #region PERSON INFO
            ORM_CMN_PER_PersonInfo temporary_doctor_person_info = new ORM_CMN_PER_PersonInfo();
            temporary_doctor_person_info.LastName = Parameter.name;
            temporary_doctor_person_info.Modification_Timestamp = DateTime.Now;
            temporary_doctor_person_info.Tenant_RefID           = securityTicket.TenantID;

            temporary_doctor_person_info.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact_Type temporary_doctor_communication_contact_type_email = new ORM_CMN_PER_CommunicationContact_Type();
            temporary_doctor_communication_contact_type_email.Tenant_RefID = securityTicket.TenantID;
            temporary_doctor_communication_contact_type_email.Type         = "Email";

            temporary_doctor_communication_contact_type_email.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact temporary_doctor_communication_contact_email = new ORM_CMN_PER_CommunicationContact();
            temporary_doctor_communication_contact_email.Tenant_RefID           = securityTicket.TenantID;
            temporary_doctor_communication_contact_email.Modification_Timestamp = DateTime.Now;
            temporary_doctor_communication_contact_email.PersonInfo_RefID       = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_communication_contact_email.Content      = Parameter.email;
            temporary_doctor_communication_contact_email.Contact_Type = temporary_doctor_communication_contact_type_email.CMN_PER_CommunicationContact_TypeID;

            temporary_doctor_communication_contact_email.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact_Type temporary_doctor_communication_contact_type_phone = new ORM_CMN_PER_CommunicationContact_Type();
            temporary_doctor_communication_contact_type_phone.Tenant_RefID = securityTicket.TenantID;
            temporary_doctor_communication_contact_type_phone.Type         = "Phone";

            temporary_doctor_communication_contact_type_phone.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact temporary_doctor_communication_contact_phone = new ORM_CMN_PER_CommunicationContact();
            temporary_doctor_communication_contact_phone.Tenant_RefID           = securityTicket.TenantID;
            temporary_doctor_communication_contact_phone.Modification_Timestamp = DateTime.Now;
            temporary_doctor_communication_contact_phone.PersonInfo_RefID       = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_communication_contact_phone.Content      = Parameter.phone;
            temporary_doctor_communication_contact_phone.Contact_Type = temporary_doctor_communication_contact_type_phone.CMN_PER_CommunicationContact_TypeID;

            temporary_doctor_communication_contact_phone.Save(Connection, Transaction);
            #endregion

            #region BPT
            ORM_CMN_BPT_BusinessParticipant temporary_doctor_bpt = new ORM_CMN_BPT_BusinessParticipant();
            temporary_doctor_bpt.IfNaturalPerson_CMN_PER_PersonInfo_RefID = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_bpt.IsNaturalPerson        = true;
            temporary_doctor_bpt.Modification_Timestamp = DateTime.Now;
            temporary_doctor_bpt.Tenant_RefID           = securityTicket.TenantID;

            temporary_doctor_bpt.Save(Connection, Transaction);
            #endregion

            #region DOCTOR
            ORM_HEC_Doctor temporary_doctor = new ORM_HEC_Doctor();
            // account ref. id = guid empty means that this is a temporary doctor with no account
            temporary_doctor.Account_RefID                     = Guid.Empty;
            temporary_doctor.BusinessParticipant_RefID         = temporary_doctor_bpt.CMN_BPT_BusinessParticipantID;
            temporary_doctor.DoctorIDNumber                    = "";
            temporary_doctor.IsDoctorForFollowupTreatmentsOnly = true;
            temporary_doctor.Tenant_RefID = securityTicket.TenantID;

            temporary_doctor.Save(Connection, Transaction);

            ORM_HEC_Doctor_UniversalProperty temporary_doctor_universal_property = new ORM_HEC_Doctor_UniversalProperty();
            temporary_doctor_universal_property.GlobalPropertyMatchingID = "mm.docconnect.temporary.aftercare.doctor.comment";
            temporary_doctor_universal_property.IsValue_String           = true;
            temporary_doctor_universal_property.Modification_Timestamp   = DateTime.Now;
            temporary_doctor_universal_property.PropertyName             = "Comment";
            temporary_doctor_universal_property.Tenant_RefID             = securityTicket.TenantID;

            temporary_doctor_universal_property.Save(Connection, Transaction);

            ORM_HEC_Doctor_UniversalPropertyValue temporary_doctor_universal_property_value = new ORM_HEC_Doctor_UniversalPropertyValue();
            temporary_doctor_universal_property_value.HEC_Doctor_RefID        = temporary_doctor.HEC_DoctorID;
            temporary_doctor_universal_property_value.Modification_Timestamp  = DateTime.Now;
            temporary_doctor_universal_property_value.Value_String            = Parameter.comment;
            temporary_doctor_universal_property_value.UniversalProperty_RefID = temporary_doctor_universal_property.HEC_Doctor_UniversalPropertyID;
            temporary_doctor_universal_property_value.Tenant_RefID            = securityTicket.TenantID;

            temporary_doctor_universal_property_value.Save(Connection, Transaction);
            #endregion

            #region IMPORT TO ELASTIC

            Practice_Doctors_Model temporary_doctor_elastic_model = new Practice_Doctors_Model();
            temporary_doctor_elastic_model.autocomplete_name = Parameter.name;
            temporary_doctor_elastic_model.name                   = Parameter.name;
            temporary_doctor_elastic_model.name_untouched         = Parameter.name;
            temporary_doctor_elastic_model.address                = Parameter.street + " " + Parameter.house_number;
            temporary_doctor_elastic_model.zip                    = Parameter.zip;
            temporary_doctor_elastic_model.city                   = Parameter.city;
            temporary_doctor_elastic_model.email                  = Parameter.email;
            temporary_doctor_elastic_model.phone                  = Parameter.phone;
            temporary_doctor_elastic_model.account_status         = "temp";
            temporary_doctor_elastic_model.id                     = temporary_doctor.HEC_DoctorID.ToString();
            temporary_doctor_elastic_model.practice_for_doctor_id = Parameter.practice_id.ToString();
            temporary_doctor_elastic_model.tenantid               = securityTicket.TenantID.ToString();
            temporary_doctor_elastic_model.type                   = "Doctor";

            Add_New_Practice.Import_Practice_Data_to_ElasticDB(new List <Practice_Doctors_Model>()
            {
                temporary_doctor_elastic_model
            }, securityTicket.TenantID.ToString());
            #endregion

            returnValue.Result = temporary_doctor.HEC_DoctorID;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #6
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_MD_CAP_1503 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here

            IAccountServiceProvider accountService;
            var _providerFactory = ProviderFactory.Instance;
            accountService = _providerFactory.CreateAccountServiceProvider();
            List <String> MailToL     = new List <String>();
            Guid          accountId   = Guid.NewGuid();
            String        accountMail = "";
            String        displayName = "";
            if (Parameter.Type == "Arzt")
            {
                var account = cls_Get_Doctor_AccountID_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDAIDfDID_1549()
                {
                    DoctorID = Parameter.PassID
                }, securityTicket).Result;
                accountId   = account.accountID;
                accountMail = account.accountMail;
                MailToL.Add(accountMail);
                displayName = account.DisplayName;
                var doctorDetails = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = Parameter.PassID
                }, securityTicket).Result.Single();
                string maildoc = null;
                if (doctorDetails.DoctorComunication.Where(k => k.Type == "Email").SingleOrDefault() != null)
                {
                    maildoc = doctorDetails.DoctorComunication.Where(k => k.Type == "Email").Single().Content;
                }

                if (maildoc != null && maildoc != accountMail)
                {
                    MailToL.Add(maildoc);
                }
            }
            else if (Parameter.Type == "Praxis")
            {
                var account = cls_Get_Practice_AccountID_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPAIDfPID_1351()
                {
                    PracticeID = Parameter.PassID
                }, securityTicket).Result;
                accountId   = account.accountID;
                accountMail = account.accountMail;
                MailToL.Add(accountMail);
                displayName = account.DisplayName;
                var practiceDetails = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
                {
                    PracticeID = Parameter.PassID
                }, securityTicket).Result;
                string mailPractice = practiceDetails.FirstOrDefault().contact_email;
                if (mailPractice != null && mailPractice != accountMail)
                {
                    MailToL.Add(mailPractice);
                }
            }
            else if (Parameter.Type == "Mitarbeiter")
            {
                var account = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                {
                    IsDeleted     = false,
                    Tenant_RefID  = securityTicket.TenantID,
                    USR_AccountID = Parameter.PassID
                }).Single();
                accountId   = account.USR_AccountID;
                accountMail = account.AccountSignInEmailAddress;
                MailToL.Add(accountMail);
                displayName = account.Username;
                var User = cls_Get_Account_Information_for_AccountID.Invoke(Connection, Transaction, new P_MD_GAIfAID_1436()
                {
                    UserAccountID = Parameter.PassID
                }, securityTicket).Result;
                string userMail = User.Contact.Length != 0 ? User.Contact.Where(usr => usr.Type == "Email").SingleOrDefault() != null?User.Contact.Where(usr => usr.Type == "Email").SingleOrDefault().Content : null : null;

                if (userMail != null && userMail != accountMail)
                {
                    MailToL.Add(userMail);
                }
            }

            BOp.Providers.TMS.Requests.ResetPasswordRequest request = new BOp.Providers.TMS.Requests.ResetPasswordRequest();
            request.AccountID    = accountId;
            request.NewPassword  = Parameter.Password;
            request.SessionToken = securityTicket.SessionTicket;
            accountService.ResetPassword(request);

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

            string 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/PasswordChangedEmailTemplate.html"));

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

            email_template = EmailTemplater.SetTemplateData(email_template, new
            {
                name                    = displayName,
                password                = Parameter.Password,
                mmapp_dashboard_url     = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                medios_connect_logo_url = imageUrl
            }, "{{", "}}");

            try
            {
                string mailFrom      = WebConfigurationManager.AppSettings["mailFrom"];
                var    mailsDistinct = MailToL.Distinct().ToList();
                foreach (var mailTo in mailsDistinct)
                {
                    if (!String.IsNullOrEmpty(mailTo))
                    {
                        EmailNotificationSenderUtil.SendEmail(mailFrom, mailTo, subjectMail, email_template);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtils.Logger.LogDocAppInfo(new LogUtils.LogEntry(System.Reflection.MethodInfo.GetCurrentMethod(), ex, null, "Change account password: Email sending failed."), "EmailExceptions");
            }
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_DO_CP_1724 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            var _providerFactory = ProviderFactory.Instance;
            IAccountServiceProvider accountService = _providerFactory.CreateAccountServiceProvider();
            List <String>           MailToL        = new List <String>();
            string mailToFromCompanySettings       = "";
            var    accountId   = Guid.Empty;
            var    accountMail = "";
            var    displayName = "";

            if (Parameter.type == "Arzt")
            {
                var account = cls_Get_Doctor_AccountID_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDAIDfDID_1549()
                {
                    DoctorID = Parameter.ID
                }, securityTicket).Result;
                accountId   = account.accountID;
                accountMail = account.accountMail;
                MailToL.Add(accountMail);
                displayName = account.DisplayName;
                var doctorDetails = cls_Get_Doctor_Details_for_DoctorID.Invoke(Connection, Transaction, new P_DO_GDDfDID_0823()
                {
                    DoctorID = Parameter.ID
                }, securityTicket).Result.Single();
                string maildoc = null;
                if (doctorDetails.DoctorComunication.Where(k => k.Type == "Email").SingleOrDefault() != null)
                {
                    maildoc = doctorDetails.DoctorComunication.Where(k => k.Type == "Email").Single().Content;
                }

                if (maildoc != null && maildoc != accountMail)
                {
                    MailToL.Add(maildoc);
                }
                mailToFromCompanySettings = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                MailToL.Add(mailToFromCompanySettings);
            }
            else if (Parameter.type == "Praxis")
            {
                var account = cls_Get_Practice_AccountID_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPAIDfPID_1351()
                {
                    PracticeID = Parameter.ID
                }, securityTicket).Result;
                accountId   = account.accountID;
                accountMail = account.accountMail;
                MailToL.Add(accountMail);
                displayName = account.DisplayName;
                var practiceDetails = cls_Get_Practice_Details_for_PracticeID.Invoke(Connection, Transaction, new P_DO_GPDfPID_1432()
                {
                    PracticeID = Parameter.ID
                }, securityTicket).Result;
                string mailPractice = practiceDetails.FirstOrDefault().contact_email;
                if (mailPractice != null && mailPractice != accountMail)
                {
                    MailToL.Add(mailPractice);
                }
                mailToFromCompanySettings = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                MailToL.Add(mailToFromCompanySettings);
            }


            BOp.Providers.TMS.Requests.ResetPasswordRequest request = new BOp.Providers.TMS.Requests.ResetPasswordRequest();
            request.AccountID    = accountId;
            request.NewPassword  = Parameter.password;
            request.SessionToken = securityTicket.SessionTicket;
            accountService.ResetPassword(request);

            string 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/PasswordChangedEmailTemplate.html"));

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

            email_template = EmailTemplater.SetTemplateData(email_template, new
            {
                name                    = displayName,
                password                = Parameter.password,
                mmapp_dashboard_url     = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                medios_connect_logo_url = imageUrl
            }, "{{", "}}");

            try
            {
                // string mailFrom = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                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, "Change password (doc app): Email sending failed."), "EmailExceptions");
            }
            return(returnValue);

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