protected void UpdateList()
    {
        Staff        staff = IsValidFormStaffID() ? StaffDB.GetByID(GetFormStaffID()) : null;
        Organisation org   = IsValidFormOrgID()   ? OrganisationDB.GetByID(GetFormOrgID()) : null;

        UpdateList(org, staff);
    }
Exemple #2
0
    protected void GrdRegistration_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId             = (Label)GrdRegistration.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlOrganisation   = (DropDownList)GrdRegistration.Rows[e.RowIndex].FindControl("ddlOrganisation");
        TextBox      txtProviderNumber = (TextBox)GrdRegistration.Rows[e.RowIndex].FindControl("txtProviderNumber");
        CheckBox     chkMainProvider   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkMainProvider");
        CheckBox     chkIncMondays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncMondays");
        CheckBox     chkIncTuesdays    = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncTuesdays");
        CheckBox     chkIncWednesdays  = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncWednesdays");
        CheckBox     chkIncThursdays   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncThursdays");
        CheckBox     chkIncFridays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncFridays");
        CheckBox     chkIncSaturdays   = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncSaturdays");
        CheckBox     chkIncSundays     = (CheckBox)GrdRegistration.Rows[e.RowIndex].FindControl("chkIncSundays");


        Staff staff = StaffDB.GetByID(GetFormID());

        if (staff == null)
        {
            HideTableAndSetErrorMessage("");
            return;
        }

        RegisterStaffDB.Update(Convert.ToInt32(lblId.Text), Convert.ToInt32(ddlOrganisation.SelectedValue), staff.StaffID, txtProviderNumber.Text, chkMainProvider.Checked,
                               !chkIncSundays.Checked, !chkIncMondays.Checked, !chkIncTuesdays.Checked, !chkIncWednesdays.Checked, !chkIncThursdays.Checked, !chkIncFridays.Checked, !chkIncSaturdays.Checked);
        if (chkMainProvider.Checked)
        {
            RegisterStaffDB.UpdateAllOtherStaffAsNotMainProviders(Convert.ToInt32(ddlOrganisation.SelectedValue), staff.StaffID);
        }

        GrdRegistration.EditIndex = -1;
        FillGrid();
    }
Exemple #3
0
    protected void lnkBackToCallCenter_Click(object sender, EventArgs e)
    {
        if (Session == null || Session["PreviousDB"] == null)
        {
            Utilities.LogoutV2(Session, Response, Request);
            return;
        }

        Session["DB"] = (string)Session["PreviousDB"];
        Session["SystemVariables"] = SystemVariableDB.GetAll();

        // Set system staff variables of external staff member 'Call Center'
        Staff staff = StaffDB.GetByID(Convert.ToInt32(Session["PreviousStaffID"]));

        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;

        Site site = SiteDB.GetByID(Convert.ToInt32(Session["PreviousSiteID"]));

        Session["SiteID"]         = site.SiteID;
        Session["SiteName"]       = site.Name;
        Session["SiteIsClinic"]   = site.SiteType.ID == 1;
        Session["SiteIsAgedCare"] = site.SiteType.ID == 2;
        Session["SiteIsGP"]       = site.SiteType.ID == 3;
        Session["SiteTypeID"]     = site.SiteType.ID;
        Session["SiteTypeDescr"]  = site.SiteType.Descr;

        Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1;



        Session.Remove("PreviousDB");
        Session.Remove("PreviousStaffID");
        Session.Remove("PreviousSiteID");


        // Set OrgID in session as external user has OrgID set
        Session.Remove("OrgID");
        Session.Remove("OrgName");

        // Remove patient list session data for pt searches
        Session.Remove("patientinfo_data");
        Session.Remove("patientlist_data");
        Session.Remove("patientlist_sortexpression");
        Session.Remove("patientinfo_sortexpression");

        // Go to call center page
        Response.Redirect("~/CallCenterV2.aspx", false);
        return;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            main_content.Style["background"] = (Session["SystemVariables"] == null) ? "url(../imagesV2/login_bg.png) center top no-repeat #EDEDED" : "url(../imagesV2/" + ((SystemVariables)Session["SystemVariables"])["MainLogoBackground"].Value + ") center top no-repeat #EDEDED";
        }

        bool showPageHeader = Request.QueryString["show_header"] == null || Request.QueryString["show_header"] == "1";

        if (!showPageHeader)
        {
            Utilities.UpdatePageHeaderV2(Page.Master, true);
        }

        Staff     staff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
        DataTable dt    = StaffSiteRestrictionDB.GetDataTable_SitesNotRestricted(staff.StaffID, -1, false);

        lstSites.DataSource = dt;
        lstSites.DataBind();

        lblNoSitesMessage.Visible = dt.Rows.Count == 0;


        if (!IsPostBack)
        {
            if (dt.Rows.Count == 1)
            {
                Session["OrgID"]          = null;
                Session["OrgName"]        = null;
                Session["IsMultipleOrgs"] = false;
                Select(Convert.ToInt32(dt.Rows[0]["site_id"]));
            }
            else if (dt.Rows.Count == 2 && Session["SiteID"] != null) // if already in a site, just switch to the other one.
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Session["OrgID"]          = null;
                    Session["OrgName"]        = null;
                    Session["IsMultipleOrgs"] = false;
                    if (Convert.ToInt32(dt.Rows[i]["site_id"]) != Convert.ToInt32(Session["SiteID"]))
                    {
                        Select(Convert.ToInt32(dt.Rows[i]["site_id"]));
                        return;
                    }
                }
            }
        }
    }
    protected string GetStaffProviderNumber(Hashtable bulkRegisterStaffHash, Hashtable bulkStaffHash, Hashtable bulkSites, Invoice invoice)
    {
        bool isClinicSite = ((Site)bulkSites[invoice.Site.SiteID]).SiteType.ID == 1;

        if (!isClinicSite)       // aged care use prov number from staff table
        {
            // return invoice.Booking.Provider.ProviderNumber; // doesnt have all provider info loaded from the db

            return((bulkStaffHash != null) ?
                   ((Staff)bulkStaffHash[invoice.Booking.Provider.StaffID]).ProviderNumber :
                   StaffDB.GetByID(invoice.Booking.Provider.StaffID).ProviderNumber);
        }
        else  // clinic use prov number specific to that clinic
        {
            if (bulkRegisterStaffHash != null)  // use cached bulk preload to avoid excess db calls
            {
                if (bulkRegisterStaffHash[new Hashtable2D.Key(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID)] == null)
                {
                    // normally doesn't pull back this info, so retrieve it for error info
                    //invoice.Booking.Provider = StaffDB.GetByID(invoice.Booking.Provider.StaffID);
                    //invoice.Booking.Organisation = OrganisationDB.GetByID(invoice.Booking.Organisation.OrganisationID);
                    //string msg = @"For invoice " + invoice.InvoiceID + @" - can not get provider number for <br />&nbsp;&nbsp;" + invoice.Booking.Provider.Person.FullnameWithoutMiddlename + @" (StaffID: " + invoice.Booking.Provider.StaffID + @")<br />at<br />&nbsp;&nbsp;" + invoice.Booking.Organisation.Name + @" (OrgID: " + invoice.Booking.Organisation.OrganisationID + @")<br />becuase they are not registered to this clinic, and the provider number for clinic invoices is stored there.";
                    //throw new CustomMessageException(msg);


                    // Marcus wants it generated with empty provider number, and when rejected, they will fix it
                    return(string.Empty);
                }
                RegisterStaff regStaff = (RegisterStaff)bulkRegisterStaffHash[new Hashtable2D.Key(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID)];
                return(regStaff.ProviderNumber);
            }
            else
            {
                RegisterStaff regStaff = RegisterStaffDB.GetByStaffIDAndOrganisationID(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID);
                if (regStaff == null)
                {
                    //string msg = @"For invoice " + invoice.InvoiceID + @" - can not get provider number for <br />&nbsp;&nbsp;" + invoice.Booking.Provider.Person.FullnameWithoutMiddlename + @" (StaffID: " + invoice.Booking.Provider.StaffID + @")<br />at<br />&nbsp;&nbsp;" + invoice.Booking.Organisation.Name + @" (OrgID: " + invoice.Booking.Organisation.OrganisationID + @")<br />becuase they are not registered to this clinic, and the provider number for clinic invoices is stored there.";
                    //throw new CustomMessageException(msg);


                    // Marcus wants it generated with empty provider number, and when rejected, they will fix it
                    return(string.Empty);
                }
                return(regStaff.ProviderNumber);
            }
        }
    }
Exemple #6
0
    protected void GetClashOneTimeBooking()
    {
        string org_id          = Request.QueryString["org"];
        string staff_id        = Request.QueryString["staff"];
        string booking_id      = Request.QueryString["edit_booking_id"];
        string booking_type_id = Request.QueryString["booking_type_id"];

        string start_datetime = Request.QueryString["start_datetime"];
        string end_datetime   = Request.QueryString["end_datetime"];


        if (start_datetime == null || !Regex.IsMatch(start_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            end_datetime == null || !Regex.IsMatch(end_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            org_id == null || !Regex.IsMatch(org_id, @"^\-?\d+$") ||
            staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$") ||
            booking_id == null || !Regex.IsMatch(booking_id, @"^\-?\d+$"))
        {
            throw new CustomMessageException();
        }

        Organisation org     = OrganisationDB.GetByID(Convert.ToInt32(org_id));
        Staff        staff   = StaffDB.GetByID(Convert.ToInt32(staff_id));
        Booking      booking = booking_id == "-1" ? null : BookingDB.GetByID(Convert.ToInt32(booking_id));

        if (booking != null && booking_type_id == "-1")
        {
            booking_type_id = booking.BookingTypeID.ToString();
        }

        if ((org_id != "0" && org == null) ||
            (staff_id != "-1" && staff == null) ||
            (booking_id != "-1" && booking == null) ||
            (booking_type_id == null || (booking_type_id != "34" && booking_type_id != "340" && booking_type_id != "341" && booking_type_id != "342")))
        {
            throw new CustomMessageException();
        }

        DateTime startDateTime = ConvertStringToDateTime(start_datetime);
        DateTime endDateTime   = ConvertStringToDateTime(end_datetime);

        Booking[] bookings            = BookingDB.GetToCheckOverlap_OneTime(startDateTime, endDateTime, staff, org, booking_type_id == "342", true, false);
        Booking[] overlappingBookings = Booking.GetOverlappingBookings(bookings, startDateTime, endDateTime, booking);
        Response.Write(GetLinks(overlappingBookings));
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            if (Session == null || Session["DB"] == null)
            {
                throw new SessionTimedOutException();
            }

            string staff_id = Request.QueryString["staff"];
            if (staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException();
            }

            Staff staff = StaffDB.GetByID(Convert.ToInt32(staff_id));
            if (staff_id == "-1" || staff == null)
            {
                throw new CustomMessageException();
            }

            string fieldsSep  = "<<sep>>";
            string serialized =
                staff.Person.FullnameWithoutMiddlename + fieldsSep +
                staff.Field.ID + fieldsSep +
                staff.Field.Descr + fieldsSep;

            Response.Write(serialized);
        }
        catch (SessionTimedOutException)
        {
            Utilities.UnsetSessionVariables();
            Response.Write("SessionTimedOutException");
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "please contact system administrator."));
        }
    }
    protected DataTable GetPatientDataTable(int staff_id)
    {
        Staff staff = StaffDB.GetByID(staff_id);

        Hashtable staffHashOriginal = StaffDB.GetAllInHashtable(true, true, true, false);
        Hashtable staffHash         = new Hashtable();

        foreach (Staff s in staffHashOriginal.Values)
        {
            staffHash[s.Person.PersonID] = s;
        }

        DataTable tbl = PatientDB.GetPatientsAddedByStaff(staff_id, GetFromDate(), GetToDate());


        // sort by most common referrer
        tbl.Columns.Add("referrer_count", typeof(int));
        tbl.Columns.Add("added_by_name", typeof(String));
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            int refCount = 0;
            if (tbl.Rows[i]["referrer_info_referrer_id"] != DBNull.Value)
            {
                for (int j = 0; j < tbl.Rows.Count; j++)
                {
                    if (tbl.Rows[j]["referrer_info_referrer_id"] != DBNull.Value && Convert.ToInt32(tbl.Rows[j]["referrer_info_referrer_id"]) == Convert.ToInt32(tbl.Rows[i]["referrer_info_referrer_id"]))
                    {
                        refCount++;
                    }
                }
            }

            tbl.Rows[i]["referrer_count"] = refCount;
            tbl.Rows[i]["added_by_name"]  = staff.Person.FullnameWithoutMiddlename;
        }
        tbl.DefaultView.Sort = "referrer_count DESC, referrer_info_surname, referrer_info_firstname, surname, firstname, middlename";
        tbl = tbl.DefaultView.ToTable();

        return(tbl);
    }
    protected void SetUpGUI()
    {
        ddlStaff.Items.Clear();
        ddlStaff.Items.Add(new ListItem("All Providers", "-1"));
        DataTable dtStaff = StaffDB.GetDataTable();

        for (int i = 0; i < dtStaff.Rows.Count; i++)
        {
            if (!Convert.ToBoolean(dtStaff.Rows[i]["staff_is_fired"]) && Convert.ToBoolean(dtStaff.Rows[i]["staff_is_provider"]))
            {
                ddlStaff.Items.Add(new ListItem(dtStaff.Rows[i]["person_firstname"].ToString() + " " + dtStaff.Rows[i]["person_surname"].ToString(), dtStaff.Rows[i]["staff_staff_id"].ToString()));
            }
        }

        ddlOfferings.Style["max-width"] = "375px";
        ddlOfferings.Items.Clear();
        ddlOfferings.Items.Add(new ListItem("All Offerings", "-1"));
        DataTable dtOfferings = OfferingDB.GetDataTable(false, "1,3", "63,89");

        for (int i = 0; i < dtOfferings.Rows.Count; i++)
        {
            if (!Convert.ToBoolean(dtOfferings.Rows[i]["o_is_deleted"]))
            {
                ddlOfferings.Items.Add(new ListItem(dtOfferings.Rows[i]["o_name"].ToString(), dtOfferings.Rows[i]["o_offering_id"].ToString()));
            }
        }

        if (IsValidFormStaffID())
        {
            ddlStaff.SelectedValue = StaffDB.GetByID(GetFormStaffID()).StaffID.ToString();
        }
        if (IsValidFormOfferingID())
        {
            ddlOfferings.SelectedValue = OfferingDB.GetByID(GetFormOfferingID()).OfferingID.ToString();
        }
    }
Exemple #10
0
    protected void SetupGUI()
    {
        chkIncMedicare.Checked   = IsValidFormIncMedicare()   ? GetFormIncMedicare(false)   : false;
        chkIncDVA.Checked        = IsValidFormIncDVA()        ? GetFormIncDVA(false)        : false;
        chkIncPrivate.Checked    = IsValidFormIncPrivate()    ? GetFormIncPrivate(false)    : true;
        chkIncReconciled.Checked = IsValidFormIncReconciled() ? GetFormIncReconciled(false) : true;


        UserView userView = UserView.GetInstance();

        ddlOrgs.Style["width"] = "300px";
        ddlOrgs.Items.Clear();
        ddlOrgs.Items.Add(new ListItem("All " + (userView.IsAgedCareView ? "Facilities" : "Clinics"), (-1).ToString()));
        foreach (Organisation curOrg in OrganisationDB.GetAll(false, true, !userView.IsClinicView && !userView.IsGPView, !userView.IsAgedCareView, true, true))
        {
            ddlOrgs.Items.Add(new ListItem(curOrg.Name, curOrg.OrganisationID.ToString()));
        }

        ddlProviders.Style["width"] = "300px";
        ddlProviders.Items.Clear();
        ddlProviders.Items.Add(new ListItem("All Staff", (-1).ToString()));
        foreach (Staff curProv in StaffDB.GetAll())
        {
            ddlProviders.Items.Add(new ListItem(curProv.Person.FullnameWithoutMiddlename, curProv.StaffID.ToString()));
        }

        if (IsValidFormOrgID())
        {
            Organisation org = OrganisationDB.GetByID(GetFormOrgID());
            if (org != null)
            {
                ddlOrgs.SelectedValue = org.OrganisationID.ToString();
            }
        }

        if (!UserView.GetInstance().IsAdminView)
        {
            providerRow.Visible = false;

            Staff provider = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
            if (provider != null)
            {
                ddlProviders.SelectedValue = provider.StaffID.ToString();
            }
        }
        else
        {
            if (IsValidFormProviderID())
            {
                Staff provider = StaffDB.GetByID(GetFormProviderID());
                if (provider != null)
                {
                    ddlProviders.SelectedValue = provider.StaffID.ToString();
                }
            }
        }

        ddlReceiptPaymentType.Style["width"] = "300px";
        DataTable paymentTypes = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "ReceiptPaymentType", "", "descr", "receipt_payment_type_id,descr");

        ddlReceiptPaymentType.Items.Add(new ListItem("All Payment Types", "-1"));
        for (int i = 0; i < paymentTypes.Rows.Count; i++)
        {
            ddlReceiptPaymentType.Items.Add(new ListItem(paymentTypes.Rows[i]["descr"].ToString(), paymentTypes.Rows[i]["receipt_payment_type_id"].ToString()));
        }

        if (IsValidFormPaymentType())
        {
            ddlReceiptPaymentType.SelectedValue = GetFormPaymentType(false).ToString();
        }


        txtStartDate.Text = IsValidFormStartDate() ? (GetFormStartDate(false) == DateTime.MinValue ? "" : GetFormStartDate(false).ToString("dd-MM-yyyy")) : DateTime.Today.ToString("dd-MM-yyyy");
        txtEndDate.Text   = IsValidFormEndDate()   ? (GetFormEndDate(false) == DateTime.MinValue ? "" : GetFormEndDate(false).ToString("dd-MM-yyyy"))   : DateTime.Today.ToString("dd-MM-yyyy");

        txtStartDate_Picker.OnClientClick = "displayDatePicker('txtStartDate', this, 'dmy', '-'); return false;";
        txtEndDate_Picker.OnClientClick   = "displayDatePicker('txtEndDate',   this, 'dmy', '-'); return false;";
    }
    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      txtLogin  = (TextBox)GrdStaff.FooterRow.FindControl("txtNewLogin");
            TextBox      txtPwd    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewPwd");
            DropDownList ddlStatus = (DropDownList)GrdStaff.FooterRow.FindControl("ddlStatus");


            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 = DateTime.MinValue;

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

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

                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, 0, 59,
                               false, "", "",
                               ddlStatus.SelectedValue == "Inactive", false, 0,
                               false, false, false, false, false, true,
                               DateTime.Today, DateTime.MinValue, "", false, false);

                FillGrid();
            }
            catch (Exception)
            {
                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }
            }
        }
    }
    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");

        TextBox      txtLogin  = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtLogin");
        TextBox      txtPwd    = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtPwd");
        DropDownList ddlStatus = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlStatus");


        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["externalstaffinfo_data"] as DataTable;

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



        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, staff.Person.Dob, DateTime.Now);
        StaffDB.Update(staff_id, person_id, txtLogin.Text, txtPwd.Text, Convert.ToInt32(row["staff_position_id"]), staff.Field.ID, staff.CostCentre.CostCentreID,
                       staff.IsContractor, staff.Tfn, staff.ProviderNumber,
                       ddlStatus.SelectedValue == "Inactive", staff.IsCommission, staff.CommissionPercent,
                       staff.IsStakeholder, staff.IsMasterAdmin, staff.IsAdmin, staff.IsPrincipal, staff.IsProvider, 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(), staff.EnableDailyReminderSMS, staff.EnableDailyReminderEmail);

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


        GrdStaff.EditIndex = -1;
        FillGrid();
    }
Exemple #13
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);
                }
            }
        }
    }
    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 DataTable SetBookingsList(Staff staff = null)
    {
        if (txtStartDate.Text.Length > 0 && !Utilities.IsValidDate(txtStartDate.Text, "dd-mm-yyyy"))
        {
            SetErrorMessage("Start date must be empty or valid and of the format dd-mm-yyyy");
            return(null);
        }
        if (txtEndDate.Text.Length > 0 && !Utilities.IsValidDate(txtEndDate.Text, "dd-mm-yyyy"))
        {
            SetErrorMessage("End date must be empty or valid and of the format dd-mm-yyyy");
            return(null);
        }
        DateTime startDate = txtStartDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtStartDate.Text, "dd-mm-yyyy");
        DateTime endDate   = txtEndDate.Text.Length == 0 ? DateTime.MinValue : Utilities.GetDate(txtEndDate.Text, "dd-mm-yyyy");

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

        if (staff == null)
        {
            staff = StaffDB.GetByID(GetFormID());
        }



        DataTable tblBookingList = BookingDB.GetDataTable_Between(startDate, endDate, null, null, null, staff, true);

        int[] booking_ids = new int[tblBookingList.Rows.Count];
        for (int i = 0; i < tblBookingList.Rows.Count; i++)
        {
            booking_ids[i] = Convert.ToInt32(tblBookingList.Rows[i]["booking_booking_id"]);
        }
        Hashtable changeHistoryHash = BookingDB.GetChangeHistoryCountHash(booking_ids);

        lblBookingListCount.Text = "(" + tblBookingList.Rows.Count + ")";
        if (tblBookingList.Rows.Count == 0)
        {
            lblBookingsList_NoRowsMessage.Visible = true;
            pnlBookingsList.Visible = false;
        }
        else
        {
            lblBookingsList_NoRowsMessage.Visible = false;
            pnlBookingsList.Visible = true;


            System.Collections.Hashtable staffHash            = StaffDB.GetAllInHashtable(true, true, true, false);
            System.Collections.ArrayList bookingsWithInvoices = new System.Collections.ArrayList();


            tblBookingList.Columns.Add("notes_text", typeof(string));
            tblBookingList.Columns.Add("invoice_text", typeof(string));
            tblBookingList.Columns.Add("booking_url", typeof(string));
            tblBookingList.Columns.Add("hide_booking_link", typeof(Boolean));
            tblBookingList.Columns.Add("show_invoice_row", typeof(int));
            tblBookingList.Columns.Add("show_notes_row", typeof(int));
            tblBookingList.Columns.Add("show_printletter_row", typeof(int));
            tblBookingList.Columns.Add("show_bookingsheet_row", typeof(int));
            tblBookingList.Columns.Add("inv_type_text", typeof(string));
            tblBookingList.Columns.Add("inv_outstanding_text", typeof(string));
            tblBookingList.Columns.Add("added_by_deleted_by_row", typeof(string));
            tblBookingList.Columns.Add("booking_change_history_link", typeof(string));
            tblBookingList.Columns.Add("hide_change_history_link", typeof(Boolean));
            tblBookingList.Columns.Add("show_change_history_row", typeof(string));
            bool hasInvoiceRows      = false;
            bool hasNotesRows        = false;
            bool hasPrintLetterRows  = false;
            bool hasBookingSheetRows = false;
            for (int i = 0; i < tblBookingList.Rows.Count; i++)
            {
                Booking curBooking = BookingDB.LoadFull(tblBookingList.Rows[i]);

                tblBookingList.Rows[i]["notes_text"] = Note.GetPopupLinkTextV2(15, curBooking.EntityID, curBooking.NoteCount > 0, true, 1050, 530, "images/notes-bw-24.jpg", "images/notes-24.png", "btnUpdateBookingList.click()");

                bool canSeeInvoiceInfo = userView.IsAdminView || userView.IsPrincipal || (curBooking.Provider != null && curBooking.Provider.StaffID == loggedInStaffID && curBooking.DateStart > DateTime.Today.AddMonths(-2));
                if (canSeeInvoiceInfo && Convert.ToInt32(tblBookingList.Rows[i]["booking_inv_count"]) > 0)
                {
                    string onclick = @"onclick=""javascript:window.showModalDialog('Invoice_ViewV2.aspx?booking_id=" + curBooking.BookingID + @"', '', 'dialogWidth:820px;dialogHeight:860px;center:yes;resizable:no; scroll:no');return false;""";
                    tblBookingList.Rows[i]["invoice_text"] = "<a " + onclick + " href=\"\">View Inv.</a>";

                    if (curBooking.DateDeleted == DateTime.MinValue && curBooking.DeletedBy == null)
                    {
                        hasInvoiceRows = true;
                    }

                    bookingsWithInvoices.Add(curBooking.BookingID);
                }
                else
                {
                    tblBookingList.Rows[i]["invoice_text"] = "";
                }

                tblBookingList.Rows[i]["hide_booking_link"] = !((userView.IsClinicView && curBooking.Organisation.OrganisationType.OrganisationTypeID == 218) ||
                                                                (userView.IsAgedCareView && (new List <int> {
                    139, 367, 372
                }).Contains(curBooking.Organisation.OrganisationType.OrganisationTypeID)));

                if (curBooking.DateDeleted == DateTime.MinValue && curBooking.DeletedBy == null)
                {
                    hasNotesRows       = true;
                    hasPrintLetterRows = true;
                    if (!Convert.ToBoolean(tblBookingList.Rows[i]["hide_booking_link"]))
                    {
                        hasBookingSheetRows = true;
                    }
                }

                string urlParams = string.Empty;
                if (curBooking.Organisation != null)
                {
                    urlParams += (urlParams.Length == 0 ? "?" : "&") + "orgs=" + curBooking.Organisation.OrganisationID;
                }
                if (curBooking.Patient != null)
                {
                    urlParams += (urlParams.Length == 0 ? "?" : "&") + "patient=" + curBooking.Patient.PatientID;
                }
                urlParams += (urlParams.Length == 0 ? "?" : "&") + "scroll_to_cell=" + "td_" + (curBooking.Organisation != null ? "" : curBooking.Organisation.OrganisationID.ToString()) + "_" + curBooking.Provider.StaffID + "_" + curBooking.DateStart.ToString("yyyy_MM_dd_HHmm");
                urlParams += (urlParams.Length == 0 ? "?" : "&") + "date=" + curBooking.DateStart.ToString("yyyy_MM_dd");
                tblBookingList.Rows[i]["booking_url"] = curBooking.GetBookingSheetLinkV2();



                string addedBy                 = curBooking.AddedBy == null || staffHash[curBooking.AddedBy.StaffID] == null ? "" : (((Staff)staffHash[curBooking.AddedBy.StaffID]).IsExternal ? "[External Staff] " : "") + ((Staff)staffHash[curBooking.AddedBy.StaffID]).Person.FullnameWithoutMiddlename;
                string addedDate               = curBooking.DateCreated == DateTime.MinValue                                       ? "" : curBooking.DateCreated.ToString("MMM d, yyyy");
                string deletedBy               = curBooking.DeletedBy == null || staffHash[curBooking.DeletedBy.StaffID] == null ? "" : ((Staff)staffHash[curBooking.DeletedBy.StaffID]).Person.FullnameWithoutMiddlename;
                string deletedDate             = curBooking.DateDeleted == DateTime.MinValue                                       ? "" : curBooking.DateDeleted.ToString("MMM d, yyyy");
                string added_by_deleted_by_row = string.Empty;
                added_by_deleted_by_row += "Added By: " + addedBy + " (" + addedDate + ")";
                if (deletedBy.Length > 0 || deletedDate.Length > 0)
                {
                    added_by_deleted_by_row += "\r\nDeleted By: " + deletedBy + " (" + deletedDate + ")";
                }
                tblBookingList.Rows[i]["added_by_deleted_by_row"] = added_by_deleted_by_row;

                tblBookingList.Rows[i]["booking_change_history_link"] = curBooking.GetBookingChangeHistoryPopupLinkImage();
                tblBookingList.Rows[i]["hide_change_history_link"]    = changeHistoryHash[curBooking.BookingID] == null;
            }

            System.Collections.Hashtable hashHasMedicareOrDVAInvoices = BookingDB.GetHashHasMedicareDVA((int[])bookingsWithInvoices.ToArray(typeof(int)));

            for (int i = 0; i < tblBookingList.Rows.Count; i++)
            {
                tblBookingList.Rows[i]["show_invoice_row"]        = hasInvoiceRows              ? 1 : 0;
                tblBookingList.Rows[i]["show_notes_row"]          = hasNotesRows                ? 1 : 0;
                tblBookingList.Rows[i]["show_printletter_row"]    = hasPrintLetterRows          ? 1 : 0;
                tblBookingList.Rows[i]["show_bookingsheet_row"]   = hasBookingSheetRows         ? 1 : 0;
                tblBookingList.Rows[i]["show_change_history_row"] = changeHistoryHash.Count > 0 ? 1 : 0;

                int  booking_id   = Convert.ToInt32(tblBookingList.Rows[i]["booking_booking_id"]);
                bool has_medicare = hashHasMedicareOrDVAInvoices[new Hashtable2D.Key(booking_id, -1)] != null && Convert.ToBoolean(hashHasMedicareOrDVAInvoices[new Hashtable2D.Key(booking_id, -1)]);
                bool has_dva      = hashHasMedicareOrDVAInvoices[new Hashtable2D.Key(booking_id, -2)] != null && Convert.ToBoolean(hashHasMedicareOrDVAInvoices[new Hashtable2D.Key(booking_id, -2)]);
                if (has_medicare)
                {
                    tblBookingList.Rows[i]["inv_type_text"] = "Medicare";
                }
                else if (has_dva)
                {
                    tblBookingList.Rows[i]["inv_type_text"] = "DVA";
                }
                else
                {
                    tblBookingList.Rows[i]["inv_type_text"] = string.Empty;
                }
            }
            tblBookingList.DefaultView.Sort = "booking_date_start DESC";
            tblBookingList            = tblBookingList.DefaultView.ToTable();
            lstBookingList.DataSource = tblBookingList;
            lstBookingList.DataBind();
        }

        return(tblBookingList);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HideErrorMessage();

            if (!IsPostBack)
            {
                PagePermissions.EnforcePermissions_RequireAny(Session, Response, true, true, false, false, false, false);
                SetUpGUI();

                if ((GetUrlParamType() == UrlParamType.Edit || GetUrlParamType() == UrlParamType.View) && IsValidFormID())
                {
                    Staff staff = StaffDB.GetByID(GetFormID());
                    if (staff != null)
                    {
                        // hide higher privleiged users from lower priveliged users
                        UserView userView = UserView.GetInstance();
                        if ((!userView.IsStakeholder && staff.IsStakeholder) || (!userView.IsStakeholder && !userView.IsMasterAdmin && staff.IsMasterAdmin))
                        {
                            Response.Redirect(PagePermissions.UnauthorisedAccessPageForward());
                        }

                        FillEditViewForm(staff, GetUrlParamType() == UrlParamType.Edit);
                    }
                    else
                    {
                        HideTableAndSetErrorMessage();
                    }
                }
                else if (GetUrlParamType() == UrlParamType.Add)
                {
                    FillEmptyAddForm();
                }
                else
                {
                    HideTableAndSetErrorMessage();
                }

                txtFirstname.Focus();
            }
        }
        catch (CustomMessageException ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage(ex.Message);
            }
            else
            {
                HideTableAndSetErrorMessage(ex.Message);
            }
        }
        catch (Exception ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage("", ex.ToString());
            }
            else
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
    }
    protected void Repeater15_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));

            DataRowView dr = (DataRowView)e.Item.DataItem;
            if (dr == null || dr.Row == null)
            {
                return;
            }
            DataRow row     = dr.Row;
            Invoice invoice = InvoiceDB.LoadAll(row);


            // get controls
            Repeater           lstReceipts       = (Repeater)e.Item.FindControl("lstReceipts");
            HtmlGenericControl div_receipts_list = (HtmlGenericControl)e.Item.FindControl("div_receipts_list");
            HtmlGenericControl span_receipts_trailing_space_row = (HtmlGenericControl)e.Item.FindControl("span_receipts_trailing_space_row");
            Label      lnkAddReceipt        = (Label)e.Item.FindControl("lnkAddReceipt");
            LinkButton showHideReceiptsList = (LinkButton)e.Item.FindControl("showHideReceiptsList");


            // get receipts
            DataTable tblReciepts = ReceiptDB.GetDataTableByInvoice(invoice.InvoiceID);
            lstReceipts.Visible = tblReciepts.Rows.Count > 0;
            span_receipts_trailing_space_row.Visible = tblReciepts.Rows.Count > 0;
            if (tblReciepts.Rows.Count > 0)
            {
                tblReciepts.Columns.Add("receipt_url", typeof(string));
                tblReciepts.Columns.Add("show_status", typeof(string));
                tblReciepts.Columns.Add("status", typeof(string));
                tblReciepts.Columns.Add("show_reconcile_link", typeof(string));
                tblReciepts.Columns.Add("reconcile_link", typeof(string));
                tblReciepts.Columns.Add("show_reverse_link", typeof(string));
                for (int i = 0; i < tblReciepts.Rows.Count; i++)
                {
                    Receipt receipt = ReceiptDB.LoadAll(tblReciepts.Rows[i]);

                    tblReciepts.Rows[i]["receipt_url"] = receipt.GetViewPopupLinkV2();

                    bool isReconciledOrReversed = receipt.IsReconciled || receipt.IsReversed;
                    tblReciepts.Rows[i]["status"]              = receipt.IsReconciled    ? "Reconciled" : "Reversed";
                    tblReciepts.Rows[i]["show_status"]         = isReconciledOrReversed  ? "1" : "0";
                    tblReciepts.Rows[i]["reconcile_link"]      = receipt.GetReconcilePopupLinkV2("window.location.href = window.location.href;");
                    tblReciepts.Rows[i]["show_reconcile_link"] = !isReconciledOrReversed && (loggedInStaff.IsStakeholder || loggedInStaff.IsMasterAdmin || loggedInStaff.IsAdmin || loggedInStaff.IsPrincipal) ? "1" : "0";
                    tblReciepts.Rows[i]["show_reverse_link"]   = !isReconciledOrReversed  ? "1" : "0";
                }

                lstReceipts.DataSource = tblReciepts;
                lstReceipts.DataBind();
            }

            if (!invoice.IsPaID) // can add items
            {
                lnkAddReceipt.Text = Receipt.GetAddReceiptPopupLinkV2(invoice.InvoiceID, "Add Payment", "window.location.href = window.location.href;");
            }
            else
            {
                lnkAddReceipt.Text = tblReciepts.Rows.Count > 0 ? string.Empty : "No Payments";
            }
            //span_add_receipts_row.Style["text-align"] = (tblReciepts.Rows.Count > 0) ? "center" : null;  // if have table, center add link, else left align
            lnkAddReceipt.Visible = lnkAddReceipt.Text.Length > 0;
            showHideReceiptsList.OnClientClick   = "javascript:show_hide_byname('div_receipts_list_" + invoice.InvoiceID + "'); return false;";
            showHideReceiptsList.Visible         = tblReciepts.Rows.Count > 0;
            div_receipts_list.Attributes["name"] = "div_receipts_list_" + invoice.InvoiceID;
        }
    }
Exemple #18
0
    protected void GrdRegistration_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Staff staff = StaffDB.GetByID(GetFormID());

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

        DataTable dt       = Session["registerorgtostaff_data"] as DataTable;
        bool      tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("register_staff_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];


            DropDownList ddlOrganisation = (DropDownList)e.Row.FindControl("ddlOrganisation");
            if (ddlOrganisation != null)
            {
                Organisation[] incList_orig = RegisterStaffDB.GetOrganisationsOf(staff.StaffID);
                Organisation[] incList      = Organisation.RemoveByID(incList_orig, Convert.ToInt32(thisRow["organisation_id"]));
                DataTable      orgs         = OrganisationDB.GetDataTable_AllNotInc(incList, true, false, false, true, true);
                orgs.DefaultView.Sort = "name ASC";

                foreach (DataRowView row in orgs.DefaultView)
                {
                    ddlOrganisation.Items.Add(new ListItem(row["name"].ToString(), row["organisation_id"].ToString()));
                }
                ddlOrganisation.SelectedValue = thisRow["organisation_id"].ToString();
            }

            ImageButton btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
            if (btnDelete != null)
            {
                bool is_deleted = Convert.ToBoolean(thisRow["registration_is_deleted"]);
                if (is_deleted)
                {
                    btnDelete.CommandName   = "_UnDelete";
                    btnDelete.ImageUrl      = "~/images/tick-24.png";
                    btnDelete.AlternateText = "UnDelete";
                    btnDelete.ToolTip       = "UnDelete";

                    btnDelete.Visible = false;
                }
            }

            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList ddlOrganisation = (DropDownList)e.Row.FindControl("ddlNewOrganisation");
            if (ddlOrganisation != null)
            {
                Organisation[] incList = RegisterStaffDB.GetOrganisationsOf(staff.StaffID);
                DataTable      orgs    = OrganisationDB.GetDataTable_AllNotInc(incList, true, false, false, true, true);
                orgs.DefaultView.Sort = "name ASC";

                foreach (DataRowView row in orgs.DefaultView)
                {
                    ddlOrganisation.Items.Add(new ListItem(row["name"].ToString(), row["organisation_id"].ToString()));
                }

                if (orgs.Rows.Count == 0)
                {
                    hideFotter = true;
                }
            }

            if (staff.IsExternal)
            {
                CheckBox chkNewIncMondays    = (CheckBox)e.Row.FindControl("chkNewIncMondays");
                CheckBox chkNewIncTuesdays   = (CheckBox)e.Row.FindControl("chkNewIncTuesdays");
                CheckBox chkNewIncWednesdays = (CheckBox)e.Row.FindControl("chkNewIncWednesdays");
                CheckBox chkNewIncThursdays  = (CheckBox)e.Row.FindControl("chkNewIncThursdays");
                CheckBox chkNewIncFridays    = (CheckBox)e.Row.FindControl("chkNewIncFridays");
                CheckBox chkNewIncSaturdays  = (CheckBox)e.Row.FindControl("chkNewIncSaturdays");
                CheckBox chkNewIncSundays    = (CheckBox)e.Row.FindControl("chkNewIncSundays");

                if (chkNewIncMondays != null)
                {
                    chkNewIncMondays.Checked = false;
                }
                if (chkNewIncTuesdays != null)
                {
                    chkNewIncTuesdays.Checked = false;
                }
                if (chkNewIncWednesdays != null)
                {
                    chkNewIncWednesdays.Checked = false;
                }
                if (chkNewIncThursdays != null)
                {
                    chkNewIncThursdays.Checked = false;
                }
                if (chkNewIncFridays != null)
                {
                    chkNewIncFridays.Checked = false;
                }
                if (chkNewIncSaturdays != null)
                {
                    chkNewIncSaturdays.Checked = false;
                }
                if (chkNewIncSundays != null)
                {
                    chkNewIncSundays.Checked = false;
                }
            }
        }
    }
Exemple #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        bool isLoggedIn  = Session != null && Session["DB"] != null;
        bool useConfigDB = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseConfigDB"]);

        try
        {
            string staff_id = Request.QueryString["staff"];
            if (staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException();
            }
            string org_id = Request.QueryString["org"];
            if (org_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$"))
            {
                throw new CustomMessageException();
            }


            if (!isLoggedIn && useConfigDB)
            {
                Session["DB"] = System.Configuration.ConfigurationManager.AppSettings["Database"];
                Session["SystemVariables"] = SystemVariableDB.GetAll();
            }
            if (!isLoggedIn && !useConfigDB)
            {
                string _output = @"<table>
                        <tr>
                            <td align=""left"" colspan=""5""><b>Patients Waiting" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
                        </tr>
                        <tr style=""height:10px"">
                            <td colspan=""5""></td>
                        </tr>
                        <tr><td colspan=""5""><font color=""#8a8a8a"">Unable to retrieve patients while logged out.</font></td></tr>
                        </table>";
                Response.Write(_output);
                return;
            }


            Staff staff = StaffDB.GetByID(Convert.ToInt32(staff_id));
            if (staff_id == "-1" || staff == null)
            {
                throw new CustomMessageException();
            }
            Organisation org = OrganisationDB.GetByID(Convert.ToInt32(org_id));
            if (staff_id == "0" || staff == null)
            {
                throw new CustomMessageException();
            }


            string output = string.Empty;

            int       count    = 0;
            Booking[] bookings = BookingDB.GetBetween(DateTime.Now.AddMinutes(-45), DateTime.Now.AddMinutes(120), new Staff[] { staff }, new Organisation[] { org }, null, null, false, "0");
            foreach (Booking b in bookings)
            {
                if (b.ArrivalTime == DateTime.MinValue)
                {
                    continue;
                }

                output += @"<tr><td>" + b.Patient.Person.FullnameWithoutMiddlename + @"</td><td style=""width:10px""></td><td>" + b.DateStart.ToString("h:mm") + @"</td><td style=""width:10px""></td><td><a href=""javascript:void(0)"" onclick=""ajax_unset_arrival_time(" + b.BookingID + @");return false;"" title=""Remove from list"" style=""text-decoration:none;""><font color=""red"">X</font></a></td></tr>";
                count++;
            }

            if (count == 0)
            {
                output += @"<tr><td colspan=""5""><font color=""#8a8a8a"">No patients waiting</font></td></tr>";
            }


//                               <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
//                               <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</td>
            output = @"<table>
                           <tr>
                                <td align=""left"" colspan=""5""><b>Patients Waiting (" + count + ")" + @"</b><font color=""#8a8a8a""> &nbsp;&nbsp;  @ " + DateTime.Now.ToString("h:mm:ss") + @"</font></td>
                           </tr>
                           <tr style=""height:10px"">
                               <td colspan=""5""></td>
                           </tr>" + output + "</table>";

            Response.Write(output);
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "please contact system administrator."));
        }
        finally
        {
            if (!isLoggedIn && useConfigDB)
            {
                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }
        }
    }
Exemple #20
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 #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HideErrorMessage();

            if (!IsPostBack)
            {
                PagePermissions.EnforcePermissions_RequireAny(Session, Response, true, true, false, false, false, false);
                SetUpGUI();

                if ((GetUrlParamType() == UrlParamType.Edit || GetUrlParamType() == UrlParamType.View) && IsValidFormID())
                {
                    Staff staff = StaffDB.GetByID(GetFormID());
                    if (staff != null)
                    {
                        // hide higher privleiged users from lower priveliged users
                        UserView userView = UserView.GetInstance();
                        if ((!userView.IsStakeholder && staff.IsStakeholder) || (!userView.IsStakeholder && !userView.IsMasterAdmin && staff.IsMasterAdmin))
                        {
                            Response.Redirect(PagePermissions.UnauthorisedAccessPageForward());
                        }

                        FillEditViewForm(staff, GetUrlParamType() == UrlParamType.Edit);

                        if (Utilities.GetAddressType().ToString() == "Contact")
                        {
                            addressControl.Visible = true;
                            addressControl.Set(staff.Person.EntityID, true, EntityType.GetByType(EntityType.EntityTypeEnum.Staff));
                        }
                        else if (Utilities.GetAddressType().ToString() == "ContactAus")
                        {
                            addressAusControl.Visible = true;
                            addressAusControl.Set(staff.Person.EntityID, true, EntityType.GetByType(EntityType.EntityTypeEnum.Staff));
                        }
                        else
                        {
                            throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                        }
                    }
                    else
                    {
                        HideTableAndSetErrorMessage();
                    }
                }
                else if (GetUrlParamType() == UrlParamType.Add)
                {
                    FillEmptyAddForm();
                }
                else
                {
                    HideTableAndSetErrorMessage();
                }
            }
        }
        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 #22
0
    protected void SetupGUI()
    {
        UserView userView = UserView.GetInstance();

        chkIncAllSites.Text      = userView.IsAgedCareView ? "&nbsp;Inc Clinics" : "&nbsp;Inc Aged Care Facilities";
        chkIncAllSites.Checked   = IsValidFormIncAllSites()   ? GetFormIncAllSites(false)   : true;
        chkIncBookings.Checked   = IsValidFormIncBookings()   ? GetFormIncBookings(false)   : true;
        chkDateAcrossTop.Checked = IsValidFormDateAcrossTop() ? GetFormDateAcrossTop(false) : true;


        ddlOrgs.Style["width"] = "300px";
        ddlOrgs.Items.Clear();
        ddlOrgs.Items.Add(new ListItem("All " + (userView.IsAgedCareView ? "Facilities" : "Clinics"), (-1).ToString()));
        foreach (Organisation curOrg in OrganisationDB.GetAll(false, true, !userView.IsClinicView && !userView.IsGPView, !userView.IsAgedCareView, true, true))
        {
            ddlOrgs.Items.Add(new ListItem(curOrg.Name, curOrg.OrganisationID.ToString()));
        }

        ddlProviders.Style["width"] = "300px";
        ddlProviders.Items.Clear();
        ddlProviders.Items.Add(new ListItem("All Providers", (-1).ToString()));
        foreach (Staff curProv in StaffDB.GetAll())
        {
            if (curProv.IsProvider)
            {
                ddlProviders.Items.Add(new ListItem(curProv.Person.FullnameWithoutMiddlename, curProv.StaffID.ToString()));
            }
        }


        if (IsValidFormOrgID())
        {
            Organisation org = OrganisationDB.GetByID(GetFormOrgID());
            if (org != null)
            {
                ddlOrgs.SelectedValue = org.OrganisationID.ToString();
            }
        }

        if (!UserView.GetInstance().IsAdminView)
        {
            providerRow.Visible = false;

            Staff provider = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
            if (provider != null)
            {
                ddlProviders.SelectedValue = provider.StaffID.ToString();
            }
        }
        else
        {
            if (IsValidFormProviderID())
            {
                Staff provider = StaffDB.GetByID(GetFormProviderID());
                if (provider != null)
                {
                    ddlProviders.SelectedValue = provider.StaffID.ToString();
                }
            }
        }

        txtStartDate.Text = IsValidFormStartDate() ? (GetFormStartDate(false) == DateTime.MinValue ? "" : GetFormStartDate(false).ToString("dd-MM-yyyy")) : DateTime.Today.ToString("dd-MM-yyyy");
        txtEndDate.Text   = IsValidFormEndDate()   ? (GetFormEndDate(false) == DateTime.MinValue ? "" : GetFormEndDate(false).ToString("dd-MM-yyyy"))   : DateTime.Today.AddMonths(1).ToString("dd-MM-yyyy");

        txtStartDate_Picker.OnClientClick = "displayDatePicker('txtStartDate', this, 'dmy', '-'); return false;";
        txtEndDate_Picker.OnClientClick   = "displayDatePicker('txtEndDate', this, 'dmy', '-'); return false;";
    }
    protected void FillGrid()
    {
        DateTime fromDate = IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text)                             : DateTime.MinValue;
        DateTime toDate   = IsValidDate(txtEndDate.Text)   ? GetDate(txtEndDate.Text).Add(new TimeSpan(23, 59, 59)) : DateTime.MinValue;

        ArrayList list = new ArrayList();

        if (chkIncCompleted.Checked)
        {
            list.Add("187");
        }
        if (chkIncCancelled.Checked)
        {
            list.Add("188");
        }
        if (chkIncIncomplete.Checked)
        {
            list.Add("0");
        }
        if (chkIncDeleted.Checked)
        {
            list.Add("-1");
        }
        string statusIDsToInclude = string.Join(",", (string[])list.ToArray(Type.GetType("System.String")));


        DataTable dt = null;

        /*
         * if (IsValidFormPatient())
         * {
         *  int patient_id = GetFormPatient(false);
         *  Patient patient = PatientDB.GetByID(patient_id);
         *  if (patient == null)
         *      throw new CustomMessageException("Invalid patient ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = patient.Person.FullnameWithoutMiddlename;
         *  lnkToEntity.NavigateUrl = "PatientDetailV2.aspx?type=view&id=" + patient.PatientID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, null, null, patient, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else if (IsValidFormOrganisation())
         * {
         *  int org_id = GetFormOrganisation(false);
         *  Organisation org = OrganisationDB.GetByID(org_id);
         *  if (org == null)
         *      throw new CustomMessageException("Invalid organisation ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = org.Name;
         *  lnkToEntity.NavigateUrl = "OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, null, new Organisation[] { org }, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else if (IsValidFormProvider())
         * {
         *  int provider_id = GetFormProvider(false);
         *  Staff provider = StaffDB.GetByID(provider_id);
         *  if (provider == null)
         *      throw new CustomMessageException("Invalid provider ID");
         *
         *  heading.InnerText = "Bookings List for : ";
         *  lnkToEntity.Text = provider.Person.FullnameWithoutMiddlename;
         *  lnkToEntity.NavigateUrl = "StaffDetailV2.aspx?type=view&id=" + provider.StaffID;
         *
         *  dt = BookingDB.GetDataTable_Between(fromDate, toDate, new Staff[] { provider }, null, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());
         * }
         * else
         *  throw new CustomMessageException("No entity to get bookings for");
         */

        Patient      patient  = null;
        Organisation org      = null;
        Staff        provider = null;


        if (IsValidFormPatient())
        {
            int patientID = GetFormPatient(false);
            patient = PatientDB.GetByID(patientID);
            if (patient == null)
            {
                throw new CustomMessageException("Invalid patient ID");
            }
        }
        if (IsValidFormOrganisation())
        {
            int orgID = GetFormOrganisation(false);
            org = OrganisationDB.GetByID(orgID);
            if (org == null)
            {
                throw new CustomMessageException("Invalid organisation ID");
            }
        }
        if (IsValidFormProvider())
        {
            int provID = GetFormProvider(false);
            provider = StaffDB.GetByID(provID);
            if (provider == null)
            {
                throw new CustomMessageException("Invalid provider ID");
            }
        }


        if (patient == null && org == null && provider == null)
        {
            throw new CustomMessageException("No entity to get bookings for");
        }

        UserView userView = UserView.GetInstance();

        lblHeading.Text = "Bookings List for:";
        int items = (patient == null ? 0 : 1) + (provider == null ? 0 : 1) + (org == null ? 0 : 1);

        if (patient != null)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Patient " : " ") + "<a href=\"PatientDetailV2.aspx?type=view&id=" + patient.PatientID + "\">" + patient.Person.FullnameWithoutMiddlename + "</a>";
        }
        if (provider != null && userView.IsAdminView)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Provider " : " ") + "<a href=\"StaffDetailV2.aspx?type=view&id=" + provider.StaffID + "\">" + provider.Person.FullnameWithoutMiddlename + "</a>";
        }
        if (provider != null && !userView.IsAdminView)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Provider " : " ") + provider.Person.FullnameWithoutMiddlename;
        }
        if (org != null)
        {
            lblHeading.Text += (items > 1 ? "<br />&nbsp;&nbsp;Clinic " : " ") + "<a href=\"OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID + "\">" + org.Name + "</a>";
        }


        if (txtBookingNbrSearch.Text.Trim().Length > 0)
        {
            fromDate = DateTime.MinValue;
            toDate   = DateTime.MinValue;
        }

        dt = BookingDB.GetDataTable_Between(fromDate, toDate, provider == null ? null : new Staff[] { provider }, org == null ? null : new Organisation[] { org }, patient, null, chkIncDeleted.Checked, statusIDsToInclude, false, txtBookingNbrSearch.Text.Trim());

        // above query gets for org OR prov .. so remove those
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            Booking booking = BookingDB.LoadFull(dt.Rows[i]);

            if ((patient != null && (booking.Patient == null || booking.Patient.PatientID != patient.PatientID)) ||
                (org != null && (booking.Organisation == null || booking.Organisation.OrganisationID != org.OrganisationID)) ||
                (provider != null && (booking.Provider == null || booking.Provider.StaffID != provider.StaffID)) ||
                (booking.BookingTypeID != 34))
            {
                dt.Rows.RemoveAt(i);
            }
        }


        // if confirmed by email/sms, display booking_confirmed_by_type.descr
        // if confirmed by person, display their name
        dt.Columns.Add("confirmed_by_text", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["booking_booking_confirmed_by_type_id"] == DBNull.Value)
            {
                dt.Rows[i]["confirmed_by_text"] = DBNull.Value;
            }
            else if (Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 2 || Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 3)
            {
                dt.Rows[i]["confirmed_by_text"] = dt.Rows[i]["booking_confirmed_by_type_descr"];
            }
            else if (Convert.ToInt32(dt.Rows[i]["booking_booking_confirmed_by_type_id"]) == 1)
            {
                dt.Rows[i]["confirmed_by_text"] = dt.Rows[i]["person_confirmed_by_person_id"] == DBNull.Value ? (object)DBNull.Value : dt.Rows[i]["person_confirmed_by_firstname"] + " " + dt.Rows[i]["person_confirmed_by_surname"];
            }
        }

        Session["bookinglist_data"] = dt;

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


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

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



        bool hasInvoices          = false;
        bool hasCompletedInvoices = false;

        foreach (GridViewRow row in GrdBooking.Rows)
        {
            if (row.RowType == DataControlRowType.Pager)
            {
                continue;
            }
            if (row.FindControl("lblViewInvoice") != null && ((Label)row.FindControl("lblViewInvoice")).Text.Length > 0)
            {
                hasInvoices = true;
            }
            if (row.FindControl("lblGeneratedSystemLetters") != null && ((Label)row.FindControl("lblGeneratedSystemLetters")).Text.Length > 0 && ((Label)row.FindControl("lblGeneratedSystemLetters")).Visible)
            {
                hasCompletedInvoices = true;
            }
        }
        GrdBooking.Columns[12].Visible = hasInvoices;
        GrdBooking.Columns[9].Visible  = hasCompletedInvoices;
    }
Exemple #24
0
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Staff staff = StaffDB.GetByID(GetFormID());

        if (staff == null)
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }
        staff.Person = PersonDB.GetByID(staff.Person.PersonID);

        lblHeading.Text = Page.Title = "Manage Clinics/Facilities For :  " + staff.Person.Firstname + " " + staff.Person.Surname;
        this.lnkThisStaff.NavigateUrl = staff.IsExternal ?  "~/StaffDetailExternalV2.aspx?type=view&id=" + GetFormID().ToString() :  "~/StaffDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisStaff.Text        = "Back to details for " + staff.Person.Firstname + " " + staff.Person.Surname;


        if (staff.IsExternal)
        {
            GrdRegistration.Columns[3].Visible  = false;
            GrdRegistration.Columns[4].Visible  = false;
            GrdRegistration.Columns[5].Visible  = false;
            GrdRegistration.Columns[6].Visible  = false;
            GrdRegistration.Columns[7].Visible  = false;
            GrdRegistration.Columns[8].Visible  = false;
            GrdRegistration.Columns[9].Visible  = false;
            GrdRegistration.Columns[10].Visible = false;
            GrdRegistration.Columns[11].Visible = false;
        }


        DataTable dt = RegisterStaffDB.GetDataTable_OrganisationsOf(staff.StaffID, null, chkShowDeleted.Checked);

        Session["registerorgtostaff_data"] = dt;

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


            try
            {
                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;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!ddlEndDateValidateAllOrNoneSet.IsValid ||
            !ddlStartDateValidateAllOrNoneSet.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"]);


            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, staff.Person.Dob, DateTime.Now);
            StaffDB.Update(staff.StaffID, staff.Person.PersonID, txtLogin.Text, txtPwd.Text, staff.StaffPosition.StaffPositionID, staff.Field.ID, staff.CostCentre.CostCentreID,
                           staff.IsContractor, staff.Tfn, staff.ProviderNumber,
                           ddlStatus.SelectedValue == "Inactive", staff.IsCommission, staff.CommissionPercent,
                           staff.IsStakeholder, staff.IsMasterAdmin, staff.IsAdmin, staff.IsPrincipal, staff.IsProvider, staff.IsExternal,
                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, staff.EnableDailyReminderSMS, staff.EnableDailyReminderEmail, staff.HideBookingNotes);

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

            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view"));
        }
        else if (GetUrlParamType() == UrlParamType.Add)
        {
            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;
            }


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

                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, DateTime.MinValue);
                staff_id  = StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, 0, 59,
                                           false, "", "",
                                           ddlStatus.SelectedValue == "Inactive", false, 0,
                                           false, false, false, false, false, true,
                                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, false, false, false);
                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 #26
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();
    }
Exemple #27
0
    public static string UpdateAllPaymentsPending(string DB, DateTime from, DateTime to, int staffID, bool incOutput = false)
    {
        bool isStakeholder = HttpContext.Current.Session != null && HttpContext.Current.Session["IsStakeholder"] != null && Convert.ToBoolean(HttpContext.Current.Session["IsStakeholder"]);

        NonPCIServiceClient client = new NonPCIServiceClient();

        px.ezidebit.com.au.EziResponseOfArrayOfPaymentTHgMB7oL result = client.GetPayments(
            ((SystemVariables)HttpContext.Current.Session["SystemVariables"])["EziDebit_DigitalKey"].Value,
            "ALL",
            "ALL",
            "ALL",
            "",
            from.ToString("yyyy-MM-dd"),
            to.ToString("yyyy-MM-dd"),
            "PAYMENT",
            "",
            ""
            );


        string output = string.Empty;

        output += "Error: " + result.Error + "<br /><br />";

        if (result.Data != null)
        {
            // some erroneous payment references have gotten in and then there is an erorr converting it to an int to sort it.
            bool   containsOnlyInts = true;
            string allPaymentRefs   = string.Empty;
            foreach (px.ezidebit.com.au.Payment payment in result.Data)
            {
                if (!Regex.IsMatch(payment.PaymentReference, @"^\d+$"))
                {
                    allPaymentRefs  += "<tr><td><font color=\"red\">" + payment.PaymentReference + "</font></td><td style=\"min-width:10px;\"></td><td>$" + payment.ScheduledAmount + "</td><td style=\"min-width:10px;\"></td><td>" + (payment.SettlementDate == null ? "" : payment.SettlementDate.Value.ToString("d MMM yyyy  mm:ss")) + "</td></tr>";
                    containsOnlyInts = false;
                }
                else
                {
                    allPaymentRefs += "<tr><td>" + payment.PaymentReference + "</td><td style=\"min-width:10px;\"></td><td>$" + payment.ScheduledAmount + "</td><td style=\"min-width:10px;\"></td><td>" + (payment.SettlementDate == null ? "" : payment.SettlementDate.Value.ToString("d MMM yyyy  mm:ss")) + "</td></tr>";
                }
            }

            if (containsOnlyInts)
            {
                Array.Sort(result.Data, delegate(px.ezidebit.com.au.Payment p1, px.ezidebit.com.au.Payment p2)
                {
                    return(Convert.ToInt32(p1.PaymentReference).CompareTo(Convert.ToInt32(p2.PaymentReference)));
                });
            }


            for (int i = 0; i < result.Data.Length; i++)
            {
                if (!Regex.IsMatch(result.Data[i].PaymentReference, @"^\d+$"))
                {
                    continue;
                }

                PaymentPending paymentPending = PaymentPendingDB.GetByID(DB, Convert.ToInt32(result.Data[i].PaymentReference));

                if (paymentPending == null)
                {
                    continue;
                }

                if (paymentPending.OutDateProcessed != DateTime.MinValue &&
                    paymentPending.OutPaymentResult == "A" &&
                    (result.Data[i].PaymentStatus.ToUpper() != "S" && result.Data[i].PaymentStatus.ToUpper() != "P"))
                {
                    Emailer.SimpleAlertEmail(
                        "Ezidebit invoice payment added and set to \"A\" but payment status not in (\"S\",\"P\"): " + result.Data[i].PaymentStatus.ToUpper() + ".<br />payment_pending_id: " + paymentPending.PaymentPendingID + "<br />DB: " + (DB == null ? System.Web.HttpContext.Current.Session["DB"] : DB),
                        "Ezidebit Reconcilliation - Payment Status Mismatch",
                        true);
                }

                if (paymentPending.OutDateProcessed != DateTime.MinValue)
                {
                    continue;
                }


                //
                // During real time transactions, results can be
                //
                // A = Approved
                // U = Unable to process at that time (Failed)
                // F = Failed                         (Failed)
                //
                // On the instant payment screen, we set in our DB as Approved (& generate receipt), or else we do not enter the result
                // There is no option (A/U/F) for Pending to update later
                //
                //
                // During this reconcilliation, results can be
                //
                // S   = Successful
                // P   = Pending (just means waiting for money to physically be sent to our bank)
                // F/D = (Dishonour/Fatal Dishonour)
                //
                //
                // Their instant payment page will always know if it was successful or failed at the time of transaction.
                //
                // So in the reconciliation web service, since 'Pending' is not a fail code, it means any payment
                // set to Pending is definitely successful and just waiting for the money to be actually sent.
                //
                // Ezidebit support confirmed this.
                //

                if (result.Data[i].PaymentStatus.ToUpper() == "S" || result.Data[i].PaymentStatus.ToUpper() == "P")
                {
                    PaymentPendingDB.Update(DB, result.Data[i].TransactionTime.Value, paymentPending.PaymentPendingID, "A", "00", "APPROVED", result.Data[i].BankReceiptID, result.Data[i].PaymentID);

                    // update this invoice as paid!
                    if (!Convert.ToBoolean(ConfigurationManager.AppSettings["EziDebit_Debugging"]))
                    {
                        Invoice invoice = InvoiceDB.GetByID(paymentPending.InvoiceID);

                        if (result.Data[i].ScheduledAmount != (double)paymentPending.PaymentAmount)
                        {
                            Emailer.SimpleAlertEmail(
                                "Ezidebit invoice late payment added but initial payment amount and reconcilliation ammount differ (" + paymentPending.PaymentAmount + ", " + result.Data[i].ScheduledAmount + ")<br />payment_pending_id: " + paymentPending.PaymentPendingID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + (DB == null ? System.Web.HttpContext.Current.Session["DB"] : DB) + "<br />Original Amount: " + paymentPending.PaymentAmount + "<br />Ezidebit Sync Amount: " + result.Data[i].ScheduledAmount + "<br />Staff: " + StaffDB.GetByID(staffID).Person.FullnameWithoutMiddlename,
                                "Ezidebit Reconcilliation Amounts Differ. Invoice " + paymentPending.InvoiceID,
                                true);
                        }

                        decimal totalOwed  = invoice.TotalDue - paymentPending.PaymentAmount;
                        bool    isOverPaid = totalOwed < 0;
                        bool    isPaid     = totalOwed <= 0;

                        int receiptID = ReceiptDB.Insert(DB, 363, paymentPending.InvoiceID, paymentPending.PaymentAmount, 0, false, isOverPaid, DateTime.MinValue, staffID);

                        if (isPaid)
                        {
                            InvoiceDB.UpdateIsPaid(DB, invoice.InvoiceID, true);
                        }

                        if (isOverPaid)
                        {
                            // send email to someone .. to fix up the overpayment
                            Emailer.SimpleAlertEmail(
                                "Ezidebit invoice late web payment added and is overpaid.<br />payment_pending_id: " + paymentPending.PaymentPendingID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + (DB == null ? System.Web.HttpContext.Current.Session["DB"] : DB),
                                "Ezidebit Invoice OverPaid. Invoice: " + invoice.InvoiceID,
                                true);
                        }
                    }
                }
                if (result.Data[i].PaymentStatus.ToUpper() == "F" || result.Data[i].PaymentStatus.ToUpper() == "D")
                {
                    PaymentPendingDB.Update(DB, result.Data[i].TransactionTime.Value, paymentPending.PaymentPendingID, "F", result.Data[i].BankReturnCode, result.Data[i].BankFailedReason, result.Data[i].BankReceiptID, result.Data[i].PaymentID);
                }
            }


            System.Collections.Hashtable ppHash = new System.Collections.Hashtable();
            if (incOutput)
            {
                DataTable dt = PaymentPendingDB.GetDataTable(DB);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    PaymentPending pp = PaymentPendingDB.Load(dt.Rows[i]);
                    ppHash[pp.PaymentPendingID] = pp;
                }
            }


            output += "<table id=\"tbl_output\" class=\"table table-bordered table-striped table-grid table-grid-top-bottum-padding-normal auto_width block_center\" border=\"1\">";

            output += @"<tr><th style=""vertical-align:top !important;"">" +
                      @"<br />Date                      </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Payment Reference         </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Payment Status
                    <table class=""text_left"">
                    <tr style=""white-space:nowrap;""><td>(<b>S</b> = Successful)</td></tr>
                    <tr style=""white-space:nowrap;""><td>(<b>F</b> = Failed)</td></tr>
                    <tr style=""white-space:nowrap;""><td>(<b>P</b> = Pending)</td></tr>
                    </table>                   </th><th style=""vertical-align:top !important;"">" +

                      @"<b>[Internal]<br/></b>Invoice ID           </th><th style=""vertical-align:top !important;"">" +
                      @"<b>[Internal]<br/></b>Customer Name        </th><th style=""vertical-align:top !important;"">" +
                      @"<b>[Internal]<br/></b>Payment Amount       </th><th style=""vertical-align:top !important;"">" +
                      @"<b>[Internal]<br/></b>OutPayment Result    
                        <table class=""text_left"">
                        <tr style=""white-space:nowrap;""><td>(<b>A</b> = Accepted)</td></tr>
                        <tr style=""white-space:nowrap;""><td>(<b>F</b> = Failed)</td></tr>
                        </table>                   </th><th style=""background-color:grey !important;"">" +

                      @"                          </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Bank Failed Reason        </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Bank Receipt ID           </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Bank Return Code          </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Customer Name             </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Debit Date                </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Settlement Date           </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Ezidebit Customer ID      </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Payment ID                </th><th style=""vertical-align:top !important;"">" +
                      (isStakeholder ? @"<br />Payment Amount            </th><th style=""vertical-align:top !important;"">" : "") +
                      @"<br />Payment Method            </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Payment Source            </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Scheduled Amount          </th><th style=""vertical-align:top !important;"">" +
                      (isStakeholder ? @"<br />Transaction Fee Client    </th><th style=""vertical-align:top !important;"">" : "") +
                      (isStakeholder ? @"<br />Transaction Fee Customer  </th><th style=""vertical-align:top !important;"">" : "") +
                      @"<br />Transaction Time          </th><th style=""vertical-align:top !important;"">" +
                      @"<br />Ezidebit Invoice ID       </th>";

            output += "</tr>";


            for (int i = result.Data.Length - 1; i >= 0; i--)
            {
                PaymentPending pp = null;
                if (Regex.IsMatch(result.Data[i].PaymentReference, @"^\d+$"))
                {
                    pp = ppHash[Convert.ToInt32(result.Data[i].PaymentReference)] as PaymentPending;
                }

                bool failed = result.Data[i].PaymentStatus != "S" && result.Data[i].PaymentStatus != "P";

                string invLink = pp == null ? null : String.Format("Invoice_ViewV2.aspx?invoice_id={0}", pp.InvoiceID);
                string onClick = pp == null ? null : "javascript:window.showModalDialog('" + invLink + "', '', 'dialogWidth:775px;dialogHeight:900px;center:yes;resizable:no; scroll:no');return false;";

                output += "<tr" + (!failed ? "" : " style='color:red;' ") + "><td>" +

                          (pp == null ? "" : (pp.DateAdded.ToString("d MMM, yyyy") + " &nbsp;&nbsp;&nbsp; " + pp.DateAdded.ToString("HH:mm"))) + "&nbsp;</td><td>&nbsp;" +

                          (failed ? "<b>" : "") + result.Data[i].PaymentReference + (failed ? "</b>" : "") + "&nbsp;</td><td>&nbsp;" +
                          (failed ? "<b>" : "") + result.Data[i].PaymentStatus + (failed ? "</b>" : "") + "&nbsp;</td><td>&nbsp;" +

                          (pp == null ? "" : "<a href=\"" + invLink + "\"" + (onClick == null ? "" : " onclick=\"" + onClick + "\"") + ">" + pp.InvoiceID + "</a>") + "&nbsp;</td><td>&nbsp;" +
                          (pp == null ? "" : pp.CustomerName.ToString()) + "&nbsp;</td><td>&nbsp;" +
                          (pp == null ? "" : pp.PaymentAmount.ToString()) + "&nbsp;</td><td>&nbsp;" +
                          (pp == null ? "" : pp.OutPaymentResult.ToString()) + "&nbsp;</td><td style=\"background-color:grey;\">&nbsp;" +

                          "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].BankFailedReason + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].BankReceiptID + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].BankReturnCode + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].CustomerName + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].DebitDate + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].SettlementDate + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].EzidebitCustomerID + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].PaymentID + "&nbsp;</td><td>&nbsp;" +
                          (isStakeholder ? result.Data[i].PaymentAmount + "&nbsp;</td><td>&nbsp;" : "") +
                          result.Data[i].PaymentMethod + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].PaymentSource + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].ScheduledAmount + "&nbsp;</td><td>&nbsp;" +
                          (isStakeholder ? result.Data[i].TransactionFeeClient + "&nbsp;</td><td>&nbsp;" : "") +
                          (isStakeholder ? result.Data[i].TransactionFeeCustomer + "&nbsp;</td><td>&nbsp;" : "") +
                          result.Data[i].TransactionTime.Value + "&nbsp;</td><td>&nbsp;" +
                          result.Data[i].InvoiceID + "&nbsp;</td>" +
                          "</tr>";
            }
            output += "</table>";
        }
        else if (result.ErrorMessage != null && result.ErrorMessage.Length > 0)
        {
            for (int i = 0; i < result.ErrorMessage.Length; i++)
            {
                output += "EziDebit Error: " + result.ErrorMessage[i] + "<br />" + Environment.NewLine;
            }

            Emailer.SimpleAlertEmail(
                output,
                "EziDebit Web Service Error",
                true);
            Logger.LogQuery(output, false, true, false);
        }

        client.Close();  // Always close the client.

        return(output);
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            int   staff_id = -1;
            Staff staff    = null;
            if (IsValidFormStaffID() && chkOnlyThisProvider.Checked)
            {
                staff = StaffDB.GetByID(GetFormStaffID());
                if (staff == null)
                {
                    throw new CustomMessageException("Invalid url staff");
                }
                staff_id = staff.StaffID;
            }

            int          org_id = 0;
            Organisation org    = null;
            if (IsValidFormOrgID() && chkOnlyThisOrganistion.Checked)
            {
                org = OrganisationDB.GetByID(GetFormOrgID());
                if (org == null)
                {
                    throw new CustomMessageException("Invalid url org");
                }
                lblOrganistion.Text = org.Name;
            }


            int booking_type_id = org_id != 0 ? 341 : 342;

            // need to make sure at least one day is selected
            if (!chkSunday.Checked && !chkMonday.Checked && !chkTuesday.Checked && !chkWednesday.Checked &&
                !chkThursday.Checked && !chkFriday.Checked && !chkSaturday.Checked)
            {
                throw new CustomMessageException("At least one day must be selected");
            }

            string days = (chkSunday.Checked ? "1" : "0") + (chkMonday.Checked ? "1" : "0") + (chkTuesday.Checked ? "1" : "0") + (chkWednesday.Checked ? "1" : "0") +
                          (chkThursday.Checked ? "1" : "0") + (chkFriday.Checked ? "1" : "0") + (chkSaturday.Checked ? "1" : "0");


            bool     allDay     = chkAllDay.Checked;
            TimeSpan start_time = allDay ? new TimeSpan(0, 0, 0) : new TimeSpan(Convert.ToInt32(ddlStartHour.SelectedValue), Convert.ToInt32(ddlStartMinute.SelectedValue), 0);
            TimeSpan end_time   = allDay ? new TimeSpan(23, 59, 0) : new TimeSpan(Convert.ToInt32(ddlEndHour.SelectedValue), Convert.ToInt32(ddlEndMinute.SelectedValue), 0);

            if (!allDay && (start_time >= end_time))
            {
                throw new CustomMessageException("End time must be after start time");
            }

            // need to check start date and end date are valid dates  (make another method to check this)    is_valid_date(txt_date)
            string start_date_text  = txtStartDate.Text;
            string end_date_text    = txtEndDate.Text;
            bool   valid_start_date = Regex.IsMatch(start_date_text, @"^\d{2}\-\d{2}\-\d{4}$");
            bool   valid_end_date   = Regex.IsMatch(end_date_text, @"^\d{2}\-\d{2}\-\d{4}$");
            if (!valid_start_date)
            {
                throw new CustomMessageException("Invalid start date - Must be in the format dd-mm-yyyy");
            }
            if (!valid_end_date)
            {
                throw new CustomMessageException("Invalid end date - Must be in the format dd-mm-yyyy");
            }


            DateTime start_datetime          = new DateTime(Convert.ToInt32(txtStartDate.Text.Substring(6, 4)), Convert.ToInt32(txtStartDate.Text.Substring(3, 2)), Convert.ToInt32(txtStartDate.Text.Substring(0, 2)));
            DateTime end_datetime            = end_date_text.Length == 0 ? DateTime.MinValue : new DateTime(Convert.ToInt32(txtEndDate.Text.Substring(6, 4)), Convert.ToInt32(txtEndDate.Text.Substring(3, 2)), Convert.ToInt32(txtEndDate.Text.Substring(0, 2)));
            bool     same_start_and_end_date = (start_datetime == end_datetime);
            int      every_n_weeks           = Convert.ToInt32(ddlEveryNWeeks.SelectedValue);


            // need to check that IF end date not null ... check 3nd date is after first date
            if (end_date_text.Length > 0)
            {
                if (start_datetime > end_datetime)
                {
                    throw new CustomMessageException("End date must be after start date");
                }

                // add one day to the end date because 7th-8th will want 8th included, so make it 7th 00:00 to 9th 00:00
                end_datetime = end_datetime.AddDays(1);
            }


            if (!same_start_and_end_date && every_n_weeks > 1 && radBookingSequenceTypeSeries.Checked)
            {
                throw new CustomMessageException("For bookings less frequently than every 1 week, you must select \"Create seperate unavailabilities\"." +
                                                 ((end_date_text.Length > 0) ? "" : "\r\n" +
                                                  "\r\n" +
                                                  "You also must set an end date when creating seperate unavailabilities."));
            }

            if (!same_start_and_end_date && every_n_weeks == 1 && !radBookingSequenceTypeSeperate.Checked && !radBookingSequenceTypeSeries.Checked)
            {
                throw new CustomMessageException("Please select either \"Create seperate unavailabilities\" or \"Create single series\"" + "\r\n" +
                                                 "<small>" +
                                                 "Creating seperate unavailabilities - once created, deleting one of those day's unavailability will not remove other unavailabilities" + "\r\n" +
                                                 "Creating as a series - once created, deleting any instance of the series will remove all instances of this series" +
                                                 "</small>");
            }

            if (radBookingSequenceTypeSeperate.Checked && end_date_text.Length == 0)
            {
                throw new CustomMessageException("Can not select \"Create seperate unavailabilities\" without an end date" + "\r\n" +
                                                 "\r\n" +
                                                 "Either add an end date, or change to \"Create single series\"");
            }

            bool create_as_series = !same_start_and_end_date && radBookingSequenceTypeSeries.Checked;
            if (every_n_weeks > 1)
            {
                create_as_series = false;
            }

            int unavailability_reason_id = -1;
            if (ddlProvUnavailabilityReason.Visible)
            {
                unavailability_reason_id = Convert.ToInt32(ddlProvUnavailabilityReason.SelectedValue);
            }
            if (ddlOrgUnavailabilityReason.Visible)
            {
                unavailability_reason_id = Convert.ToInt32(ddlOrgUnavailabilityReason.SelectedValue);
            }



            Booking[] bookings = BookingDB.GetToCheckOverlap_Recurring(start_datetime, end_datetime, start_time, end_time, days, staff, org, booking_type_id == 342, true, false, true);
            //if (Booking.HasOverlap(bookings, start_datetime, end_datetime, days, start_time, end_time, null))
            //    throw new CustomMessageException("Please move or delete existing bookings first.");
            Booking[] overlappingBookings = Booking.GetOverlappingBookings(bookings, start_datetime, end_datetime, days, start_time, end_time, every_n_weeks, null);
            if (overlappingBookings.Length > 0)
            {
                string space        = "          ";
                string bookingDates = overlappingBookings.Length == 0 ? string.Empty : "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
                for (int i = 0; i < overlappingBookings.Length; i++)
                {
                    string href = overlappingBookings[i].GetBookingSheetLink();
                    if (href.StartsWith("~/"))
                    {
                        href = href.Substring(2);
                    }
                    string allFeatures = "dialogWidth:1500px;dialogHeight:1000px;center:yes;resizable:no; scroll:no";
                    string js          = "javascript:window.showModalDialog('" + href + "', '', '" + allFeatures + "');document.getElementById('btnUpdateEPCInfo').click();return false;";
                    string link        = "<a href=\"#\" onclick=\"" + js + "\">" + (overlappingBookings[i].Patient != null ? overlappingBookings[i].Patient.Person.FullnameWithoutMiddlename : overlappingBookings[i].BookingID.ToString()) + "</a>";
                    bookingDates += "<tr><td>" + space + overlappingBookings[i].DateStart.ToString(@"ddd MMM d, yyy HH:mm") + "</td><td width=\"10\"></td><td>" + link + "</td></tr>";
                }
                bookingDates += overlappingBookings.Length == 0 ? string.Empty : "</table>";
                throw new CustomMessageException("Can not create an unavailability until these existing bookings have been deleted or moved:" + "<br /><small>" + bookingDates + "</small>");
            }


            // MAKE BOOKING FOR EACH WEEK DAY!
            bool madeAtLeastOneBooking = false;
            for (int i = 0; i < 7; i++)
            {
                if (days[i] != '1')
                {
                    continue;
                }
                DayOfWeek dayOfWeek = WeekDayDB.GetDayOfWeek(i + 1);


                if (create_as_series)
                {
                    BookingDB.Insert(start_datetime, end_datetime, org == null ? 0 : org.OrganisationID, staff == null ? -1 : staff.StaffID, -1, -1,
                                     booking_type_id, 0, Convert.ToInt32(unavailability_reason_id), Convert.ToInt32(Session["StaffID"]), 1, Convert.ToInt32(Session["StaffID"]), DateTime.Now, -1, DateTime.MinValue, -1, DateTime.MinValue, false, false, false, true, dayOfWeek, start_time, end_time);
                    madeAtLeastOneBooking = true;
                }
                else
                {
                    // get which dates will occur .. and create individual bookings....
                    DateTime curStartDate = start_datetime;
                    while (curStartDate.DayOfWeek != dayOfWeek)
                    {
                        curStartDate = curStartDate.AddDays(1);
                    }

                    DateTime curStartDateTime = new DateTime(curStartDate.Year, curStartDate.Month, curStartDate.Day, start_time.Hours, start_time.Minutes, 0);
                    DateTime curEndDateTime   = new DateTime(curStartDate.Year, curStartDate.Month, curStartDate.Day, end_time.Hours, end_time.Minutes, 0);
                    int      weekNbr          = 0;
                    while ((allDay && curStartDateTime.Date < end_datetime.Date) || (!allDay && curStartDateTime.Date <= end_datetime.Date))
                    {
                        if (weekNbr % every_n_weeks == 0)
                        {
                            BookingDB.Insert(curStartDateTime, curEndDateTime, org == null ? 0 : org.OrganisationID, staff == null ? -1 : staff.StaffID, -1, -1,
                                             booking_type_id, 0, Convert.ToInt32(unavailability_reason_id), Convert.ToInt32(Session["StaffID"]), 1, Convert.ToInt32(Session["StaffID"]), DateTime.Now, -1, DateTime.MinValue, -1, DateTime.MinValue, false, false, false, false, curStartDateTime.DayOfWeek, TimeSpan.Zero, TimeSpan.Zero);
                            madeAtLeastOneBooking = true;
                        }

                        curStartDateTime = curStartDateTime.AddDays(7);
                        curEndDateTime   = curEndDateTime.AddDays(7);
                        weekNbr++;
                    }
                }
            }

            if (!madeAtLeastOneBooking)
            {
                throw new CustomMessageException("No bookings made - please check that the day/s of week selected are within the dates specified.");
            }

            UpdateList();

            // close this window
            Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=true;self.close();</script>");
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
    }
Exemple #29
0
    protected void GoTo(string db, int orgID, int siteID, int patientID)
    {
        //lblInfo1.Text += "GET<br/>DB: " + db + "<br />Org: " + orgID;

        bool isExternalStaff = orgID != 0 && patientID == -1;
        bool isStakeHolder   = !isExternalStaff && Convert.ToBoolean(Session["IsStakeholder"]);

        if (db != Session["DB"].ToString())
        {
            // Set previous StaffID, pervious DB
            Session["PreviousStaffID"] = Session["StaffID"];
            Session["PreviousDB"]      = Session["DB"];
            Session["PreviousSiteID"]  = Session["SiteID"];

            // Change to new DB & SystemVariables
            Session["DB"] = db;
            Session["SystemVariables"] = SystemVariableDB.GetAll();

            // Set system staff variables
            int   callCentreStaffID = isExternalStaff ? -5 : (!isStakeHolder ? -7 : -8);
            Staff staff             = StaffDB.GetByID(callCentreStaffID);
            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;

            // Set OrgID in session as external user has OrgID set
            if (isExternalStaff)
            {
                Organisation org = OrganisationDB.GetByID(orgID);
                Session["OrgID"]   = orgID;
                Session["OrgName"] = org.Name;
            }


            Site site = null;
            if (siteID != 0)
            {
                site = SiteDB.GetByID(siteID);
            }
            else
            {
                // log in to same site type if possible, else just log in to site 1
                site = SiteDB.GetSiteByType((SiteDB.SiteType)Convert.ToInt32(Session["SiteTypeID"]), null, db);
                if (site == null)
                {
                    site = SiteDB.GetByID(1);
                }
            }

            Session["SiteID"]         = site.SiteID;
            Session["SiteName"]       = site.Name;
            Session["SiteIsClinic"]   = site.SiteType.ID == 1;
            Session["SiteIsAgedCare"] = site.SiteType.ID == 2;
            Session["SiteIsGP"]       = site.SiteType.ID == 3;
            Session["SiteTypeID"]     = site.SiteType.ID;
            Session["SiteTypeDescr"]  = site.SiteType.Descr;

            Session["IsMultipleSites"] = SiteDB.GetAll().Length > 1;



            // Remove patient list session data for pt searches
            Session.Remove("patientinfo_data");
            Session.Remove("patientlist_data");
            Session.Remove("patientlist_sortexpression");
            Session.Remove("patientinfo_sortexpression");
        }


        // Go to booking page with this org

        if (isExternalStaff)
        {
            Response.Redirect("~/BookingsV2.aspx?orgs=" + Session["OrgID"] + "&ndays=4", false);
        }

        else if (patientID != -1 && orgID != 0)
        {
            Response.Redirect("~/BookingsV2.aspx?orgs=" + orgID + "&patient=" + patientID + "&ndays=4", false);
        }
        else if (patientID != -1 && orgID == 0)
        {
            Response.Redirect("~/PatientDetailV2.aspx?type=view&id=" + patientID, false);
        }

        else
        {
            Response.Redirect("~/Default.aspx", false);
        }
        return;
    }
Exemple #30
0
    protected void GrdRegistration_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlOrganisation   = (DropDownList)GrdRegistration.FooterRow.FindControl("ddlNewOrganisation");
            TextBox      txtProviderNumber = (TextBox)GrdRegistration.FooterRow.FindControl("txtNewProviderNumber");
            CheckBox     chkMainProvider   = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewMainProvider");
            CheckBox     chkIncMondays     = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncMondays");
            CheckBox     chkIncTuesdays    = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncTuesdays");
            CheckBox     chkIncWednesdays  = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncWednesdays");
            CheckBox     chkIncThursdays   = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncThursdays");
            CheckBox     chkIncFridays     = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncFridays");
            CheckBox     chkIncSaturdays   = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncSaturdays");
            CheckBox     chkIncSundays     = (CheckBox)GrdRegistration.FooterRow.FindControl("chkNewIncSundays");


            Staff staff = StaffDB.GetByID(GetFormID());
            if (staff == null)
            {
                HideTableAndSetErrorMessage("");
                return;
            }

            try
            {
                RegisterStaffDB.Insert(Convert.ToInt32(ddlOrganisation.SelectedValue), staff.StaffID, txtProviderNumber.Text, chkMainProvider.Checked,
                                       !chkIncSundays.Checked, !chkIncMondays.Checked, !chkIncTuesdays.Checked, !chkIncWednesdays.Checked, !chkIncThursdays.Checked, !chkIncFridays.Checked, !chkIncSaturdays.Checked);
                if (chkMainProvider.Checked)
                {
                    RegisterStaffDB.UpdateAllOtherStaffAsNotMainProviders(Convert.ToInt32(ddlOrganisation.SelectedValue), staff.StaffID);
                }
            }
            catch (UniqueConstraintException)
            {
                // happens when 2 forms allow adding - do nothing and let form re-update
            }
            FillGrid();
        }

        if (e.CommandName.Equals("_Delete") || e.CommandName.Equals("_UnDelete"))
        {
            int register_staff_id = Convert.ToInt32(e.CommandArgument);

            try
            {
                if (e.CommandName.Equals("_Delete"))
                {
                    RegisterStaffDB.UpdateInactive(register_staff_id);
                }
                else
                {
                    RegisterStaffDB.UpdateActive(register_staff_id);
                }
            }
            catch (CustomMessageException cmEx)
            {
                SetErrorMessage(cmEx.Message);
            }
            catch (ForeignKeyConstraintException fkcEx)
            {
                if (Utilities.IsDev())
                {
                    SetErrorMessage("Can not delete because other records depend on this : " + fkcEx.Message);
                }
                else
                {
                    SetErrorMessage("Can not delete because other records depend on this");
                }
            }

            FillGrid();
        }
    }