Exemple #1
0
    protected void SetNotificationInfo()
    {
        chkEnableEmails.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendEmail").Value) == 1;
        txtEmailAddress.Text    = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_EmailAddress").Value;

        chkIncClinicsAuto.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncClinic").Value) == 1;
        chkIncAgedCareAuto.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncAgedCare").Value) == 1;

        chkIncUnsentAuto.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncUnsent").Value) == 1;
        chkIncBatchedAuto.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncBatched").Value) == 1;

        rdioSendTypeAuto.SelectedValue = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMethod").Value;

        chkSendMondays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMondays").Value) == 1;
        chkSendTuesdays.Checked   = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendTuesdays").Value) == 1;
        chkSendWednesdays.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendWednesdays").Value) == 1;
        chkSendThursdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendThursdays").Value) == 1;
        chkSendFridays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendFridays").Value) == 1;
        chkSendSaturdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSaturdays").Value) == 1;
        chkSendSundays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSundays").Value) == 1;


        btnUpdateNotificationInfo.CssClass = "hiddencol";
        btnRevertNotificationInfo.CssClass = "hiddencol";
    }
Exemple #2
0
    protected void btnTesty_Click(object sender, EventArgs e)
    {
        decimal cost = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

        SMSHistoryDataDB.Insert(1, -1, 62000, "61-nbr...", "msg", cost, txtMsgId.Text);
        UpdateDB();
    }
Exemple #3
0
    public static EPCInfo GetEPCInfo(int patient_id)
    {
        int MedicareMaxNbrServicesPerYear        = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);
        int NbrMedicareServicesUsedSoFarThisYear = (int)InvoiceDB.GetMedicareCountByPatientAndYear(patient_id, DateTime.Now.Year);

        return(new EPCInfo(MedicareMaxNbrServicesPerYear, NbrMedicareServicesUsedSoFarThisYear));
    }
Exemple #4
0
    protected void SetNotificationInfo()
    {
        chkEnableEmails.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendEmail").Value) == 1;
        txtEmailAddress.Text    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_EmailAddress").Value;

        chkIncPatientsWithMobile.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_IncPatientsWithMobile").Value) == 1;
        chkIncPatientsWithEmail.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_IncPatientsWithEmail").Value) == 1;

        chkSendMondays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendMondays").Value) == 1;
        chkSendTuesdays.Checked   = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendTuesdays").Value) == 1;
        chkSendWednesdays.Checked = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendWednesdays").Value) == 1;
        chkSendThursdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendThursdays").Value) == 1;
        chkSendFridays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFridays").Value) == 1;
        chkSendSaturdays.Checked  = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendSaturdays").Value) == 1;
        chkSendSundays.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendSundays").Value) == 1;

        ddlFromDaysAheadMondays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Mondays").Value;
        ddlUntilDaysAheadMondays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Mondays").Value;
        ddlFromDaysAheadTuesdays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Tuesdays").Value;
        ddlUntilDaysAheadTuesdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Tuesdays").Value;
        ddlFromDaysAheadWednesdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Wednesdays").Value;
        ddlUntilDaysAheadWednesdays.SelectedValue = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Wednesdays").Value;
        ddlFromDaysAheadThursdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Thursdays").Value;
        ddlUntilDaysAheadThursdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Thursdays").Value;
        ddlFromDaysAheadFridays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Fridays").Value;
        ddlUntilDaysAheadFridays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Fridays").Value;
        ddlFromDaysAheadSaturdays.SelectedValue   = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Saturdays").Value;
        ddlUntilDaysAheadSaturdays.SelectedValue  = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Saturdays").Value;
        ddlFromDaysAheadSundays.SelectedValue     = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendFromDaysAhead_Sundays").Value;
        ddlUntilDaysAheadSundays.SelectedValue    = SystemVariableDB.GetByDescr("BirthdayNotificationEmail_SendUntilDaysAhead_Sundays").Value;

        btnUpdateNotificationInfo.CssClass = "hiddencol";
        btnRevertNotificationInfo.CssClass = "hiddencol";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                Utilities.SetNoCache(Response);
            }
            HideErrorMessage();
            Utilities.UpdatePageHeaderV2(Page.Master, true);

            if (!IsPostBack)
            {
                Session.Remove("suburb_sortExpression");
                Session.Remove("suburb_data");


                ddlState.Items.Add(new ListItem("All", "All"));
                DataTable states = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Suburb", "", "state", "distinct state");
                foreach (DataRow row in states.Rows)
                {
                    ddlState.Items.Add(new ListItem(row["state"].ToString(), row["state"].ToString()));
                }

                SystemVariable sysVariable = SystemVariableDB.GetByDescr("DefaultState");
                if (sysVariable != null && sysVariable.Value.Trim() != "")
                {
                    ddlState.SelectedValue = sysVariable.Value.Trim();
                }

                FillSuburbGrid();
            }

            this.GrdSuburb.EnableViewState = true;
        }
        catch (CustomMessageException ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage(ex.Message);
            }
            else
            {
                HideTableAndSetErrorMessage(ex.Message);
            }
        }
        catch (Exception ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage("", ex.ToString());
            }
            else
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
    }
Exemple #6
0
 protected void SetNotificationInfo()
 {
     txtSMSCreditNotificationEmailAddress.Text     = SystemVariableDB.GetByDescr("SMSCreditNotificationEmailAddress").Value;
     txtSMSCreditLowBalance_Threshold.Text         = SystemVariableDB.GetByDescr("SMSCreditLowBalance_Threshold").Value;
     chkSMSCreditOutOfBalance_SendEmail.Checked    = Convert.ToInt32(SystemVariableDB.GetByDescr("SMSCreditOutOfBalance_SendEmail").Value) == 1;
     chkSMSCreditLowBalance_SendEmail.Checked      = Convert.ToInt32(SystemVariableDB.GetByDescr("SMSCreditLowBalance_SendEmail").Value) == 1;
     btnUpdateNotificationInfo.Style["visibility"] = "hidden";
     btnRevertNotificationInfo.Style["visibility"] = "hidden";
 }
Exemple #7
0
    protected void Run(bool incDisplay, bool incSending)
    {
        // 1. get all fields from systemvariables

        int DaysBeforePaymentDueToSendReminder = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DaysBeforePaymentDueToSendReminder"]);
        int PaymentDueDayOfMonth = Convert.ToInt32(SystemVariableDB.GetByDescr("PaymentDueDayOfMonth").Value);

        string CustomerEmail = SystemVariableDB.GetByDescr("AdminAlertEmail_To").Value;
        string DB            = System.Web.HttpContext.Current.Session["DB"].ToString();

        /*
         * // log for debugging
         * Hashtable logFile = new Hashtable();
         * logFile["SMSSender_Scheduled_LogFile_Eli-PC"]     = @"C:\Users\Eli\Documents\Mediclinic\SMSSender_Scheduled_LogFile2.txt";
         * logFile["SMSSender_Scheduled_LogFile_ELI-LAPTOP"] = @"D:\Dropbox\Mediclinic\SMSSender_Scheduled_LogFile2.txt";
         *      logFile["SMSSender_Scheduled_LogFile_box001"]     = @"C:\inetpub\sites\MediclinicDocs\SMSSender_Scheduled_LogFile2.txt";
         * Logger.WriteToFile(
         *  ((DateTime.Today.Date != GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today)) ? "Not Sent -- " : "Sent -- ") +
         *  @"DB = " + DB + " Today = " + DateTime.Today.ToString("dd-MM") + " SendDate = " + GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today).ToString("dd-MM") + Environment.NewLine,
         *  logFile["SMSSender_Scheduled_LogFile_" + Environment.MachineName].ToString());
         */


        // 2. validate

        if (DateTime.Today.Date != GetDueDateThisMonth(PaymentDueDayOfMonth, DaysBeforePaymentDueToSendReminder, DateTime.Today))
        {
            return;
        }


        // 3. run it -- send reminder email to marcus

        string emailBody = @"
Mediclinic payment due date is coming up for :
<br />
<br />
<table>
    <tr><td>Customer Email</td><td>" + CustomerEmail + @"</td></tr>
    <tr><td>Due Day Of Month</td><td>" + Utilities.GetDateOrdinal(PaymentDueDayOfMonth) + @"</td></tr>
    <tr><td>Database</td><td>" + DB + @"</td></tr>
</table>";

        Emailer.AsyncSimpleEmail(
            System.Configuration.ConfigurationManager.AppSettings["ErrorEmail_FromEmail"],
            System.Configuration.ConfigurationManager.AppSettings["ErrorEmail_FromName"],
            System.Configuration.ConfigurationManager.AppSettings["TopupEmail_To"],
            "Mediclinic Customer Payment Due",
            emailBody,
            true,
            null);
    }
Exemple #8
0
    public static void UpdateAndCheckWarning(int organisation_id, int offering_id, int qtyUsed)
    {
        Organisation org      = OrganisationDB.GetByID(organisation_id);
        Offering     offering = OfferingDB.GetByID(offering_id);

        Stock[] stockList    = StockDB.GetByOrg(org.OrganisationID);
        string  warningEmail = SystemVariableDB.GetByDescr("StockWarningNotificationEmailAddress").Value;

        for (int i = 0; i < stockList.Length; i++)
        {
            if (offering.OfferingID == stockList[i].Offering.OfferingID && stockList[i].Quantity >= 0)
            {
                int prevQty = stockList[i].Quantity;
                int postQty = stockList[i].Quantity - qtyUsed;
                if (postQty < 0)
                {
                    postQty = 0;
                }

                if (warningEmail.Length > 0 && stockList[i].WarningAmount >= 0 && qtyUsed > 0 && stockList[i].WarningAmount < prevQty && stockList[i].WarningAmount >= postQty)
                {
                    try
                    {
                        Emailer.SimpleEmail(
                            warningEmail,
                            "Stock Warning Level Reached For " + stockList[i].Offering.Name + " at " + org.Name,
                            "This is an automated email to notify you that the stock warning level of <b>" + stockList[i].WarningAmount + "</b> items that was set for <b>" + stockList[i].Offering.Name + "</b> at <b>" + org.Name + "</b> has been reached and you may need to re-stock.<br /><br />Best regards,<br />Mediclinic",
                            true,
                            null,
                            null
                            );
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex, true);
                    }
                }

                StockDB.UpdateQuantity(stockList[i].StockID, postQty);
            }
        }
    }
    protected void SetMaxNbrProvidersTextBox(bool editable)
    {
        int maxNbrProviders = Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value);

        txtMaxNbrProviders.Text      = maxNbrProviders.ToString();
        txtMaxNbrProviders.ReadOnly  = !editable;
        txtMaxNbrProviders.Enabled   = editable;
        txtMaxNbrProviders.ForeColor = System.Drawing.Color.Black;

        btnMaxNbrProvidersSetEditMode.Visible    = !editable;
        btnMaxNbrProvidersCancelEditMode.Visible = editable;
        btnMaxNbrProvidersUpdate.Visible         = editable;
        Utilities.SetEditControlBackColour(txtMaxNbrProviders, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Transparent, editable);

        if (editable)
        {
            // set cursor at "end" of the text
            string jsSetCursorEnd = @"var b98 = document.getElementById('" + txtMaxNbrProviders.ID.ToString() + @"'); b98.focus(); var val = b98.value; b98.value = ''; b98.value = val;";
            ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), Page.ClientID, jsSetCursorEnd, true);
        }
    }
Exemple #10
0
    protected void SetSMSPriceTextBox(bool editable)
    {
        decimal smsPrice = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

        sms_credit_div.Style["width"] = editable ? "575px" : "350px";

        txtSMSPrice.Text      = smsPrice.ToString("0.00");
        txtSMSPrice.ReadOnly  = !editable;
        txtSMSPrice.Enabled   = editable;
        txtSMSPrice.ForeColor = System.Drawing.Color.Black;

        btnSMSPriceSetEditMode.Visible    = !editable;
        btnSMSPriceCancelEditMode.Visible = editable;
        btnSMSPriceUpdate.Visible         = editable;
        Utilities.SetEditControlBackColour(txtSMSPrice, editable, System.Drawing.Color.LightGoldenrodYellow, System.Drawing.Color.Transparent, editable);

        if (editable)
        {
            // set cursor at "end" of the text
            string jsSetCursorEnd = @"var b98 = document.getElementById('" + txtSMSPrice.ID.ToString() + @"'); b98.focus(); var val = b98.value; b98.value = ''; b98.value = val;";
            ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), Page.ClientID, jsSetCursorEnd, true);
        }
    }
Exemple #11
0
    protected void GrdStaff_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            CustomValidator txtValidateDOB = (CustomValidator)GrdStaff.FooterRow.FindControl("txtValidateNewDOB");
            if (!txtValidateDOB.IsValid)
            {
                return;
            }

            DropDownList ddlTitle      = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewTitle");
            TextBox      txtFirstname  = (TextBox)GrdStaff.FooterRow.FindControl("txtNewFirstname");
            TextBox      txtMiddlename = (TextBox)GrdStaff.FooterRow.FindControl("txtNewMiddlename");
            TextBox      txtSurname    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewSurname");
            DropDownList ddlGender     = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewGender");
            TextBox      txtDOB        = (TextBox)GrdStaff.FooterRow.FindControl("txtNewDOB");

            TextBox txtLogin = (TextBox)GrdStaff.FooterRow.FindControl("txtNewLogin");
            TextBox txtPwd   = (TextBox)GrdStaff.FooterRow.FindControl("txtNewPwd");


            //DropDownList ddlStaffPosition     = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewStaffPosition");
            DropDownList ddlField             = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewField");
            CheckBox     chkContractor        = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewContractor");
            TextBox      txtTFN               = (TextBox)GrdStaff.FooterRow.FindControl("txtNewTFN");
            DropDownList ddlStatus            = (DropDownList)GrdStaff.FooterRow.FindControl("ddlStatus");
            DropDownList ddlCostCentre        = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewCostCentre");
            TextBox      txtProviderNumber    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewProviderNumber");
            CheckBox     chkIsCommission      = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsCommission");
            TextBox      txtCommissionPercent = (TextBox)GrdStaff.FooterRow.FindControl("txtNewCommissionPercent");

            CheckBox chkIsStakeholder = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsStakeholder");
            CheckBox chkIsAdmin       = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsAdmin");
            CheckBox chkIsMasterAdmin = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsMasterAdmin");
            CheckBox chkIsPrincipal   = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsPrincipal");
            CheckBox chkIsProvider    = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsProvider");
            CheckBox chkSMSBKs        = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewSMSBKs");
            CheckBox chkEmailBKs      = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewEmailBKs");
            CheckBox chkHideBKNotes   = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewHideBKNotes");



            if (chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to add them. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }


            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            DateTime dob = GetDate(txtDOB.Text.Trim());

            int person_id    = -1;
            int mainDbUserID = -1;

            try
            {
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                if (chkIsMasterAdmin.Checked)
                {
                    chkIsAdmin.Checked = true;
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, dob);
                StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), Convert.ToInt32(ddlCostCentre.SelectedValue),
                               chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                               ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                               chkIsStakeholder.Checked, chkIsMasterAdmin.Checked, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, false,
                               DateTime.Today, DateTime.MinValue, "", chkSMSBKs.Checked, chkEmailBKs.Checked, chkHideBKNotes.Checked);

                FillGrid();
            }
            catch (Exception)
            {
                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }
            }
        }
    }
Exemple #12
0
    protected void GrdStaff_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId         = (Label)GrdStaff.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlTitle      = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlTitle");
        TextBox      txtFirstname  = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtFirstname");
        TextBox      txtMiddlename = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtMiddlename");
        TextBox      txtSurname    = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtSurname");
        DropDownList ddlGender     = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlGender");
        DropDownList ddlDOB_Day    = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Day");
        DropDownList ddlDOB_Month  = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Month");
        DropDownList ddlDOB_Year   = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Year");

        TextBox txtLogin = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtLogin");
        TextBox txtPwd   = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtPwd");
        //DropDownList ddlStaffPosition     = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlStaffPosition");
        DropDownList ddlField             = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlField");
        CheckBox     chkContractor        = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkContractor");
        TextBox      txtTFN               = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtTFN");
        DropDownList ddlStatus            = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlStatus");
        DropDownList ddlCostCentre        = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlCostCentre");
        TextBox      txtProviderNumber    = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtProviderNumber");
        CheckBox     chkIsCommission      = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsCommission");
        TextBox      txtCommissionPercent = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtCommissionPercent");
        CheckBox     chkIsStakeholder     = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsStakeholder");
        CheckBox     chkIsAdmin           = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsAdmin");
        CheckBox     chkIsMasterAdmin     = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsMasterAdmin");
        CheckBox     chkIsPrincipal       = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsPrincipal");
        CheckBox     chkIsProvider        = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsProvider");
        CheckBox     chkSMSBKs            = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkSMSBKs");
        CheckBox     chkEmailBKs          = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkEmailBKs");
        CheckBox     chkHideBKNotes       = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkHideBKNotes");



        int staff_id  = Convert.ToInt32(lblId.Text);
        int person_id = GetPersonID(Convert.ToInt32(lblId.Text));

        if (person_id == -1) // happens when back button hit after update .. with option to update again ... but no selected row exists within page data
        {
            GrdStaff.EditIndex = -1;
            FillGrid();
            return;
        }


        Staff staff = StaffDB.GetByID(staff_id);

        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
        {
            SetErrorMessage("Login name already in use by another user");
            return;
        }
        if (staff.Login != txtLogin.Text && StaffDB.LoginExists(txtLogin.Text, staff_id))
        {
            SetErrorMessage("Login name already in use by another user");
            return;
        }
        if (staff.Pwd != txtPwd.Text && txtPwd.Text.Length < 6)
        {
            SetErrorMessage(staff.Pwd.Length >= 6 ? "Password must be at least 6 characters" : "New passwords must be at least 6 characters");
            return;
        }

        DataTable dt = Session["staffinfo_data"] as DataTable;

        DataRow[] foundRows = dt.Select("person_id=" + person_id.ToString());
        DataRow   row       = foundRows[0]; // Convert.ToInt32(row["person_id"])



        if (!Convert.ToBoolean(row["is_provider"]) && chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
        {
            SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to update them or hit cancel. Contact Mediclinic if you would like to upgrade your account.");
            return;
        }


        if (chkIsProvider.Checked)
        {
            System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

            bool         roleSetAsProvider = false;
            IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                {
                    roleSetAsProvider = true;
                }
            }

            if (!roleSetAsProvider)
            {
                if (fields.Length == 1)
                {
                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                    return;
                }
                else if (fields.Length == 2)
                {
                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                    return;
                }
                else
                {
                    string providerFields = string.Empty;
                    for (int i = 0; i < fields.Length; i++)
                    {
                        providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                    }

                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                    return;
                }
            }
        }



        if (chkIsMasterAdmin.Checked)
        {
            chkIsAdmin.Checked = true;
        }

        PersonDB.Update(person_id, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), row["nickname"].ToString(), ddlGender.SelectedValue, GetDate(ddlDOB_Day.SelectedValue, ddlDOB_Month.SelectedValue, ddlDOB_Year.SelectedValue), DateTime.Now);
        StaffDB.Update(staff_id, person_id, txtLogin.Text, txtPwd.Text, Convert.ToInt32(row["staff_position_id"]), Convert.ToInt32(ddlField.SelectedValue), Convert.ToInt32(ddlCostCentre.SelectedValue),
                       chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                       ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                       chkIsStakeholder.Checked, chkIsMasterAdmin.Checked, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, staff.IsExternal,
                       row["start_date"] == DBNull.Value ? DateTime.MinValue : (DateTime)row["start_date"], row["end_date"] == DBNull.Value ? DateTime.MinValue : (DateTime)row["end_date"], row["comment"].ToString(), chkSMSBKs.Checked, chkEmailBKs.Checked, chkHideBKNotes.Checked);

        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text)
        {
            UserDatabaseMapper curDBMapper = UserDatabaseMapperDB.GetByLogin(staff.Login, Session["DB"].ToString());
            if (curDBMapper == null)
            {
                UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
            }
            else
            {
                UserDatabaseMapperDB.Update(curDBMapper.ID, txtLogin.Text, Session["DB"].ToString());
            }
        }


        GrdStaff.EditIndex = -1;
        FillGrid();
    }
 protected void SetNotificationInfo()
 {
     txtEmailAddress.Text = SystemVariableDB.GetByDescr("ServiceSpecificBookingReminderLettersToBatch_EmailAddress").Value;
     update_button_row.Attributes["class"] = "hiddencol";
 }
    protected void FillGrid()
    {
        DateTime fromDate = DateTime.MinValue; // IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text) : DateTime.MinValue;
        DateTime toDate   = IsValidDate(txtEndDate.Text)   ? GetDate(txtEndDate.Text)   : DateTime.MinValue;
        DateTime nNoRecallLettersAfterDate = IsValidDate(txtNoRecallLettersAfterDate.Text) ? GetDate(txtNoRecallLettersAfterDate.Text) : DateTime.MinValue;


        //DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, chkOnlyShowIfHasEPCs.Checked, Convert.ToInt32(ddlClinics.SelectedValue));
        DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, false, Convert.ToInt32(ddlClinics.SelectedValue));



        int[] patientIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            patientIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);
        }


        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(patientIDs);


        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(patientIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(patientIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        ArrayList remainingPatientIDs = new ArrayList();

        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;

            // remove if no valid epc and set to show only those with a valid EPC
            if (!chkShowWithEPC.Checked && has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (!chkShowWithNoEPC.Checked && !has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (nNoRecallLettersAfterDate != DateTime.MinValue && mostRecentRecallHashByPatientID[patientID] != null && ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date.Date > nNoRecallLettersAfterDate)
            {
                dt.Rows.RemoveAt(i);
            }
            else
            {
                remainingPatientIDs.Add(patientID);
            }
        }

        hiddenPatientIDs.Value = string.Join(",", (int[])remainingPatientIDs.ToArray(typeof(int)));

        Session["recallpatientinfo_data"] = dt;


        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["recallpatientinfo_sortexpression"] != null && Session["recallpatientinfo_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort         = Session["recallpatientinfo_sortexpression"].ToString();
                GrdPatient.DataSource = dataView;
            }
            else
            {
                GrdPatient.DataSource = dt;
            }


            try
            {
                GrdPatient.DataBind();
                GrdPatient.PagerSettings.FirstPageText = "1";
                GrdPatient.PagerSettings.LastPageText  = GrdPatient.PageCount.ToString();
                GrdPatient.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatient.DataSource = dt;
            GrdPatient.DataBind();

            int TotalColumns = GrdPatient.Rows[0].Cells.Count;
            GrdPatient.Rows[0].Cells.Clear();
            GrdPatient.Rows[0].Cells.Add(new TableCell());
            GrdPatient.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdPatient.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
Exemple #15
0
    public static string Run(bool incDisplay, bool incSending, bool incPtSending, DateTime date)
    {
        date = date.Date;

        string batchEmail = SystemVariableDB.GetByDescr("ServiceSpecificBookingReminderLettersToBatch_EmailAddress").Value;

        // don't actually run it if email empty (ie deactivated)
        incSending = incSending && batchEmail.Length > 0;

        Site[] sites = SiteDB.GetAll();


        string output = string.Empty;

        Hashtable lettersHash = LetterDB.GetHashTable();

        Offering[] offerings = OfferingDB.GetAll(false, -1);
        for (int j = 0; j < offerings.Length; j++)
        {
            if (offerings[j].ReminderLetterMonthsLaterToSend == 0 || offerings[j].ReminderLetterID == -1)
            {
                continue;
            }

            Booking[] bookings = BookingDB.GetWhenLastServiceFromXMonthsAgoToGenerageReminderLetter(offerings[j].OfferingID, date, offerings[j].ReminderLetterMonthsLaterToSend);


            Hashtable distinctPatients = new Hashtable();
            for (int i = 0; i < bookings.Length; i++)
            {
                if (bookings[i].Patient != null && distinctPatients[bookings[i].Patient.PatientID] == null)
                {
                    distinctPatients[bookings[i].Patient.PatientID] = bookings[i].Patient;
                }
            }

            Patient[] patients = (Patient[])(new ArrayList(distinctPatients.Values)).ToArray(typeof(Patient));
            Hashtable patientContactEmailHash = GetPatientEmailCache(patients);



            // Generate Letters

            ArrayList filesToPrint = new ArrayList();
            for (int i = 0; i < bookings.Length; i++)
            {
                Booking curBooking = bookings[i];
                if (curBooking.Patient == null)
                {
                    continue;
                }

                Patient curPatient         = curBooking.Patient;
                string  curPatientEmail    = GetEmail(patientContactEmailHash, curPatient.Person.EntityID);
                bool    curPatientHasEmail = curPatientEmail != null;


                SendMethod sendMethod = incPtSending && curPatientHasEmail ? SendMethod.Email_To_Patient : SendMethod.Batch;

                if (incSending)
                {
                    if (sendMethod == SendMethod.Email_To_Patient)
                    {
                        // generate and send email
                        Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.PDF, lettersHash, sites);
                        fileContents.DocName = "Reminder" + System.IO.Path.GetExtension(fileContents.DocName);
                        if (fileContents != null)
                        {
                            Site site = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic);
                            SendEmail(site.Name, curPatientEmail, "Important Reminder", "Hi " + curBooking.Patient.Person.Firstname + ",<br /><br />Please find attached a review reminder letter for a previous appointment.<br /><br/>Best regards,<br />" + site.Name, true, new Letter.FileContents[] { fileContents });
                        }
                    }
                    else
                    {
                        // generate and add to batch list (if batch email set)
                        if (batchEmail.Length > 0)
                        {
                            Letter.FileContents fileContents = GenerteLetter(curBooking, Letter.FileFormat.Word, lettersHash, sites);
                            if (fileContents != null)
                            {
                                filesToPrint.Add(fileContents);
                            }
                        }
                    }
                }

                string addEditContactListPage;
                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    addEditContactListPage = "AddEditContactList.aspx";
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    addEditContactListPage = "ContactAusListV2.aspx";
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }

                string allFeatures     = "dialogWidth:555px;dialogHeight:350px;center:yes;resizable:no; scroll:no";
                string onclick         = "onclick=\"javascript:window.showModalDialog('" + addEditContactListPage + "?entity_type=referrer&id=" + curBooking.Patient.Person.EntityID.ToString() + "', '', '" + allFeatures + "');document.getElementById('btnUpdateList').click();return false;\"";
                string hrefUpdateEmail = "<u><a style=\"text-decoration: none\" title=\"Edit\" AlternateText=\"Edit\" " + onclick + " href=\"\">Update PT Email</a></u>";

                output += @"<tr>
                                <td class=""nowrap"">" + curBooking.BookingID + " &nbsp;&nbsp;&nbsp;[" + curBooking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td>
                                <td class=""text_left"">" + curBooking.Organisation.Name + @"</td>
                                <td class=""text_left"">" + curBooking.Offering.Name + @"</td>
                                <td class=""text_left"">" + ((Letter)lettersHash[curBooking.Offering.ReminderLetterID]).Docname + @"</td>
                                <td class=""text_left"">" + curPatient.Person.FullnameWithoutMiddlename + @"</td>
                                <td class=""nowrap"">" + (curPatientHasEmail ? curPatientEmail : "Has No Email") + " (" + hrefUpdateEmail + ")" + @"</td>
                                <td>" + sendMethod.ToString().Replace("_", " ") + @"</td>
                            </tr>";
            }


            // combine and email where the patient had no email
            if (incSending && filesToPrint.Count > 0)
            {
                Letter.FileContents filesContents = Letter.FileContents.Merge((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)), "Reminders.pdf"); // .pdf
                SendEmail(
                    ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value,
                    batchEmail,
                    "Batch Reminder Letters",
                    string.Empty,
                    true,
                    new Letter.FileContents[] { filesContents });
            }
        }


        if (output.Length == 0)
        {
            output += @"<tr>
                            <td colspan=""7"">No Reminders To Send Today</td>
                        </tr>";
        }

        return(@"
            <table class=""table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center"" style=""border-style:solid;border-width:1px;border-collapse:collapse;padding:4px;"">
            <tr>
              <th>Booking (ID, Date/Time)</th>
              <th>Organisation</th>
              <th>Service</th>
              <th>Letter</th>
              <th>Patient</th>
              <th>PT Email</th>
              <th>Send Method</th>
            </tr>
            " + output + @"
            </table>");
    }
    // http://portal.mediclinic.com.au:803/Hinx/HinxGeneration.aspx?pwd=mah_sms_reminder
    // http://portal.mediclinic.com.au:803/Hinx/HinxGeneration.aspx?pwd=mah_sms_reminder&inc_sending=false


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            string pwd = Request.Form["pwd"];

            if (pwd == null)
            {
                pwd = Request.QueryString["pwd"];
            }

            if (pwd != null)  // sent by http post
            {
                if (pwd == null || pwd != System.Configuration.ConfigurationManager.AppSettings["SMSRunRemindersPwd"])
                {
                    throw new CustomMessageException("Incorrect password");
                }

                string exceptionOutput = string.Empty;

                if (Session != null && Session["DB"] != null)
                {
                    throw new CustomMessageException("Can not run this while logged in.");
                }
                else
                {
                    System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
                    for (int i = 0; i < tbl.Rows.Count; i++)
                    {
                        string databaseName = tbl.Rows[i][0].ToString();

                        if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                        {
                            continue;
                        }
                        if (databaseName == "Mediclinic_0026")
                        {
                            continue;
                        }

                        try
                        {
                            Session["DB"] = databaseName;
                            Session["SystemVariables"] = SystemVariableDB.GetAll();

                            if (Convert.ToInt32(SystemVariableDB.GetByDescr("AutoMedicareClaiming").Value) == 1)
                            {
                                GenerateMedicareHinxFiles();
                                GenerateDVAHinxFiles();
                            }
                        }
                        catch (Exception ex)
                        {
                            exceptionOutput += Environment.NewLine + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " " + "DB: " + databaseName;
                            exceptionOutput += Environment.NewLine + ex.ToString();
                        }
                        finally
                        {
                            Session.Remove("DB");
                            Session.Remove("SystemVariables");
                        }
                    }
                }


                if (exceptionOutput.Length > 0)
                {
                    Response.Write("Run Completed But With Errors!");
                    Response.Write(Environment.NewLine + exceptionOutput);
                }
                else
                {
                    Response.Write("Run Completed!");
                }
            }
        }
        catch (CustomMessageException ex)
        {
            Response.Write(ex.Message);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + ex.ToString());
        }
    }
    protected void SetUrlFields()
    {
        try
        {
            string booking_patient_id = Request.QueryString["bookingpatient"];
            string booking_id         = Request.QueryString["booking"];

            if (booking_patient_id != null)
            {
                lblHeading.Text = "Print A Letter For Booking";
                SetBooking();
            }
            else if (booking_id != null)
            {
                lblHeading.Text = "Print A Letter For Booking";
                SetBooking();
            }
            else
            {
                lblHeading.Text = "Print A Letter";

                td_booking_space.Visible = false;
                td_booking.Visible       = false;

                string patient_id = Request.QueryString["patient"];
                if (patient_id != null && patient_id != "-1")
                {
                    if (!Regex.IsMatch(patient_id, @"^\d+$"))
                    {
                        throw new CustomMessageException();
                    }

                    Patient patient = PatientDB.GetByID(Convert.ToInt32(patient_id));
                    if (patient == null)
                    {
                        throw new CustomMessageException();
                    }

                    btnOtherEmail.OnClientClick = "javascript: get_referrer_additional_emails(" + patient.PatientID + ");return false;";

                    txtUpdatePatientID.Text      = patient.PatientID.ToString();
                    txtUpdatePatientName.Text    = patient.Person.FullnameWithoutMiddlename;
                    txtUpdatePatientName.Visible = false;
                    lblUpdatePatientName.Text    = "<a href=\"#=\" onclick=\"open_new_window('PatientDetailV2.aspx?type=view&id=" + patient.PatientID + "'); return false;\">" + patient.Person.FullnameWithoutMiddlename + "</a>";
                    lblUpdatePatientName.Visible = true;


                    // hide if got from url ... no need to change it
                    btnPatientListPopup.Visible = false;
                    btnClearPatient.Visible     = false;


                    // if patient only linked to 1 org, then set org
                    Organisation[] orgs = RegisterPatientDB.GetOrganisationsOf(patient.PatientID);
                    if (orgs.Length == 1)
                    {
                        txtUpdateOrganisationID.Text      = orgs[0].OrganisationID.ToString();
                        txtUpdateOrganisationName.Text    = orgs[0].Name;
                        txtUpdateOrganisationName.Visible = false;
                        lblUpdateOrganisationName.Text    = "<a href=\"#=\" onclick=\"open_new_window('OrganisationDetailV2.aspx?type=view&id=" + orgs[0].OrganisationID + "'); return false;\">" + orgs[0].Name + "</a>";
                        lblUpdateOrganisationName.Visible = true;

                        PopulateLettersList();

                        // hide if got from url ... no need to change it
                        btnOrganisationListPopup.Visible = false;
                        btnClearOrganisation.Visible     = false;
                    }
                }

                string org_id = Request.QueryString["org"];
                if (org_id != null && org_id != "0")
                {
                    if (!Regex.IsMatch(org_id, @"^\d+$"))
                    {
                        throw new CustomMessageException();
                    }

                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(org_id));
                    if (org == null)
                    {
                        throw new CustomMessageException();
                    }

                    txtUpdateOrganisationID.Text      = org.OrganisationID.ToString();
                    txtUpdateOrganisationName.Text    = org.Name;
                    txtUpdateOrganisationName.Visible = false;
                    lblUpdateOrganisationName.Text    = "<a href=\"#=\" onclick=\"open_new_window('OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID + "'); return false;\">" + org.Name + "</a>";
                    lblUpdateOrganisationName.Visible = true;

                    PopulateLettersList();

                    // hide if got from url ... no need to change it
                    btnOrganisationListPopup.Visible = false;
                    btnClearOrganisation.Visible     = false;
                }
            }


            UpdateTextbox(txtUpdatePatientName, lblUpdatePatientName, txtUpdatePatientID.Text.Length == 0);
            UpdateTextbox(txtUpdateOrganisationName, lblUpdateOrganisationName, txtUpdateOrganisationID.Text.Length == 0);

            string letter_id = Request.QueryString["letter"];
            if (letter_id != null && letter_id != "-1")
            {
                if (!Regex.IsMatch(letter_id, @"^\d+$"))
                {
                    throw new CustomMessageException();
                }

                Letter letter = LetterDB.GetByID(Convert.ToInt32(letter_id));
                if (letter == null)
                {
                    throw new CustomMessageException();
                }

                foreach (ListItem item in lstLetters.Items)
                {
                    if (item.Value == letter.LetterID.ToString())
                    {
                        item.Selected = true;
                    }
                }
            }


            txtSubject.Text   = SystemVariableDB.GetByDescr("LettersEmailDefaultSubject").Value;
            FreeTextBox1.Text = SystemVariableDB.GetByDescr("LettersEmailSignature").Value;
        }
        catch (CustomMessageException ex)
        {
            SetErrorMessage();
        }
    }
    protected void GrdNote_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId       = (Label)GrdNote.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlNoteType = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlNoteType");
        DropDownList ddlBodyPart = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlBodyPart");
        TextBox      txtText     = (TextBox)GrdNote.Rows[e.RowIndex].FindControl("txtText");
        //DropDownList ddlSite = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlSite");
        DropDownList ddlDate_Day   = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Day");
        DropDownList ddlDate_Month = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Month");
        DropDownList ddlDate_Year  = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Year");

        DataTable dt = ViewState["noteinfo_data"] as DataTable;

        DataRow[] foundRows = dt.Select("note_id=" + lblId.Text);
        Note      note      = NoteDB.Load(foundRows[0]);

        DateTime date = GetDate(ddlDate_Day.SelectedValue, ddlDate_Month.SelectedValue, ddlDate_Year.SelectedValue);

        NoteDB.Update(Convert.ToInt32(lblId.Text), date, Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(ddlNoteType.SelectedValue), Convert.ToInt32(ddlBodyPart.SelectedValue), txtText.Text, note.Site.SiteID);



        // if its a booking note
        // email admin so they know if a provider is sabotaging the system (it has happened before)

        int loggedInStaffID = Session["StaffID"] == null ? -1 : Convert.ToInt32(Session["StaffID"]);

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)  // if note is for a booking
        {
            int thresholdCharacters   = 50;
            int totalCharactersBefore = note.Text.Trim().Length;
            int totalCharactersAfter  = txtText.Text.Trim().Length;
            int difference            = totalCharactersAfter - totalCharactersBefore;

            if (totalCharactersBefore > thresholdCharacters && totalCharactersAfter < thresholdCharacters && difference < -20)
            {
                string mailText = @"This is an administrative email to notify you that notes for a booking may have been deleted.

<u>Logged-in user performing the udate</u>
" + StaffDB.GetByID(loggedInStaffID).Person.FullnameWithoutMiddlename + @"

<u>Original Text (Characters: " + totalCharactersBefore + @")</u>
<font color=""blue"">" + note.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Updated Text (Characters: " + totalCharactersAfter + @")</u>
<font color=""blue"">" + txtText.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Booking details</u>
<table border=""0"" cellpadding=""2"" cellspacing=""2""><tr><td>Booking ID:</td><td>" + booking.BookingID + @"</td></tr><tr><td>Booking Date:</td><td>" + booking.DateStart.ToString("d MMM, yyyy") + " " + booking.DateStart.ToString("h:mm") + (booking.DateStart.Hour < 12 ? "am" : "pm") + @"</td></tr><tr><td>Organisation:</td><td>" + booking.Organisation.Name + @"</td></tr><tr><td>Provider:</td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr><tr><td>Patient:</td><td>" + (booking.Patient == null ? "" : booking.Patient.Person.FullnameWithoutMiddlename + " [ID:" + booking.Patient.PatientID + "]") + @"</td></tr><tr><td>Status:</td><td>" + booking.BookingStatus.Descr + @"</td></tr></table>

Regards,
Mediclinic
";
                bool   EnableDeletedBookingsAlerts = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDeletedBookingsAlerts").Value) == 1;

                if (EnableDeletedBookingsAlerts && !Utilities.IsDev())
                {
                    Emailer.AsyncSimpleEmail(
                        ((SystemVariables)Session["SystemVariables"])["Email_FromEmail"].Value,
                        ((SystemVariables)Session["SystemVariables"])["Email_FromName"].Value,
                        ((SystemVariables)Session["SystemVariables"])["AdminAlertEmail_To"].Value,
                        "Notification that booking notes may have been deleted",
                        mailText.Replace(Environment.NewLine, "<br />"),
                        true,
                        null);
                }
            }
        }



        GrdNote.Columns[7].Visible = true;
        GrdNote.EditIndex          = -1;
        FillNoteGrid();
    }
    protected void FillNoteGrid()
    {
        if (!IsValidFormID())
        {
            if (!Utilities.IsDev() || Request.QueryString["id"] != null)
            {
                HideTableAndSetErrorMessage();
                return;
            }

            // can still view all if dev and no id set .. but no insert/edit
            GrdNote.Columns[5].Visible = false;
        }

        if (!IsValidFormScreen() && !Utilities.IsDev())
        {
            HideTableAndSetErrorMessage();
            return;
        }


        DataTable dt = IsValidFormID() ? NoteDB.GetDataTable_ByEntityID(GetFormID(), null, true, true) : NoteDB.GetDataTable(true);


        if (IsValidFormScreen())
        {
            Hashtable allowedNoteTypes = new Hashtable();
            DataTable noteTypes        = ScreenNoteTypesDB.GetDataTable_ByScreenID(GetFormScreen());
            for (int i = 0; i < noteTypes.Rows.Count; i++)
            {
                allowedNoteTypes[Convert.ToInt32(noteTypes.Rows[i]["note_type_id"])] = 1;
            }

            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (allowedNoteTypes[Convert.ToInt32(dt.Rows[i]["note_type_id"])] == null)
                {
                    dt.Rows.RemoveAt(i);
                }
            }
        }

        UserView userView         = UserView.GetInstance();
        bool     canSeeModifiedBy = userView.IsStakeholder || userView.IsMasterAdmin;

        dt.Columns.Add("last_modified_note_info_visible", typeof(Boolean));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_modified_note_info_visible"] = canSeeModifiedBy;
        }


        ViewState["noteinfo_data"] = dt;



        // add note info to hidden field to use when emailing notes

        string emailBodyText = string.Empty;

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)
        {
            emailBodyText += @"<br /><br />
<u>Treatment Information</u>
<br />
<table border=""0"" cellpadding=""0"" cellspacing=""0"">" +
                             (booking.Patient == null ? "" : @"<tr><td>Patient</td><td style=""width:10px;""></td><td>" + booking.Patient.Person.FullnameWithoutMiddlename + @"</td></tr>") +
                             (booking.Offering == null ? "" : @"<tr><td>Service</td><td></td><td>" + booking.Offering.Name + @"</td></tr>") + @"
    <tr><td>Date</td><td></td><td>" + booking.DateStart.ToString("dd-MM-yyyy") + @"</td></tr>
    <tr><td>Provider</td><td></td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr>
</table>";
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Note n = NoteDB.Load(dt.Rows[i]);
            emailBodyText += "<br /><br /><u>Note (" + n.DateAdded.ToString("dd-MM-yyyy") + ")</u><br />" + n.Text.Replace(Environment.NewLine, "<br />");
        }
        emailText.Value = emailBodyText + "<br /><br />" + SystemVariableDB.GetByDescr("LettersEmailSignature").Value;;



        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && ViewState["noteinfo_sortexpression"] != null && ViewState["noteinfo_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort      = ViewState["noteinfo_sortexpression"].ToString();
                GrdNote.DataSource = dataView;
            }
            else
            {
                GrdNote.DataSource = dt;
            }


            try
            {
                GrdNote.DataBind();
            }
            catch (Exception ex)
            {
                this.lblErrorMessage.Visible = true;
                this.lblErrorMessage.Text    = ex.ToString();
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdNote.DataSource = dt;
            GrdNote.DataBind();

            int TotalColumns = GrdNote.Rows[0].Cells.Count;
            GrdNote.Rows[0].Cells.Clear();
            GrdNote.Rows[0].Cells.Add(new TableCell());
            GrdNote.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdNote.Rows[0].Cells[0].Text       = "No Record Found";
        }


        Tuple <string, string, string, string> refsEmailInfo = GetReferrersEmail();
        ImageButton btnEmail = GrdNote.HeaderRow.FindControl("btnEmail") as ImageButton;

        if (refsEmailInfo != null)
        {
            btnEmail.Visible = true;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefEmail")).Value           = refsEmailInfo.Item1;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefName")).Value            = refsEmailInfo.Item2;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenBookingOrg")).Value         = refsEmailInfo.Item3;
            ((HiddenField)GrdNote.HeaderRow.FindControl("HiddenBookingPatientName")).Value = refsEmailInfo.Item4;
        }
        else
        {
            btnEmail.Visible = false;
        }

        DisallowAddEditIfNoPermissions(); // place this after databinding
    }
Exemple #20
0
    private void LogIn(string login, string pwd)
    {
        try
        {
            Session.Remove("DB");
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
            {
                Session["DB"] = ConfigurationManager.AppSettings["Database"];
            }
            else // Get DB from Mediclinic_Main
            {
                UserDatabaseMapper user = UserDatabaseMapperDB.GetByLogin(login);
                if (user == null)
                {
                    this.FailureText.Text = "<div class=\"alert alert-danger\" runat=\"server\"><strong>Login Failed.</strong> Please ensure that your username and password are correct and try again.</div>";
                    return;
                }

                Session["DB"] = user.DBName;
            }



            Staff   staff              = StaffDB.GetByLogin(login);
            Patient patient            = PatientDB.GetByLogin(login);
            bool    allowPatientLogins = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowPatientLogins").Value) == 1;
            bool    validStaff         = staff != null && staff.Pwd == pwd && !staff.IsFired;
            bool    validPatient       = allowPatientLogins && patient != null && patient.Pwd == pwd && !patient.IsDeleted;

            if (validStaff)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(staff.StaffID, -1, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, staff.StaffID, -1);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(staff.StaffID, -1);
                    UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, -1, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                Session["IsLoggedIn"]    = true;
                Session["IsStakeholder"] = staff.IsStakeholder;
                Session["IsMasterAdmin"] = staff.IsMasterAdmin;
                Session["IsAdmin"]       = staff.IsAdmin;
                Session["IsPrincipal"]   = staff.IsPrincipal;
                Session["IsProvider"]    = staff.IsProvider;
                Session["IsExternal"]    = staff.IsExternal;
                Session["StaffID"]       = staff.StaffID;
                Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename;
                Session["StaffFirstname"] = staff.Person.Firstname;
                Session["NumDaysToDisplayOnBookingScreen"] = staff.NumDaysToDisplayOnBookingScreen;
                Session["HideBookingNotes"] = staff.HideBookingNotes;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = staff.ShowHeaderOnBookingScreen;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                UserView userView = UserView.GetInstance();

                Site[] allowedSites = StaffSiteRestrictionDB.GetSitesNotRestricted(staff.StaffID, -1, false);


                //
                // until aged care is running, remove aged care from display
                //

                /*
                 * System.Collections.ArrayList list = new System.Collections.ArrayList();
                 * for (int i = 0; i < allowedSites.Length; i++)
                 *  if (allowedSites[i].SiteType.ID == 1 || Utilities.IsDev())
                 *      list.Add(allowedSites[i]);
                 * allowedSites = (Site[])list.ToArray(typeof(Site));
                 */

                Site[] allSites = SiteDB.GetAll();
                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]          = allSites[0].SiteID;
                    Session["SiteName"]        = allSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }



                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]          = allowedSites[0].SiteID;
                    Session["SiteName"]        = allowedSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allowedSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Session["IsMultipleSites"] = true;
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }



                /*
                 *
                 * if (!staff.IsAdmin)
                 * {
                 *  // provs only login to clinic site
                 *  Site site = SiteDB.GetByID(2);
                 *  Session["SiteID"]   = site.SiteID;
                 *  Session["SiteName"] = site.Name;
                 *
                 *  if (Session["OrgID"] == null)  // providers et to login to select an org, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 * else
                 * {
                 *  if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 *
                 */

                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }
            else if (validPatient)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(-1, patient.PatientID, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, -1, patient.PatientID);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(-1, patient.PatientID);
                    UserLoginDB.Insert(-1, (patient == null) ? -1 : patient.PatientID, login, -1, validPatient, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                Session["IsLoggedIn"]    = true;
                Session["IsStakeholder"] = false;
                Session["IsMasterAdmin"] = false;
                Session["IsAdmin"]       = false;
                Session["IsPrincipal"]   = false;
                Session["IsProvider"]    = false;
                Session["IsExternal"]    = false;
                Session["PatientID"]     = patient.PatientID;
                Session["StaffFullnameWithoutMiddlename"] = patient.Person.FullnameWithoutMiddlename;
                Session["StaffFirstname"] = patient.Person.Firstname;
                Session["NumDaysToDisplayOnBookingScreen"]   = 3;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = true;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                Site[] allSites     = SiteDB.GetAll();
                Site[] allowedSites = SiteDB.GetAll();


                //
                // remove aged care from display
                //
                System.Collections.ArrayList list = new System.Collections.ArrayList();
                for (int i = 0; i < allSites.Length; i++)
                {
                    if (allSites[i].SiteType.ID == 1)
                    {
                        list.Add(allSites[i]);
                    }
                }
                allowedSites = (Site[])list.ToArray(typeof(Site));

                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]         = allSites[0].SiteID;
                    Session["SiteName"]       = allSites[0].Name;
                    Session["SiteIsClinic"]   = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allSites[0].SiteType.Descr;


                    UserLoginDB.UpdateSite(-1, patient.PatientID, allSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers, ext staff, patient logins need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }


                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }

                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]         = allowedSites[0].SiteID;
                    Session["SiteName"]       = allowedSites[0].Name;
                    Session["SiteIsClinic"]   = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(-1, patient.PatientID, allowedSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }

                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }


                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }

            else
            {
                //UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                this.FailureText.Text = "Login Failed.";
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            if (Utilities.IsDev())
            {
                FailureText.Text = ex.ToString();
            }
            else
            {
                throw;
            }
        }
    }
    private void FillEmptyAddForm()
    {
        txtName.Focus();

        Page.Title      = ((SystemVariables)Session["SystemVariables"])["Site"].Value + " - " + "Add Site";
        lblHeading.Text = "Add Site";

//        this.lnkNotes.Visible = false;

        idRow.Visible = false;


        DataTable dt = SiteDB.GetDataTable();
        bool      showClinicAddOption   = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteClinic").Value) == 1;
        bool      showAgedCareAddOption = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteAgedCare").Value) == 1;
        bool      showGPAddOption       = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowAddSiteGP").Value) == 1;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 1)
            {
                showClinicAddOption = false;
            }
            if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 2)
            {
                showAgedCareAddOption = false;
            }
            if (Convert.ToInt32(dt.Rows[i]["site_type_id"]) == 3)
            {
                showGPAddOption = false;
            }
        }
        ddlClinic.Items.Clear();
        if (showClinicAddOption)
        {
            ddlClinic.Items.Add(new ListItem("Clinic", "1"));
        }
        if (showAgedCareAddOption)
        {
            ddlClinic.Items.Add(new ListItem("Aged Care", "2"));
        }
        if (showGPAddOption)
        {
            ddlClinic.Items.Add(new ListItem("GP", "3"));
        }
        if (!showClinicAddOption && !showAgedCareAddOption)
        {
            HideTableAndSetErrorMessage("Unable to add either Clinic or Aged Care Facility or GP.");
        }



        ddlNumBookingMonthsToGet.SelectedValue = "9";

        ddlFiscalYrEnd_Day.SelectedValue   = "30";
        ddlFiscalYrEnd_Month.SelectedValue = "6";

        chkIncSunday.Checked    = false;
        chkIncMonday.Checked    = true;
        chkIncTuesday.Checked   = true;
        chkIncWednesday.Checked = true;
        chkIncThursday.Checked  = true;
        chkIncFriday.Checked    = true;
        chkIncSaturday.Checked  = false;

        ddlDayStart_Hour.SelectedValue   = "8";
        ddlDayStart_Minute.SelectedValue = "0";
        ddlDayEnd_Hour.SelectedValue     = "18";
        ddlDayEnd_Minute.SelectedValue   = "0";

        ddlLunchStart_Hour.SelectedValue   = "12";
        ddlLunchStart_Minute.SelectedValue = "0";
        ddlLunchEnd_Hour.SelectedValue     = "13";
        ddlLunchEnd_Minute.SelectedValue   = "0";

        addressControl.Visible    = false;
        addressAusControl.Visible = false;

        btnSubmit.Text = "Add Site";
    }
Exemple #22
0
    protected void Run(bool incDisplay, bool incSending)
    {
        // 1. get all fields from systemvariables

        bool   EnableEmails = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendEmail").Value) == 1;
        string EmailAddress = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_EmailAddress").Value;

        bool IncClinicsAuto  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncClinic").Value) == 1;
        bool IncAgedCareAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncAgedCare").Value) == 1;

        bool IncUnsentAuto  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncUnsent").Value) == 1;
        bool IncBatchedAuto = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_IncBatched").Value) == 1;

        ReferrerEPCLettersSending.SendMethod sendMethod = SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMethod").Value == "Email" ?
                                                          ReferrerEPCLettersSending.SendMethod.Email_To_Referrer :
                                                          ReferrerEPCLettersSending.SendMethod.Batch;

        bool SendMondays    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendMondays").Value) == 1;
        bool SendTuesdays   = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendTuesdays").Value) == 1;
        bool SendWednesdays = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendWednesdays").Value) == 1;
        bool SendThursdays  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendThursdays").Value) == 1;
        bool SendFridays    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendFridays").Value) == 1;
        bool SendSaturdays  = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSaturdays").Value) == 1;
        bool SendSundays    = Convert.ToInt32(SystemVariableDB.GetByDescr("ReferrerEPCAutoGenerateLettersEmail_SendSundays").Value) == 1;



        // 2. validate

        if (!EnableEmails)
        {
            return;
        }
        if (!Utilities.IsValidEmailAddresses(EmailAddress, false))
        {
            return;
        }
        if (!IncClinicsAuto && !IncAgedCareAuto)
        {
            return;
        }

        if (DateTime.Today.DayOfWeek == DayOfWeek.Monday && !SendMondays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Tuesday && !SendTuesdays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday && !SendWednesdays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Thursday && !SendThursdays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Friday && !SendFridays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday && !SendSaturdays)
        {
            return;
        }
        if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday && !SendSundays)
        {
            return;
        }



        // 3. run it

        int siteID = -1;

        if (IncClinicsAuto && IncAgedCareAuto)
        {
            siteID = -1;
        }
        else if (IncClinicsAuto && !IncAgedCareAuto)
        {
            foreach (Site s in SiteDB.GetAll())
            {
                if (s.SiteType.ID == 1)
                {
                    siteID = s.SiteID;
                }
            }
        }
        else if (!IncClinicsAuto && IncAgedCareAuto)
        {
            foreach (Site s in SiteDB.GetAll())
            {
                if (s.SiteType.ID == 2)
                {
                    siteID = s.SiteID;
                }
            }
        }


        string outputInfo;
        string outputList;

        Letter.FileContents fileContents = ReferrerEPCLettersSending.Run(
            sendMethod,
            siteID,
            -1,
            -1,
            IncBatchedAuto,
            IncUnsentAuto,
            !incSending,
            false,
            out outputInfo,
            out outputList,
            string.Empty
            );

        if (incDisplay)
        {
            Response.Write(outputInfo + "<br /><br />" + outputList);
        }



        // 4. Put in file and email it

        if (fileContents != null)
        {
            string tmpLettersDirectory = Letter.GetTempLettersDirectory();
            if (!System.IO.Directory.Exists(tmpLettersDirectory))
            {
                throw new CustomMessageException("Temp letters directory doesn't exist");
            }

            string tmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory);
            System.IO.Directory.CreateDirectory(tmpDir);
            string tmpFileName = tmpDir + fileContents.DocName;
            System.IO.File.WriteAllBytes(tmpFileName, fileContents.Contents);

            Emailer.SimpleEmail(EmailAddress, "Automated Referral Letters [" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + "]", "Please find attached referral letters to send to referrers.<br /><br />Regards,<br />Mediclinic", true, new string[] { tmpFileName }, null);

            System.IO.File.Delete(tmpFileName);
            System.IO.Directory.Delete(tmpDir);
        }
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            decimal smsBalance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal();
            decimal smsCost    = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);

            int maxSMSCountCanAfford = smsCost == 0 ? 1000000 : (int)(smsBalance / smsCost);
            int smsCountSending      = 0;


            //
            // Start Validation
            //

            txtEmailSubject.Text     = txtEmailSubject.Text.Trim();
            txtEmailForPrinting.Text = txtEmailForPrinting.Text.Trim();
            txtSMSText.Text          = txtSMSText.Text.Trim();


            bool printSelected = (ddlBothMobileAndEmail.SelectedValue == "1" || ddlEmailNoMobile.SelectedValue == "1" ||
                                  ddlMobileNoEmail.SelectedValue == "1" || ddlNeitherMobileOrEmail.SelectedValue == "1");
            bool emailSelected = (ddlBothMobileAndEmail.SelectedValue == "2" || ddlEmailNoMobile.SelectedValue == "2" ||
                                  ddlMobileNoEmail.SelectedValue == "2" || ddlNeitherMobileOrEmail.SelectedValue == "2");
            bool smsSelected = (ddlBothMobileAndEmail.SelectedValue == "3" || ddlEmailNoMobile.SelectedValue == "3" ||
                                ddlMobileNoEmail.SelectedValue == "3" || ddlNeitherMobileOrEmail.SelectedValue == "3");


            string validationErrors = string.Empty;

            if (printSelected)
            {
                if (txtEmailForPrinting.Text.Length == 0)
                {
                    validationErrors += "<li>Printed Batch Letters Email Address To Send To can not be empty.</li>";
                }
                else if (!Utilities.IsValidEmailAddress(txtEmailForPrinting.Text))
                {
                    validationErrors += "<li>Printed Batch Letters Email Address To Send To must look like a valid email address.</li>";
                }
            }
            if (emailSelected)
            {
                if (txtEmailSubject.Text.Length == 0)
                {
                    validationErrors += "<li>Email Subject can not be empty.</li>";
                }
                if (FreeTextBox1.Text.Length == 0)
                {
                    validationErrors += "<li>Email Text can not be empty.</li>";
                }
            }
            if (smsSelected)
            {
                if (smsCost > 0 && smsBalance == 0)
                {
                    validationErrors += "<li>Can not send SMS's - your SMS balance is empty. Please topup or unselect sending by SMS.</li>";
                }
                else if (txtSMSText.Text.Length == 0)
                {
                    validationErrors += "<li>SMS Text can not be empty.</li>";
                }
            }

            if (validationErrors.Length > 0)
            {
                throw new CustomMessageException("<ul>" + validationErrors + "</ul>");
            }

            //
            // End Validation
            //



            //
            // get hashtables of those with mobiles and emails
            //

            ArrayList regRefIDsArr = new ArrayList();


            foreach (ListItem referrerItem in lstReferrers.Items)  // regrefid
            {
                if (referrerItem.Selected)
                {
                    regRefIDsArr.Add(Convert.ToInt32(referrerItem.Value));
                }
            }


            int[]     regRefIDs    = (int[])regRefIDsArr.ToArray(typeof(int));
            int[]     entityIDs    = RegisterReferrerDB.GetOrgEntityIDs(regRefIDs);
            Hashtable entityIDHash = RegisterReferrerDB.GetOrgEntityIDsHash(regRefIDs);
            Hashtable regRefIDHash = RegisterReferrerDB.GetByIDsInHashtable(regRefIDs);

            Hashtable emailHash  = PatientsContactCacheDB.GetBullkEmail(entityIDs, -1);
            Hashtable mobileHash = PatientsContactCacheDB.GetBullkPhoneNumbers(entityIDs, -1, "30");

            string email_from_address = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value;
            string email_from_name    = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value;

            //bool StoreLettersHistoryInDB       = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInDB"]);
            //bool StoreLettersHistoryInFlatFile = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["StoreLettersHistoryInFlatFile"]);
            bool StoreLettersHistoryInDB       = false; // don't store bulk marketing letters
            bool StoreLettersHistoryInFlatFile = false; // don't store bulk marketing letters



            //
            // ok start the sending process
            //


            int bulkLetterSendingQueueBatchID = UseBulkLetterSender ? BulkLetterSendingQueueBatchDB.Insert(txtEmailForPrinting.Text, false) : -1;


            // TODO: Send Letter By Email
            int letterPrintHistorySendMethodID = 1; // send by mail


            // make sure at least one referrer selected
            if (lstReferrers.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select at least one referrer.");
            }

            // make sure at least one letter selected
            if (lstLetters.GetSelectedIndices().Length == 0)
            {
                throw new CustomMessageException("Please select a letter.");
            }


            // get letter and make sure it exists
            Letter letter             = LetterDB.GetByID(Convert.ToInt32(lstLetters.SelectedValue));
            string sourchTemplatePath = letter.GetFullPath(Convert.ToInt32(Session["SiteID"]));
            if (!File.Exists(sourchTemplatePath))
            {
                throw new CustomMessageException("File doesn't exist.");
            }

            // get temp directory
            string tmpLettersDirectory = Letter.GetTempLettersDirectory();
            if (!Directory.Exists(tmpLettersDirectory))
            {
                throw new CustomMessageException("Temp letters directory doesn't exist");
            }

            // delete old tmp files
            FileHelper.DeleteOldFiles(tmpLettersDirectory, new TimeSpan(1, 0, 0));



            // create individual merged docs and put into list of docsToMerge - only if there is an org-patient relationship
            ArrayList docsToMerge = new ArrayList();

            Site site    = SiteDB.GetByID(Convert.ToInt32(Session["SiteID"]));
            int  StaffID = Convert.ToInt32(Session["StaffID"]);
            foreach (ListItem referrerItem in lstReferrers.Items)
            {
                if (!referrerItem.Selected)
                {
                    continue;
                }

                if (UseBulkLetterSender)
                {
                    int        refEntityID    = (int)entityIDHash[Convert.ToInt32(referrerItem.Value)];
                    string     refPhoneNumber = GetPhoneNbr(mobileHash, refEntityID, true);
                    string     refEmail       = GetEmail(emailHash, refEntityID);
                    SendMethod sendMethod     = GetSendMethod(refEmail != null, refPhoneNumber != null);

                    RegisterReferrer regRef = RegisterReferrerDB.GetByID(Convert.ToInt32(referrerItem.Value));

                    if (sendMethod != SendMethod.None)
                    {
                        string text = string.Empty;
                        if (sendMethod == SendMethod.SMS)
                        {
                            text = txtSMSText.Text;
                        }
                        if (sendMethod == SendMethod.Email)
                        {
                            text = FreeTextBox1.Text;
                        }

                        text = ReplaceMergeFields(text, regRefIDHash, Convert.ToInt32(referrerItem.Value));

                        bool generateLetter = false;
                        if (sendMethod == SendMethod.SMS)
                        {
                            generateLetter = false;
                        }
                        if (sendMethod == SendMethod.Email)
                        {
                            generateLetter = lstLetters.GetSelectedIndices().Length != 0;
                        }
                        if (sendMethod == SendMethod.Print)
                        {
                            generateLetter = true;
                        }


                        if (sendMethod == SendMethod.SMS)  // copy to other methods!!
                        {
                            smsCountSending++;
                        }


                        BulkLetterSendingQueueDB.Insert
                        (
                            bulkLetterSendingQueueBatchID,
                            (int)sendMethod,                                              // bulk_letter_sending_queue_method_id
                            StaffID,                                                      // added_by
                            -1,                                                           // patient_id
                            regRef.Referrer.ReferrerID,                                   // referrer_id
                            -1,                                                           // booking_id
                            (sendMethod == SendMethod.SMS)   ? refPhoneNumber       : "", // phone_number
                            (sendMethod == SendMethod.Email) ? refEmail             : "", // email_to_address
                            "",                                                           // email_to_name
                            (sendMethod == SendMethod.Email) ? email_from_address   : "", // email_from_address
                            (sendMethod == SendMethod.Email) ? email_from_name      : "", // email_from_name
                            text,                                                         // text
                            (sendMethod == SendMethod.Email) ? txtEmailSubject.Text : "", // email_subject
                            "",                                                           // email_attachment_location
                            false,                                                        // email_attachment_delete_after_sending
                            false,                                                        // email_attachment_folder_delete_after_sending

                            !generateLetter ? -1    : letter.LetterID,
                            !generateLetter ? false : chkKeepInHistory.Checked && StoreLettersHistoryInDB,
                            !generateLetter ? false : chkKeepInHistory.Checked && StoreLettersHistoryInFlatFile,
                            !generateLetter ? -1    : letterPrintHistorySendMethodID,
                            !generateLetter ? ""    : Letter.GetLettersHistoryDirectory(0),
                            !generateLetter ? ""    : letter.Docname.Replace(".dot", ".doc"),
                            !generateLetter ? -1    : site.SiteID,
                            0,                                                             // organisation_id
                            -1,                                                            // booking id
                            -1,                                                            // patient_id

                            !generateLetter ? -1    : Convert.ToInt32(referrerItem.Value), // register_referrer_id_to_use_instead_of_patients_reg_ref
                            !generateLetter ? -1    : StaffID,
                            -1,                                                            //healthcardactionid
                            !generateLetter ? ""    : sourchTemplatePath,
                            !generateLetter ? ""    : tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"),
                            !generateLetter ? false : true,

                            "",    // email_letter_extra_pages
                            "",    // email_letter_item_seperator
                            "",    // sql_to_run_on_completion
                            ""     // sql_to_run_on_failure
                        );
                    }
                }
                else
                {
                    // create doc
                    string tmpSingleFileName = Letter.CreateMergedDocument(
                        letter.LetterID,
                        chkKeepInHistory.Checked && StoreLettersHistoryInDB,
                        chkKeepInHistory.Checked && StoreLettersHistoryInFlatFile,
                        letterPrintHistorySendMethodID,
                        Letter.GetLettersHistoryDirectory(0),
                        letter.Docname.Replace(".dot", ".doc"),
                        site,
                        0,  // org id
                        -1, // booking id
                        -1, // patient id
                        Convert.ToInt32(referrerItem.Value),
                        StaffID,
                        -1, //healthcardactionid
                        sourchTemplatePath,
                        tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"),
                        true);

                    // record name of merged doc
                    docsToMerge.Add(tmpSingleFileName);
                }
            }


            if (UseBulkLetterSender)
            {
                if ((smsCountSending * smsCost) > smsBalance)
                {
                    BulkLetterSendingQueueDB.DeleteByBatchID(bulkLetterSendingQueueBatchID);
                    BulkLetterSendingQueueBatchDB.Delete(bulkLetterSendingQueueBatchID);

                    SetErrorMessage("Not Enough Credit To Send SMS's. Please Top Up You SMS Credit or Choose Methods Other Than SMS.");
                    return;
                }

                BulkLetterSendingQueueBatchDB.UpdateReadyToProcess(bulkLetterSendingQueueBatchID, true);
                SetErrorMessage("Items Added To Sending Queue. View Details <a href='/Letters_PrintBatch_StatusV2.aspx?batch_id=" + bulkLetterSendingQueueBatchID + "'>Here</a>");
            }
            else
            {
                // merge all tmp files
                string tmpFinalFileName = Letter.MergeMultipleDocuments(
                    ((string[])docsToMerge.ToArray(typeof(string))),
                    tmpLettersDirectory + letter.Docname.Replace(".dot", ".doc"));

                // delete all single tmp files
                foreach (string file in docsToMerge)
                {
                    File.Delete(file);
                }

                // download the document
                byte[] fileContents = File.ReadAllBytes(tmpFinalFileName);
                System.IO.File.Delete(tmpFinalFileName);

                // Nothing gets past the "DownloadDocument" method because it outputs the file
                // which is writing a response to the client browser and calls Response.End()
                // So make sure any other code that functions goes before this
                Letter.DownloadDocument(Response, fileContents, letter.Docname.Replace(".dot", ".doc"));
            }
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
    }
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Organisation org = OrganisationDB.GetByID(GetFormID());

        if (org == null)
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        lblHeading.Text             = Page.Title = "Manage Registrations For :  " + org.Name;
        this.lnkThisOrg.NavigateUrl = "~/OrganisationDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisOrg.Text        = "Back to details for " + org.Name;



        string searchSurname = "";

        if (Request.QueryString["surname_search"] != null && Request.QueryString["surname_search"].Length > 0)
        {
            searchSurname         = Request.QueryString["surname_search"];
            txtSearchSurname.Text = Request.QueryString["surname_search"];
        }
        bool searchSurnameOnlyStartsWith = true;

        if (Request.QueryString["surname_starts_with"] != null && Request.QueryString["surname_starts_with"].Length > 0)
        {
            searchSurnameOnlyStartsWith           = Request.QueryString["surname_starts_with"] == "0" ? false : true;
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }
        else
        {
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }


        DataTable dt = RegisterPatientDB.GetDataTable_PatientsOf(GetFormViewOnlyLast(), org.OrganisationID, false, false, false, false, searchSurname, searchSurnameOnlyStartsWith);


        int[] ptIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ptIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_id"]);
        }


        // get last and next booking dates

        Hashtable lastBookingDates = BookingDB.GetLastBookingDates(ptIDs, org.OrganisationID);
        Hashtable nextBookingDates = BookingDB.GetNextBookingDates(ptIDs, org.OrganisationID);

        dt.Columns.Add("last_booking_date", typeof(DateTime));
        dt.Columns.Add("next_booking_date", typeof(DateTime));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_booking_date"] = lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
            dt.Rows[i]["next_booking_date"] = nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
        }



        // get epc info

        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(ptIDs);

        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(ptIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(ptIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(ptIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;
        }



        Session["registerpatienttoorg_data"] = dt;

        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["registerpatienttoorg_sortexpression"] != null && Session["registerpatienttoorg_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort = Session["registerpatienttoorg_sortexpression"].ToString();
                GrdRegistration.DataSource = dataView;
            }
            else
            {
                GrdRegistration.DataSource = dt;
            }


            try
            {
                GrdRegistration.DataBind();
                GrdRegistration.PagerSettings.FirstPageText = "1";
                GrdRegistration.PagerSettings.LastPageText  = GrdRegistration.PageCount.ToString();
                GrdRegistration.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdRegistration.DataSource = dt;
            GrdRegistration.DataBind();

            int TotalColumns = GrdRegistration.Rows[0].Cells.Count;
            GrdRegistration.Rows[0].Cells.Clear();
            GrdRegistration.Rows[0].Cells.Add(new TableCell());
            GrdRegistration.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdRegistration.Rows[0].Cells[0].Text       = "No Record Found";
        }

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
Exemple #25
0
    protected void FillGrid_Patients(Type type, int id)
    {
        UserView userView = UserView.GetInstance();

        DataTable dt = null;

        if (type == typeof(Organisation))
        {
            Organisation org = OrganisationDB.GetByID(id);
            lblPatientsHeading.Text = "Patients of &nbsp;&nbsp;<big><b>All Referrers</b></big>&nbsp;&nbsp; at &nbsp;&nbsp;<big><b>" + org.Name + "</b></big>";

            if (userView.IsAdminView && userView.IsClinicView)
            {
                dt = PatientDB.GetDataTable(false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
            if (userView.IsAdminView && !userView.IsClinicView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOfOrgGroupType(false, "6", false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
            if (!userView.IsAdminView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOf(false, Convert.ToInt32(Session["OrgID"]), false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", "", "", id.ToString(), false, false, false);
            }
        }
        else if (type == typeof(RegisterReferrer))
        {
            RegisterReferrer regRef = RegisterReferrerDB.GetByID(id);
            lblPatientsHeading.Text = "Patients of &nbsp;&nbsp;<big><b>" + regRef.Referrer.Person.FullnameWithoutMiddlename + "</b></big>&nbsp;&nbsp; at &nbsp;&nbsp;<big><b>" + regRef.Organisation.Name + "</b></big>";

            if (userView.IsAdminView && userView.IsClinicView)
            {
                dt = PatientDB.GetDataTable(false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
            if (userView.IsAdminView && !userView.IsClinicView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOfOrgGroupType(false, "6", false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
            if (!userView.IsAdminView)
            {
                dt = RegisterPatientDB.GetDataTable_PatientsOf(false, Convert.ToInt32(Session["OrgID"]), false, false, userView.IsClinicView, false, "", false, "", false, "", "", "", "", "", false, -1, -1, -1, "", "", id.ToString(), "", "", false, false, false);
            }
        }
        else
        {
            SetErrorMessage("Unknown type: " + type.ToString());
            return;
        }


        lblPatientsHeading.Visible = true;
        GrdPatients.Visible        = true;



        // put in epc info into the table in a bulk call
        // epc exp date, if valid, how many epc's remaining...


        int[] patientIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            patientIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_id"]);
        }

        int MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);

        Hashtable patientsMedicareCountThisYearCache = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year);
        Hashtable patientsMedicareCountNextYearCache = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year + 1);
        Hashtable patientsEPCRemainingCache          = PatientsEPCRemainingCacheDB.GetBullk(patientIDs, DateTime.MinValue);

        dt.Columns.Add("epc_signed_date", typeof(DateTime));
        dt.Columns.Add("epc_expiry_date", typeof(DateTime));
        dt.Columns.Add("epc_n_services_left", typeof(Int32));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            int  totalServicesAllowedLeft = (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountThisYearCache[patientID]);
            Pair totalEPCRemaining        = patientsEPCRemainingCache[patientID] as Pair;

            int nServicesLeft = 0;
            if (totalEPCRemaining != null)
            {
                DateTime referralSignedDate = (DateTime)totalEPCRemaining.Second;
                DateTime hcExpiredDate      = referralSignedDate.AddYears(1);
                if (DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
                {
                    nServicesLeft = (int)totalEPCRemaining.First;
                }
                if (totalServicesAllowedLeft < nServicesLeft)
                {
                    nServicesLeft = totalServicesAllowedLeft;
                }

                dt.Rows[i]["epc_signed_date"]     = referralSignedDate;
                dt.Rows[i]["epc_expiry_date"]     = hcExpiredDate;
                dt.Rows[i]["epc_n_services_left"] = nServicesLeft;
            }
            else
            {
                dt.Rows[i]["epc_signed_date"]     = DBNull.Value;
                dt.Rows[i]["epc_expiry_date"]     = DBNull.Value;
                dt.Rows[i]["epc_n_services_left"] = DBNull.Value;
            }
        }



        Session["referrerinfoclinic_patients_data"] = dt;

        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["referrerinfoclinic_patients_sortexpression"] != null && Session["referrerinfoclinic_patients_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort          = Session["referrerinfoclinic_patients_sortexpression"].ToString();
                GrdPatients.DataSource = dataView;
            }
            else
            {
                GrdPatients.DataSource = dt;
            }


            try
            {
                GrdPatients.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatients.DataSource = dt;
            GrdPatients.DataBind();

            int TotalColumns = GrdPatients.Rows[0].Cells.Count;
            GrdPatients.Rows[0].Cells.Clear();
            GrdPatients.Rows[0].Cells.Add(new TableCell());
            GrdPatients.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdPatients.Rows[0].Cells[0].Text       = "No Patients";
        }
    }
 protected void SetNotificationInfo()
 {
     txtStockWarningLevelNotificationEmailAddress.Text = SystemVariableDB.GetByDescr("StockWarningNotificationEmailAddress").Value;
     btnUpdateNotificationInfo.CssClass = "hiddencol";
     btnRevertNotificationInfo.CssClass = "hiddencol";
 }
    public static string Run(bool incDisplay, bool incSending, DateTime date)
    {
        date = date.Date;


        bool   EnableDailyBookingReminderSMS             = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyBookingReminderSMS").Value) == 1;
        bool   EnableDailyBookingReminderEmails          = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDailyBookingReminderEmails").Value) == 1;
        int    NbrDaysAheadToSendDailyBookingReminderSMS = Convert.ToInt32(SystemVariableDB.GetByDescr("NbrDaysAheadToSendDailyBookingReminderSMS").Value);
        string SendDailyBookingReminderText_SMS          = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_SMS").Value;
        string SendDailyBookingReminderText_Email        = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_Email").Value;
        string SendDailyBookingReminderText_EmailSubject = SystemVariableDB.GetByDescr("SendDailyBookingReminderText_EmailSubject").Value;
        string PT_Reminders_HasBothSMSandEmail           = SystemVariableDB.GetByDescr("PT_Reminders_HasBothSMSandEmail").Value;

        date = date.AddDays(NbrDaysAheadToSendDailyBookingReminderSMS - 1);


        Booking[] bookings = BookingDB.GetBetween(date, date.AddDays(1).AddMinutes(-1), null, null, null, null, false, "0", false, null);
        Hashtable patientContactPhoneNbrHash = GetPatientPhoneNbrCache(bookings);
        Hashtable patientContactEmailHash    = GetPatientEmailCache(bookings);
        Hashtable orgContactHash             = GetOrgPhoneNbrCache(bookings);
        Hashtable orgAddrContactHash         = GetOrgAddrCache(bookings);



        decimal balance = SMSCreditDataDB.GetTotal() - SMSHistoryDataDB.GetTotal();
        decimal cost    = Convert.ToDecimal(SystemVariableDB.GetByDescr("SMSPrice").Value);


        string    callerId                 = System.Configuration.ConfigurationManager.AppSettings["SMSTech_callerId"];  // not used here as the callerId will be the org name
        string    countryCode              = System.Configuration.ConfigurationManager.AppSettings["SMSTech_CountryCode"];
        ArrayList messagesToSMS            = new ArrayList();
        ArrayList messagesToEmail          = new ArrayList();
        ArrayList bookingIDsConfirmedSMS   = new ArrayList();
        ArrayList bookingIDsConfirmedEmail = new ArrayList();


        string output           = "<table class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-thick auto_width block_center\" border=\"1\" style=\"border-collapse:collapse;\">";
        int    countWithPatient = 0;

        foreach (Booking booking in bookings)
        {
            if (booking.BookingTypeID != 34)  // only bookings, not days marked off
            {
                continue;
            }

            if (booking.Patient == null || booking.Offering == null)      // prob aged care booking
            {
                continue;
            }

            // Marcus: send sms even if booking is confirmed
            //if (booking.ConfirmedBy != null)  // don't send reminders to those already confirmed
            //    continue;

            // get all info to send via sms or email

            string phoneNumPatient = GetPhoneNbr(patientContactPhoneNbrHash, booking.Patient.Person.EntityID, true);
            if (phoneNumPatient != null)
            {
                phoneNumPatient = phoneNumPatient.StartsWith("0") ? countryCode + phoneNumPatient.Substring(1) : phoneNumPatient;
            }

            string emailPatient = GetEmail(patientContactEmailHash, booking.Patient.Person.EntityID);
            string phoneNumOrg  = GetPhoneNbrs(orgContactHash, booking.Organisation.EntityID);
            string addrOrg      = GetAddr(orgAddrContactHash, booking.Organisation.EntityID);

            string smsText          = GetSMSText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_SMS);
            string emailText        = GetEmailText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_Email);
            string emailSubjectText = GetEmailSubjectText(booking, phoneNumOrg, addrOrg, SendDailyBookingReminderText_EmailSubject);


            // kept just to show their email/phone number exists even though we may not be sending to there due to settings or low balance.
            string phoneNumPatient_Original = phoneNumPatient;
            string emailPatient_Original    = emailPatient;


            // ignore if setting is to not sending sms's or emails
            if (phoneNumPatient != null && !EnableDailyBookingReminderSMS)
            {
                phoneNumPatient = null;
            }
            if (emailPatient != null && !EnableDailyBookingReminderEmails)
            {
                emailPatient = null;
            }

            // if balance too low, can not send by SMS
            if (phoneNumPatient != null && balance < cost)
            {
                phoneNumPatient = null;
            }

            // if has both, then send based on setting
            if (phoneNumPatient != null && emailPatient != null)
            {
                if (PT_Reminders_HasBothSMSandEmail == "Email") // setting is - when both, send only via email
                {
                    phoneNumPatient = null;
                }
                if (PT_Reminders_HasBothSMSandEmail == "SMS")   // setting is - when both, send only via sms
                {
                    emailPatient = null;
                }
            }


            string textToDisplay = string.Empty;
            if (phoneNumPatient != null)
            {
                textToDisplay += "<b>" + smsText.Replace(Environment.NewLine, "<br />") + "</b>";
            }
            if (emailPatient != null)
            {
                textToDisplay += (textToDisplay.Length == 0 ? "" : "<br><hr>") + "<u>" + emailSubjectText + "</u><br /><br />" + emailText;
            }



            // display the info

            string tdTagStart          = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td>"  : "<td>");
            string tdTagStartLeftAlign = phoneNumPatient == null && emailPatient == null ? "<td class=\"nowrap text_left\" style=\"color:grey;\">" : (phoneNumPatient == null ? "<td class=\"text_left\">" : "<td class=\"text_left\">");
            string tdTagEnd            = phoneNumPatient == null && emailPatient == null ? "</td>" : (phoneNumPatient == null ? "</td>" : "</td>");

            output += "<tr>";
            output += tdTagStart + booking.BookingID + tdTagEnd;
            output += tdTagStart + booking.DateStart.ToString("dd-MM-yy") + "<br />" + booking.DateStart.ToString("HH:mm") + " - " + booking.DateEnd.ToString("HH:mm") + tdTagEnd;
            output += tdTagStart + booking.Organisation.Name + "<br />" + (phoneNumOrg == null ? "-- No Phone --" : phoneNumOrg.Replace(",", "<br />").Replace("or", "<br />")) + tdTagEnd;
            output += tdTagStart + booking.Patient.Person.FullnameWithoutMiddlename + "<br />" +
                      (phoneNumPatient_Original == null ? "-- No Mobile --" : "<u>" + phoneNumPatient_Original + "</u>") + "<br />" +
                      (emailPatient_Original == null ? "-- No Email --"  : "<u>" + emailPatient_Original + "</u>") + tdTagEnd;
            output += tdTagStartLeftAlign + textToDisplay + tdTagEnd;
            output += "</tr>";

            countWithPatient++;



            /*
             *  add to lists to sms or email (or both)
             */

            if (phoneNumPatient != null)
            {
                messagesToSMS.Add(new Tuple <int, decimal, string, string, string>(booking.BookingID, cost, phoneNumPatient, smsText, booking.Organisation.Name));
                bookingIDsConfirmedSMS.Add(booking.BookingID);
                if (incSending)
                {
                    balance -= cost;
                }
            }
            if (emailPatient != null)
            {
                messagesToEmail.Add(new Tuple <int, string, string, string, string>(booking.BookingID, booking.Organisation.Name, emailPatient, emailText, emailSubjectText));
                bookingIDsConfirmedEmail.Add(booking.BookingID);
            }


            /*
             * bool sendingAlready = false;
             * if (EnableDailyBookingReminderSMS && phoneNumPatient != null && balance >= cost)
             * {
             *  messagesToSMS.Add(new Tuple<int, decimal, string, string, string>(booking.BookingID, cost, phoneNumPatient, smsText, booking.Organisation.Name));
             *  bookingIDsConfirmedSMS.Add(booking.BookingID);
             *  sendingAlready = true;
             *  if (incSending)
             *      balance -= cost;
             * }
             * if (EnableDailyBookingReminderEmails && emailPatient != null)
             * {
             *  messagesToEmail.Add(new Tuple<int, string, string, string, string>(booking.BookingID, booking.Organisation.Name, emailPatient, emailText, emailSubjectText));
             *  if (!sendingAlready)  // if not already added for sms sending
             *      bookingIDsConfirmedEmail.Add(booking.BookingID);
             * }
             */
        }
        output += "</table>";


        // run the sending and send off reminders -- but only if there was any bookings

        if (incSending && bookings.Length > 0)
        {
            /*
             * run the sendings
             */

            SendSMSes((Tuple <int, decimal, string, string, string>[])messagesToSMS.ToArray(typeof(Tuple <int, decimal, string, string, string>)));
            SendEmails((Tuple <int, string, string, string, string>[])messagesToEmail.ToArray(typeof(Tuple <int, string, string, string, string>)));

            /*
             * if sms or email sent, set booking as confirmed
             */
            BookingDB.UpdateSetConfirmed((int[])bookingIDsConfirmedSMS.ToArray(typeof(int)), 2, -1);
            BookingDB.UpdateSetConfirmed((int[])bookingIDsConfirmedEmail.ToArray(typeof(int)), 3, -1);

            /*
             * send balance warning
             */

            SystemVariables systemVariables            = SystemVariableDB.GetAll();
            string          warningEmail               = systemVariables["SMSCreditNotificationEmailAddress"].Value;
            decimal         warningThreshold           = Convert.ToDecimal(systemVariables["SMSCreditLowBalance_Threshold"].Value);
            bool            checkSMSCreditOutOfBalance = Convert.ToInt32(systemVariables["SMSCreditOutOfBalance_SendEmail"].Value) == 1;
            bool            checkMSCreditLowBalance    = Convert.ToInt32(systemVariables["SMSCreditLowBalance_SendEmail"].Value) == 1;


            if (warningEmail.Length > 0 && checkSMSCreditOutOfBalance && balance < cost)
            {
                SendEmail(
                    warningEmail,
                    "SMS Credit Used Up",
                    "Please note that your SMS credit at mediclinic has been used up. To continue sending, please top up.<br /><br />Best regards,<br />Mediclinic");
            }
            else if (warningEmail.Length > 0 && checkMSCreditLowBalance && balance <= warningThreshold)  // dont send warning low balance if already sending out of credit email
            {
                SendEmail(
                    warningEmail,
                    "SMS Credit Warning - Don't Forget To Top-Up Before It Runs Out",
                    "Hi! Just a friendly reminder that the SMS reminder threshold you set has been reached.<br /> To avoid missing SMS'es being sent, don't forget to top-up before the remainder runs out!<br /><br />Best regards,<br />Mediclinic");
            }
        }

        if (incDisplay)
        {
            return("Count: <b>" + countWithPatient + "</b> &nbsp;&nbsp; [Sending Via SMS: <b>" + messagesToSMS.Count + "</b>] &nbsp;&nbsp; [Sending Via Email: <b>" + messagesToEmail.Count + "</b>] " + "<br /><br />" + output);
        }
        else
        {
            return(string.Empty);
        }
    }
Exemple #28
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!ddlEndDateValidateAllOrNoneSet.IsValid ||
            !ddlStartDateValidateAllOrNoneSet.IsValid ||
            !ddlDOBValidateAllOrNoneSet.IsValid)
        {
            return;
        }

        txtPwd.Attributes["value"] = txtPwd.Text;  // pwd fields is unset on send back to server, so re-set it

        if (GetUrlParamType() == UrlParamType.View)
        {
            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "edit"));
        }
        else if (GetUrlParamType() == UrlParamType.Edit)
        {
            Staff staff = StaffDB.GetByID(Convert.ToInt32(this.lblId.Text));

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text, staff.StaffID))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (staff.Pwd != txtPwd.Text && txtPwd.Text.Length < 6)
            {
                SetErrorMessage(staff.Pwd.Length >= 6 ? "Password must be at least 6 characters" : "New passwords must be at least 6 characters");
                return;
            }

            bool loggedInUserIsStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
            bool loggedInUserIsMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);
            bool setIsStakeholder          = loggedInUserIsStakeholder ? chkIsStakeholder.Checked : staff.IsStakeholder;
            bool setIsMasterAdmin          = loggedInUserIsStakeholder || loggedInUserIsMasterAdmin ? chkIsMasterAdmin.Checked : staff.IsMasterAdmin;

            if (!staff.IsProvider && chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to update them or hit cancel. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }


            if (chkIsProvider.Checked)
            {
                System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

                bool         roleSetAsProvider = false;
                IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                    if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                    {
                        roleSetAsProvider = true;
                    }
                }

                if (!roleSetAsProvider)
                {
                    if (fields.Length == 1)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                        return;
                    }
                    else if (fields.Length == 2)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                        return;
                    }
                    else
                    {
                        string providerFields = string.Empty;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                        }

                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                        return;
                    }
                }
            }



            if (chkIsMasterAdmin.Checked)
            {
                chkIsAdmin.Checked = true;
            }

            PersonDB.Update(staff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), staff.Person.Nickname, ddlGender.SelectedValue, GetDOBFromForm(), DateTime.Now);
            StaffDB.Update(staff.StaffID, staff.Person.PersonID, txtLogin.Text, txtPwd.Text, staff.StaffPosition.StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), staff.CostCentre.CostCentreID,
                           chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                           ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                           setIsStakeholder, setIsMasterAdmin, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, staff.IsExternal,
                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, chkSMSBKs.Checked, chkEmailBKs.Checked);

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text)
            {
                UserDatabaseMapper curDBMapper = UserDatabaseMapperDB.GetByLogin(staff.Login, Session["DB"].ToString());
                if (curDBMapper == null)
                {
                    UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }
                else
                {
                    UserDatabaseMapperDB.Update(curDBMapper.ID, txtLogin.Text, Session["DB"].ToString());
                }
            }

            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view"));
        }
        else if (GetUrlParamType() == UrlParamType.Add)
        {
            if (chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to add them. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }

            if (chkIsProvider.Checked)
            {
                System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

                bool         roleSetAsProvider = false;
                IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                    if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                    {
                        roleSetAsProvider = true;
                    }
                }

                if (!roleSetAsProvider)
                {
                    if (fields.Length == 1)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                        return;
                    }
                    else if (fields.Length == 2)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                        return;
                    }
                    else
                    {
                        string providerFields = string.Empty;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                        }

                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                        return;
                    }
                }
            }

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                lblErrorMessage.Text    = "Login name already in use by another user";
                lblErrorMessage.Visible = true;
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                lblErrorMessage.Text    = "Login name already in use by another user";
                lblErrorMessage.Visible = true;
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            int  person_id    = -1;
            int  staff_id     = -1;
            bool staff_added  = false;
            int  mainDbUserID = -1;

            try
            {
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                bool loggedInUserIsStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
                bool loggedInUserIsMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);
                bool setIsStakeholder          = loggedInUserIsStakeholder ? chkIsStakeholder.Checked : false;
                bool setIsMasterAdmin          = loggedInUserIsStakeholder || loggedInUserIsMasterAdmin ? chkIsMasterAdmin.Checked : false;

                if (chkIsMasterAdmin.Checked)
                {
                    chkIsAdmin.Checked = true;
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, GetDOBFromForm());
                staff_id  = StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), 59,
                                           chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                                           ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                                           setIsStakeholder, setIsMasterAdmin, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, false,
                                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, chkSMSBKs.Checked, chkEmailBKs.Checked);
                staff_added = true;

                string url = Request.RawUrl;
                url = UrlParamModifier.AddEdit(url, "type", "view");
                url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                Response.Redirect(url);
            }
            catch (Exception)
            {
                if (staff_added)
                {
                    string url = Request.RawUrl;
                    url = UrlParamModifier.AddEdit(url, "type", "view");
                    url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                    Response.Redirect(url);
                    return;
                }

                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }

                throw;
            }
        }
        else
        {
            HideTableAndSetErrorMessage();
        }
    }
Exemple #29
0
    public void FillOfferingGrid()
    {
        Booking.InvoiceType invType = InvoiceType;

        decimal GST_Percent  = Convert.ToDecimal(((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["GST_Percent"].Value);
        decimal GST_Modifier = GST_Percent / (decimal)100;

        bool hasGstItems_HC = false;
        bool hasGstItems_PT = false;

        DataTable dt_offering;
        DataTable dt_org_offering = null; // just to get the prices if there is a specific price for this clinic

        try
        {
            if (this.booking == null)
            {
                dt_offering = OrganisationOfferingsDB.GetDataTable_OfferingsByOrg(true, 0);  // get empty datatable
            }
            else
            {
                if (booking.Organisation.OrganisationType.OrganisationTypeGroup.ID == 5) // clinics
                {
                    dt_offering     = OfferingDB.GetDataTable(false, "1,3", "63");
                    dt_org_offering = OrganisationOfferingsDB.GetDataTable_OfferingsByOrg(true, booking.Organisation.OrganisationID, "1,3", "63,89"); // dt_offering = OfferingDB.GetDataTable(1);
                }
                else if (booking.Organisation.OrganisationType.OrganisationTypeGroup.ID == 6)                                                         // aged care
                {
                    dt_offering     = OfferingDB.GetDataTable(false, "3,4", "63");
                    dt_org_offering = OrganisationOfferingsDB.GetDataTable_OfferingsByOrg(true, booking.Organisation.OrganisationID, "3,4", "63,89");  // dt_offering = OfferingDB.GetDataTable(4);
                }
                else
                {
                    throw new Exception("Unknown booking screen type");
                }


                // If row exists in org-offering table, then use that price
                for (int i = 0; i < dt_org_offering.Rows.Count; i++)
                {
                    for (int j = 0; j < dt_offering.Rows.Count; j++)
                    {
                        if (Convert.ToInt32(dt_offering.Rows[j]["o_offering_id"]) == Convert.ToInt32(dt_org_offering.Rows[i]["o_offering_id"]))
                        {
                            dt_offering.Rows[j]["o_default_price"] = dt_org_offering.Rows[i]["o_default_price"];
                        }
                    }
                }
            }


            for (int i = dt_offering.Rows.Count - 1; i >= 0; i--)
            {
                // remove service they are here for
                if (booking.Offering.OfferingID == Convert.ToInt32(dt_offering.Rows[i]["o_offering_id"]))
                {
                    dt_offering.Rows.RemoveAt(i);
                }
                else
                {
                    // if pt pays  invoice, use default price for all (so no change)
                    // if medicare invoice, use default price for all offerings OTHER than the service they are here for (so no change)
                    // if dva      invoice, use dva price for all

                    // Remove this ... and show pt price and hc price on the screen and use that on the data tables
                    //
                    //if (invType == Booking.InvoiceType.DVA)
                    //    dt_offering.Rows[i]["o_default_price"] = dt_offering.Rows[i]["o_dva_charge"];
                }
            }


            // add all products (by invoice type id  1 or 4, and offering_type_ids for only products : "89")
            DataTable dt_products = null;
            if (this.booking == null)
            {
                dt_products = OfferingDB.GetDataTable(false, UserView.GetInstance().IsAgedCareView ? "3,4" : "1,3", "89");
            }
            else
            {
                if (booking.Organisation.OrganisationType.OrganisationTypeGroup.ID == 5)
                {
                    dt_products = OfferingDB.GetDataTable(false, "1,3", "89");
                }
                else if (booking.Organisation.OrganisationType.OrganisationTypeGroup.ID == 6)
                {
                    dt_products = OfferingDB.GetDataTable(false, "3,4", "89");
                }
                else
                {
                    throw new Exception("Unknown booking screen type");
                }

                //
                // If row exists in org-offering table, then use that price
                //
                if (dt_org_offering != null)
                {
                    for (int i = 0; i < dt_org_offering.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt_products.Rows.Count; j++)
                        {
                            if (Convert.ToInt32(dt_products.Rows[j]["o_offering_id"]) == Convert.ToInt32(dt_org_offering.Rows[i]["o_offering_id"]))
                            {
                                dt_products.Rows[j]["o_default_price"] = dt_org_offering.Rows[i]["o_default_price"];
                            }
                        }
                    }
                }
            }


            for (int i = 0; i < dt_products.Rows.Count; i++)
            {
                dt_offering.ImportRow(dt_products.Rows[i]);
            }


            bool invoiceGapPayments = Convert.ToInt32(SystemVariableDB.GetByDescr("InvoiceGapPayments").Value) == 1;

            dt_offering.Columns.Add("hc_paid");
            dt_offering.Columns.Add("pt_price", typeof(decimal));
            dt_offering.Columns.Add("hc_price", typeof(decimal));
            dt_offering.Columns.Add("pt_gst", typeof(decimal));
            dt_offering.Columns.Add("hc_gst", typeof(decimal));
            for (int i = 0; i < dt_offering.Rows.Count; i++)
            {
                bool isGstExempt = Convert.ToBoolean(dt_offering.Rows[i]["o_is_gst_exempt"]);

                string medicare_company_code = dt_offering.Rows[i]["o_medicare_company_code"].ToString();
                string dva_company_code      = dt_offering.Rows[i]["o_dva_company_code"].ToString();
                string tac_company_code      = dt_offering.Rows[i]["o_tac_company_code"].ToString();

                bool incGstOnPTInvoices = IncGstOnInvoices_Private && !isGstExempt;
                bool incGstOnHCInvoices = (invType == Booking.InvoiceType.Medicare && IncGstOnInvoices_MC && !isGstExempt) ||
                                          (invType == Booking.InvoiceType.DVA && IncGstOnInvoices_DVA && !isGstExempt) ||
                                          (invType == Booking.InvoiceType.Insurance && IncGstOnInvoices_Insurance && !isGstExempt);

                dt_offering.Rows[i]["pt_price"] = Convert.ToDecimal(dt_offering.Rows[i]["o_default_price"]);
                dt_offering.Rows[i]["hc_price"] = 0;
                dt_offering.Rows[i]["pt_gst"]   = !incGstOnPTInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["pt_price"]) * GST_Modifier;
                dt_offering.Rows[i]["hc_gst"]   = !incGstOnHCInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["hc_price"]) * GST_Modifier;



                if (invType == Booking.InvoiceType.DVA)
                {
                    dt_offering.Rows[i]["hc_paid"] = dva_company_code.Length > 0;

                    if (dva_company_code.Length > 0)
                    {
                        decimal default_price = Convert.ToDecimal(dt_offering.Rows[i]["o_default_price"]);
                        decimal dva_price     = Convert.ToDecimal(dt_offering.Rows[i]["o_dva_charge"]);

                        dt_offering.Rows[i]["pt_price"] = (invoiceGapPayments && default_price > dva_price) ? default_price - dva_price : 0;
                        dt_offering.Rows[i]["hc_price"] = dva_price;
                        dt_offering.Rows[i]["pt_gst"]   = !incGstOnPTInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["pt_price"]) * GST_Modifier;
                        dt_offering.Rows[i]["hc_gst"]   = !incGstOnHCInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["hc_price"]) * GST_Modifier;
                    }
                }
                if (invType == Booking.InvoiceType.Insurance)
                {
                    dt_offering.Rows[i]["hc_paid"] = tac_company_code.Length > 0;

                    //if (tac_company_code.Length > 0)
                    //{
                    decimal default_price = Convert.ToDecimal(dt_offering.Rows[i]["o_default_price"]);
                    decimal tac_price     = (tac_company_code.Length > 0) ? Convert.ToDecimal(dt_offering.Rows[i]["o_tac_charge"]) : default_price;

                    dt_offering.Rows[i]["pt_price"] = (invoiceGapPayments && default_price > tac_price) ? default_price - tac_price : 0;
                    dt_offering.Rows[i]["hc_price"] = tac_price;
                    dt_offering.Rows[i]["pt_gst"]   = !incGstOnPTInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["pt_price"]) * GST_Modifier;
                    dt_offering.Rows[i]["hc_gst"]   = !incGstOnHCInvoices ? 0 : Convert.ToDecimal(dt_offering.Rows[i]["hc_price"]) * GST_Modifier;
                    //}
                }
                else if (InvoiceType == Booking.InvoiceType.Medicare)
                {
                    dt_offering.Rows[i]["hc_paid"] = false; // medicare invoice - all items to add beyond booking offering are privately invoiced
                }
                else
                {
                    dt_offering.Rows[i]["hc_paid"] = false;
                }


                if (!isGstExempt && Convert.ToDecimal(dt_offering.Rows[i]["hc_gst"]) > 0)
                {
                    hasGstItems_HC = true;
                }
                if (!isGstExempt && Convert.ToDecimal(dt_offering.Rows[i]["pt_gst"]) > 0)
                {
                    hasGstItems_PT = true;
                }
            }
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
            //return;
            throw;
        }

        Session["data_offering"] = dt_offering;


        if (!hasGstItems_HC && !hasGstItems_PT)
        {
            GrdOffering.Columns[7].Visible = false;
            GrdOffering.Columns[5].Visible = false;
        }


        if (dt_offering.Rows.Count > 0)
        {
            if (IsPostBack && Session["sortExpression_Offering"] != null && Session["sortExpression_Offering"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt_offering);
                dataView.Sort          = Session["sortExpression_Offering"].ToString();
                GrdOffering.DataSource = dataView;
            }
            else
            {
                GrdOffering.DataSource = dt_offering;
            }


            try
            {
                GrdOffering.DataBind();



                // add items for javascript live search so can have
                // dropdown that when chosing an item, it clicks the right button

                string fieldsSep = "[[fieldsSep]]";
                string itemSep   = "[[itemSep]]";

                string output = string.Empty;
                for (int i = 0; i < GrdOffering.Rows.Count; i++)
                {
                    Label  lblShortName = (Label)GrdOffering.Rows[i].FindControl("lblShortName");
                    Button btnAdd       = (Button)GrdOffering.Rows[i].FindControl("btnAdd");
                    output += (i == 0 ? "" : itemSep) + lblShortName.Text + fieldsSep + btnAdd.ClientID;
                }

                hiddenItemList.Value = output;

                // end live search data
            }
            catch (Exception)
            {
                //SetErrorMessage("", ex.ToString()); // already should be showing in page containing this control

                this.HideElementsForError();
                throw;
            }
        }
        else
        {
            dt_offering.Rows.Add(dt_offering.NewRow());
            GrdOffering.DataSource = dt_offering;
            GrdOffering.DataBind();

            int TotalColumns = GrdOffering.Rows[0].Cells.Count;
            GrdOffering.Rows[0].Cells.Clear();
            GrdOffering.Rows[0].Cells.Add(new TableCell());
            GrdOffering.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdOffering.Rows[0].Cells[0].Text       = "No Items Found";
        }
    }
Exemple #30
0
    public DataTable GetSelectedList()
    {
        DataTable dt_selected_list = Session["data_selected"] as DataTable;

        string areaTreated = string.Empty;

        if (InvoiceType == Booking.InvoiceType.DVA || InvoiceType == Booking.InvoiceType.Insurance)
        {
            areaTreated = HealthCardDB.GetActiveByPatientID(Booking.Patient.PatientID).AreaTreated;
        }

        if (dt_selected_list == null)
        {
            dt_selected_list = new DataTable();
            dt_selected_list.Columns.Add(new DataColumn("offering_id"));
            dt_selected_list.Columns.Add(new DataColumn("hc_paid"));
            dt_selected_list.Columns.Add(new DataColumn("short_name"));
            dt_selected_list.Columns.Add(new DataColumn("name"));
            dt_selected_list.Columns.Add(new DataColumn("area_treated"));
            dt_selected_list.Columns.Add(new DataColumn("service_reference"));
            dt_selected_list.Columns.Add(new DataColumn("show_area_treated", typeof(Boolean)));
            dt_selected_list.Columns.Add(new DataColumn("show_service_reference", typeof(Boolean)));
            dt_selected_list.Columns.Add(new DataColumn("default_price"));
            dt_selected_list.Columns.Add(new DataColumn("pt_price"));                // added
            dt_selected_list.Columns.Add(new DataColumn("hc_price"));                // added
            dt_selected_list.Columns.Add(new DataColumn("pt_gst"));                  // added
            dt_selected_list.Columns.Add(new DataColumn("hc_gst"));                  // added
            dt_selected_list.Columns.Add(new DataColumn("quantity"));
            dt_selected_list.Columns.Add(new DataColumn("total_line_price"));
            dt_selected_list.Columns.Add(new DataColumn("total_line_gst"));
            dt_selected_list.Columns.Add(new DataColumn("total_pt_price"));          // added
            dt_selected_list.Columns.Add(new DataColumn("total_hc_price"));          // added
            dt_selected_list.Columns.Add(new DataColumn("total_pt_gst"));            // added
            dt_selected_list.Columns.Add(new DataColumn("total_hc_gst"));            // added
            dt_selected_list.Columns.Add(new DataColumn("on_order", typeof(Boolean)));


            if (this.booking != null)
            {
                Booking.InvoiceType invType = InvoiceType;

                Offering orgOffering = OrganisationOfferingsDB.GetOfferingByOrgAndOffering(this.booking.Organisation.OrganisationID, this.booking.Offering.OfferingID);
                if (orgOffering == null)
                {
                    orgOffering = this.booking.Offering;
                }

                bool    invoiceGapPayments = Convert.ToInt32(SystemVariableDB.GetByDescr("InvoiceGapPayments").Value) == 1;
                decimal GST_Percent        = Convert.ToDecimal(((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["GST_Percent"].Value);
                decimal GST_Modifier       = GST_Percent / (decimal)100;

                bool incGstOnPTInvoices = IncGstOnInvoices_Private && !orgOffering.IsGstExempt;
                bool incGstOnHCInvoices = (invType == Booking.InvoiceType.Medicare && IncGstOnInvoices_MC && !orgOffering.IsGstExempt) ||
                                          (invType == Booking.InvoiceType.DVA && IncGstOnInvoices_DVA && !orgOffering.IsGstExempt) ||
                                          (invType == Booking.InvoiceType.Insurance && IncGstOnInvoices_Insurance && !orgOffering.IsGstExempt);


                decimal pt_price = orgOffering.DefaultPrice;
                decimal hc_price = 0;
                decimal pt_tax   = !incGstOnPTInvoices ? 0 : pt_price * GST_Modifier;
                decimal hc_tax   = !incGstOnHCInvoices ? 0 : hc_price * GST_Modifier;

                if (invType == Booking.InvoiceType.Medicare)
                {
                    pt_price = invoiceGapPayments && orgOffering.DefaultPrice > orgOffering.MedicareCharge ? orgOffering.DefaultPrice - orgOffering.MedicareCharge : 0;
                    hc_price = orgOffering.MedicareCharge;
                    pt_tax   = !incGstOnPTInvoices ? 0 : pt_price * GST_Modifier;
                    hc_tax   = !incGstOnHCInvoices ? 0 : hc_price * GST_Modifier;
                }
                if (invType == Booking.InvoiceType.DVA)
                {
                    pt_price = invoiceGapPayments && orgOffering.DefaultPrice > orgOffering.DvaCharge ? orgOffering.DefaultPrice - orgOffering.DvaCharge : 0;
                    hc_price = orgOffering.DvaCharge;
                    pt_tax   = !incGstOnPTInvoices ? 0 : pt_price * GST_Modifier;
                    hc_tax   = !incGstOnHCInvoices ? 0 : hc_price * GST_Modifier;
                }
                if (invType == Booking.InvoiceType.Insurance)
                {
                    hc_price = orgOffering.TacCompanyCode.Length > 0 ? orgOffering.TacCharge : orgOffering.DefaultPrice;
                    pt_price = invoiceGapPayments && orgOffering.DefaultPrice > hc_price ? orgOffering.DefaultPrice - hc_price : 0;
                    pt_tax   = !incGstOnPTInvoices ? 0 : pt_price * GST_Modifier;
                    hc_tax   = !incGstOnHCInvoices ? 0 : hc_price * GST_Modifier;
                }


                DataRow row = dt_selected_list.NewRow();
                row["offering_id"]            = booking.Offering.OfferingID;
                row["hc_paid"]                = (this.InvoiceType == Booking.InvoiceType.DVA || this.InvoiceType == Booking.InvoiceType.Medicare);
                row["short_name"]             = booking.Offering.ShortName;
                row["name"]                   = booking.Offering.Name;
                row["area_treated"]           = areaTreated;
                row["service_reference"]      = "";
                row["show_area_treated"]      = InvoiceType == Booking.InvoiceType.DVA || InvoiceType == Booking.InvoiceType.Insurance;
                row["show_service_reference"] = InvoiceType == Booking.InvoiceType.Insurance;
                row["default_price"]          = row["total_line_price"] = orgOffering.DefaultPrice;
                row["pt_price"]               = row["total_pt_price"] = pt_price;                      // added
                row["pt_gst"]                 = row["total_pt_gst"] = pt_tax;                          // added
                row["hc_price"]               = row["total_hc_price"] = hc_price;                      // added
                row["hc_gst"]                 = row["total_hc_gst"] = hc_tax;                          // added
                row["quantity"]               = "1";
                row["on_order"]               = false;
                dt_selected_list.Rows.Add(row);
            }

            Session["data_selected"] = dt_selected_list;
        }

        if (dt_selected_list.Rows.Count == 1 && dt_selected_list.Rows[0][0] == DBNull.Value)
        {
            dt_selected_list.Rows.RemoveAt(0);
        }

        return(dt_selected_list);
    }