Exemplo n.º 1
0
    public static Hashtable GetBulkInvoiceLinesByInvoiceID(Invoice[] invoices)
    {
        Hashtable hash = new Hashtable();

        int[] invoiceIDs = new int[invoices.Length];
        for (int i = 0; i < invoices.Length; i++)
        {
            invoiceIDs[i] = invoices[i].InvoiceID;
        }
        InvoiceLine[] allInvoiceLines = InvoiceLineDB.GetByInvoiceIDs(invoiceIDs);

        foreach (Invoice curInvoice in invoices)
        {
            System.Collections.ArrayList curInvoiceLines = new System.Collections.ArrayList();
            for (int i = 0; i < allInvoiceLines.Length; i++)
            {
                if (allInvoiceLines[i].InvoiceID == curInvoice.InvoiceID)
                {
                    curInvoiceLines.Add(allInvoiceLines[i]);
                }
            }

            hash[curInvoice.InvoiceID] = (InvoiceLine[])curInvoiceLines.ToArray(typeof(InvoiceLine));
        }

        return(hash);
    }
    private void FillEditViewForm()
    {
        InvoiceLine invLine = InvoiceLineDB.GetByID(GetFormID());

        if (invLine == null)
        {
            HideTableAndSetErrorMessage("Invalid InvoiceLine ID");
            return;
        }


        txtFlashingText.Text = invLine.AreaTreated;


        btnSubmit.Text = "Update";
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage();
            return;
        }

        InvoiceLine invLine = InvoiceLineDB.GetByID(GetFormID());

        if (invLine == null)
        {
            HideTableAndSetErrorMessage("Invalid InvoiceLine ID");
            return;
        }

        InvoiceLineDB.UpdateAreaTreated(invLine.InvoiceLineID, txtFlashingText.Text);

        //close this window
        Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=false;self.close();</script>");
    }
Exemplo n.º 4
0
    private void InvoiceItemsControl_SubmitButtonClicked(object sender, EventArgs e)
    {
        try
        {
            if (txtUpdateOrganisationID.Text.Length == 0)
            {
                throw new CustomMessageException("Please select an organisation.");
            }

            Organisation org = OrganisationDB.GetByID(Convert.ToInt32(txtUpdateOrganisationID.Text));
            if (org == null)
            {
                throw new Exception("Unknown organisation selected. Pelase contact your system administrator.");
            }


            // keep id's to delete if exception and need to roll back
            int       invID            = -2;
            ArrayList invLineIDs       = new ArrayList();
            ArrayList offeringOrderIDs = new ArrayList();

            // used to check update stock and check warning level emails sent
            ArrayList invoiceLines = new ArrayList();


            try
            {
                int patientID = txtUpdatePatientID.Text.Length == 0 ? -1 : Convert.ToInt32(txtUpdatePatientID.Text);

                DataTable dt_selected_list = this.invoiceItemsControl.GetSelectedList();

                decimal total = 0;
                decimal gst   = 0;
                for (int i = 0; i < dt_selected_list.Rows.Count; i++)
                {
                    total += Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]);
                    gst   += Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]);
                }

                invID = InvoiceDB.Insert(108, -1, 0, patientID, org.OrganisationID, "", "", Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(Session["SiteID"]), total + gst, gst, false, false, false, DateTime.MinValue);
                for (int i = 0; i < dt_selected_list.Rows.Count; i++)
                {
                    int offeringOrderID = -1;
                    if (Convert.ToBoolean(dt_selected_list.Rows[i]["on_order"]))
                    {
                        OfferingOrderDB.Insert(
                            Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]),
                            org.OrganisationID,
                            Convert.ToInt32(Session["StaffID"]),
                            patientID,
                            Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]),
                            DateTime.Today,
                            DateTime.MinValue,
                            DateTime.MinValue,
                            string.Empty
                            );
                        offeringOrderIDs.Add(offeringOrderID);
                    }


                    int invoiceLineID = InvoiceLineDB.Insert(invID, -1, Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]), Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]) + Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), "", "", offeringOrderID);
                    invLineIDs.Add(invoiceLineID);
                    invoiceLines.Add(new InvoiceLine(invoiceLineID, invID, -1, Convert.ToInt32(dt_selected_list.Rows[i]["offering_id"]), Convert.ToInt32(dt_selected_list.Rows[i]["quantity"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_price"]) + Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), Convert.ToDecimal(dt_selected_list.Rows[i]["total_pt_gst"]), "", "", offeringOrderID));
                }

                Session.Remove("data_selected");


                // successfully completed, so update and check warning level for stocks
                foreach (InvoiceLine invoiceLine in invoiceLines)
                {
                    if (invoiceLine.OfferingOrder == null) // stkip counting down if item is on order
                    {
                        StockDB.UpdateAndCheckWarning(org.OrganisationID, invoiceLine.Offering.OfferingID, (int)invoiceLine.Quantity);
                    }
                }
            }
            catch (Exception ex)
            {
                // roll back...
                foreach (int invLineID in invLineIDs)
                {
                    InvoiceLineDB.Delete(invLineID);
                }
                foreach (int offeringOrderID in offeringOrderIDs)
                {
                    OfferingOrderDB.Delete(offeringOrderID);
                }
                InvoiceDB.Delete(invID);

                throw;
            }

            Response.Redirect("~/Invoice_ViewV2.aspx?invoice_id=" + invID + "&is_popup=0");
            //Response.Redirect("~/InvoiceListV2.aspx?start_date=" + DateTime.Today.ToString("yyyy_MM_dd") + "&end_date=" + DateTime.Today.AddDays(1).ToString("yyyy_MM_dd") + "&inc_medicare=0&inc_dva=0&inc_private=1");
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
            return;
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
            return;
        }
    }
Exemplo n.º 5
0
    protected void FillInvoicesList(DataTable dt_invoices)
    {
        Invoice[] invoices   = new Invoice[dt_invoices.Rows.Count];
        int[]     invoiceIDs = new int[dt_invoices.Rows.Count];


        int countShowing = 0;

        dt_invoices.Columns.Add("message_reversed_wiped", typeof(string));
        dt_invoices.Columns.Add("td_name", typeof(string));                // for use of td 'name' tag to hide all reversed or hide all rejected
        dt_invoices.Columns.Add("style_display", typeof(string));          // to set initially reversed and/or rejected as hidden
        dt_invoices.Columns.Add("inv_debtor", typeof(string));
        dt_invoices.Columns.Add("inv_total_due", typeof(decimal));
        for (int i = 0; i < dt_invoices.Rows.Count; i++)
        {
            Invoice invoice = InvoiceDB.LoadAll(dt_invoices.Rows[i]);

            invoiceIDs[i] = invoice.InvoiceID;
            invoices[i]   = invoice;

            if (invoice.ReversedBy != null)
            {
                dt_invoices.Rows[i]["message_reversed_wiped"] = "Reversed";
                dt_invoices.Rows[i]["td_name"]       = "td_reversed";
                dt_invoices.Rows[i]["style_display"] = "none";
            }
            else if (invoice.PayerOrganisation != null && (invoice.PayerOrganisation.OrganisationID == -1 || invoice.PayerOrganisation.OrganisationID == -2) && invoice.Total > 0 && invoice.CreditNotesTotal >= invoice.Total)
            {
                dt_invoices.Rows[i]["message_reversed_wiped"] = "Rejected";
                dt_invoices.Rows[i]["td_name"]       = "td_rejected";
                dt_invoices.Rows[i]["style_display"] = "none";
            }
            else
            {
                countShowing++;
            }

            if (invoice.PayerOrganisation != null)
            {
                dt_invoices.Rows[i]["inv_debtor"] = invoice.PayerOrganisation.Name;
            }
            else if (invoice.PayerPatient != null)
            {
                dt_invoices.Rows[i]["inv_debtor"] = invoice.PayerPatient.Person.FullnameWithoutMiddlename;
            }
            else
            {
                dt_invoices.Rows[i]["inv_debtor"] = invoice.Booking != null &&
                                                    invoice.Booking.Patient != null &&
                                                    invoice.Booking.Patient.Person != null    ? invoice.Booking.Patient.Person.FullnameWithoutMiddlename : string.Empty; // empty for invoices without bookings
            }
            dt_invoices.Rows[i]["inv_total_due"] = invoice.TotalDue.ToString();
        }


        // single db call to get invoicelines into hashtable lookup by invoice
        Hashtable invoiceLinesHash = InvoiceLineDB.GetBulkInvoiceLinesByInvoiceID(invoices);

        dt_invoices.Columns.Add("inv_lines_text", typeof(string));
        for (int i = 0; i < dt_invoices.Rows.Count; i++)
        {
            Invoice       invoice  = InvoiceDB.LoadAll(dt_invoices.Rows[i]);
            InvoiceLine[] invLines = (InvoiceLine[])invoiceLinesHash[invoice.InvoiceID];

            bool showAreaTreated      = invoice.PayerOrganisation != null && (invoice.PayerOrganisation.OrganisationID == -2 || invoice.PayerOrganisation.OrganisationType.OrganisationTypeID == 150);
            bool showServiceReference = invoice.PayerOrganisation != null && invoice.PayerOrganisation.OrganisationType.OrganisationTypeID == 150;

            string output = "<ul style=\"padding-left:14px;\">";
            foreach (InvoiceLine invLine in invLines)
            {
                string extras = string.Empty;
                if (showAreaTreated || showServiceReference)
                {
                    string linkAreaTreated      = "<a title=\"Edit\" onclick=\"javascript:window.showModalDialog('Invoice_UpdateAreaTreatedV2.aspx?inv_line=" + invLine.InvoiceLineID + "', '', 'dialogWidth:600px;dialogHeight:275px;center:yes;resizable:no; scroll:no');window.location.href=window.location.href;return false;\" href=\"#\">Edit</a>";
                    string linkServiceReference = "<a title=\"Edit\" onclick=\"javascript:window.showModalDialog('Invoice_UpdateServiceReferenceV2.aspx?inv_line=" + invLine.InvoiceLineID + "', '', 'dialogWidth:600px;dialogHeight:275px;center:yes;resizable:no; scroll:no');window.location.href=window.location.href;return false;\" href=\"#\">Edit</a>";

                    extras += "<table>";
                    if (showAreaTreated)
                    {
                        extras += "<tr><td>Area Treated</td><td style=\"min-width:10px;\"></td><td>" + (invLine.AreaTreated.Length == 0 ? "[EMPTY]" : invLine.AreaTreated) + "</td><td style=\"min-width:10px;\"></td><td>" + linkAreaTreated + "</td></tr>";
                    }
                    if (showServiceReference)
                    {
                        extras += "<tr><td>Service Reference</td><td style=\"min-width:10px;\"></td><td>" + (invLine.ServiceReference.Length == 0 ? "[EMPTY]" : invLine.ServiceReference) + "</td><td style=\"min-width:10px;\"></td><td>" + linkServiceReference + "</td></tr>";
                    }
                    extras += "</table>";
                }

                string itemDescr = string.Empty;
                if (invLine.Offering != null)
                {
                    itemDescr = invLine.Offering.Name;
                }
                if (invLine.Credit != null)
                {
                    itemDescr = "Voucher: <i>" + invLine.Credit.VoucherDescr + "</i>";
                }


                output += "<li>" + itemDescr + " x " + ((invLine.Quantity % 1) == 0 ? Convert.ToInt32(invLine.Quantity) : invLine.Quantity) + " = " + invLine.Price + (invLine.Tax == 0 ? "" : " (<i>Inc GST</i>)") + (invLine.Patient.Person == null ? "" : " [" + invLine.Patient.Person.FullnameWithoutMiddlename + "]") + extras + "</li>";
            }
            output += "</ul>";

            dt_invoices.Rows[i]["inv_lines_text"] = output;

            if (countShowing == 0)
            {
                dt_invoices.Rows[i]["style_display"] = "";
            }
        }


        //get approximate page width...
        // 194 = row titles
        // average row = 340 px (about 220-440)
        // add 70px for good measure
        int pageWidth = 194 + 365 * (countShowing == 0 ? 1 : countShowing) + 120;

        Page.ClientScript.RegisterStartupScript(this.GetType(), "resize_window", "<script language=javascript>window.resizeTo(  (" + pageWidth + "+ window.outerWidth - window.innerWidth) < screen.width ? (" + pageWidth + " + window.outerWidth - window.innerWidth) : screen.width , window.outerHeight);</script>");



        if (dt_invoices.Rows.Count <= 1)
        {
            divToggleShowReversedRejected.Visible = false;
        }
        else if (countShowing == 0)
        {
            chkShowReversed.Checked = true;
            chkShowRejected.Checked = true;
        }


        // now databind
        Repeater1.DataSource  = dt_invoices; Repeater1.DataBind();
        Repeater2.DataSource  = dt_invoices; Repeater2.DataBind();
        Repeater3.DataSource  = dt_invoices; Repeater3.DataBind();
        Repeater4.DataSource  = dt_invoices; Repeater4.DataBind();
        Repeater5.DataSource  = dt_invoices; Repeater5.DataBind();
        Repeater6.DataSource  = dt_invoices; Repeater6.DataBind();
        Repeater7.DataSource  = dt_invoices; Repeater7.DataBind();
        Repeater8.DataSource  = dt_invoices; Repeater8.DataBind();
        Repeater9.DataSource  = dt_invoices; Repeater9.DataBind();
        Repeater10.DataSource = dt_invoices; Repeater10.DataBind();
        Repeater11.DataSource = dt_invoices; Repeater11.DataBind();
        Repeater12.DataSource = dt_invoices; Repeater12.DataBind();
        Repeater13.DataSource = dt_invoices; Repeater13.DataBind();
        Repeater14.DataSource = dt_invoices; Repeater14.DataBind();
        Repeater15.DataSource = dt_invoices; Repeater15.DataBind();
        Repeater16.DataSource = dt_invoices; Repeater16.DataBind();
        Repeater17.DataSource = dt_invoices; Repeater17.DataBind();
        Repeater18.DataSource = dt_invoices; Repeater18.DataBind();
        Repeater19.DataSource = dt_invoices; Repeater19.DataBind();


        // non booking invoices (ie standard invoices) will not have a booking
        Booking booking = invoices[0].Booking;

        if (booking != null)
        {
            string patientText = string.Empty;
            if (booking != null && booking.Patient != null)
            {
                patientText = booking.Patient.Person.FullnameWithoutMiddlename;
            }
            else if (invoices[0].PayerPatient != null)
            {
                patientText = invoices[0].PayerPatient.Person.FullnameWithoutMiddlename;
            }
            else
            {
                patientText = "< No patient >";
            }


            // show booking info
            lblBooking_Org.Text                = booking.Organisation.Name;
            lblBooking_Provider.Text           = booking.Provider.Person.FullnameWithoutMiddlename;
            lblBooking_Patient.Text            = patientText;  // booking.Patient.Person.FullnameWithoutMiddlename;
            lblBooking_Offering.Text           = booking.Offering == null ? "< No service >" : booking.Offering.Name;
            lblBooking_BookingStatus.Text      = booking.BookingStatus.Descr;
            lblBooking_Time.Text               = booking.DateStart.Date.ToString("dd MMM yyyy") + " - " + booking.DateStart.ToString("h:mm") + (booking.DateStart.Hour < 12 ? "am" : "pm") + "-" + booking.DateEnd.ToString("h:mm") + (booking.DateEnd.Hour < 12 ? "am" : "pm");
            lblBooking_PatientMissedAppt.Text  = booking.IsPatientMissedAppt ? "Yes" : "No";
            lblBooking_ProviderMissedAppt.Text = booking.IsProviderMissedAppt ? "Yes" : "No";
            lblBooking_Emergency.Text          = booking.IsEmergency ? "Yes" : "No";
            lblBooking_Notes.Text              = Note.GetPopupLinkTextV2(15, booking.EntityID, booking.NoteCount > 0, true, 1050, 530, "images/notes-bw-24.jpg", "images/notes-24.png");
        }
        else
        {
            booking_space.Visible                  = false;
            booking_title.Visible                  = false;
            booking_offering.Visible               = false;
            booking_patient.Visible                = false;
            booking_provider.Visible               = false;
            booking_org.Visible                    = false;
            booking_status.Visible                 = false;
            booking_apptmt_time.Visible            = false;
            booking_patiemt_missed_apptmt.Visible  = false;
            booking_provider_missed_apptmt.Visible = false;
            booking_isemergency.Visible            = false;
            booking_notes.Visible                  = false;
        }
    }
    protected void Save(SaveType saveType)
    {
        if (Request.QueryString["debug"] != null && Request.QueryString["debug"] == "1")
        {
            lblXML.Text = "<pre>" + hiddenResponse.Value.Replace("<", "&lt;").Replace(">", "&gt;").Replace(Environment.NewLine, "<br />") + "</pre>";
        }

        Invoice invoice = InvoiceDB.GetByID(Convert.ToInt32(Request.QueryString["invoice"]));

        InvoiceLine[] invLines = InvoiceLineDB.GetByInvoiceID(invoice.InvoiceID);


        using (XmlReader reader = XmlReader.Create(new StringReader(hiddenResponse.Value)))
        {
            reader.ReadToFollowing("detail");

            string tyro_transaction_id = reader.GetAttribute("tyro_transaction_id");

            string result = reader.GetAttribute("result");
            string healthpointErrorCode                  = reader.GetAttribute("healthpointErrorCode");
            string healthpointErrorDescription           = reader.GetAttribute("healthpointErrorDescription");
            string healthpointRefTag                     = reader.GetAttribute("healthpointRefTag");
            string healthpointTotalBenefitAmount         = reader.GetAttribute("healthpointTotalBenefitAmount");
            string healthpointSettlementDateTime         = reader.GetAttribute("healthpointSettlementDateTime");
            string healthpointTerminalDateTime           = reader.GetAttribute("healthpointTerminalDateTime");
            string healthpointMemberNumber               = reader.GetAttribute("healthpointMemberNumber");
            string healthpointProviderId                 = reader.GetAttribute("healthpointProviderId");
            string healthpointServiceType                = reader.GetAttribute("healthpointServiceType");
            string healthpointGapAmount                  = reader.GetAttribute("healthpointGapAmount");
            string healthpointPhfResponseCode            = reader.GetAttribute("healthpointPhfResponseCode");
            string healthpointPhfResponseCodeDescription = reader.GetAttribute("healthpointPhfResponseCodeDescription");



            if (result != "APPROVED")
            {
                var errMsg = "<br />Result: <b>" + result + "</b>";

                if (healthpointErrorCode != "" && healthpointErrorDescription != "")
                {
                    errMsg += "<br />" + healthpointErrorDescription + " (Error Code " + healthpointErrorCode + ")";
                }
                else if (healthpointErrorCode != "")
                {
                    errMsg += "<br />Error Code: " + healthpointErrorCode;
                }
                else if (healthpointErrorDescription != "")
                {
                    errMsg += "<br />Error: " + healthpointErrorDescription;
                }

                lblErrorMessage.Text = errMsg;

                // Email alert this

                return;
            }



            if (saveType == SaveType.Claim)
            {
                DateTime _healthpointSettlementDateTime;
                if (healthpointSettlementDateTime == "undefined")
                {
                    _healthpointSettlementDateTime = DateTime.MinValue;
                }
                else if (!DateTime.TryParseExact(healthpointSettlementDateTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _healthpointSettlementDateTime))
                {
                    throw new Exception("healthpointSettlementDateTime not in correct format: " + healthpointSettlementDateTime);
                }

                DateTime _healthpointTerminalDateTime;
                if (healthpointTerminalDateTime == "undefined")
                {
                    _healthpointTerminalDateTime = DateTime.MinValue;
                }
                else if (!DateTime.TryParseExact(healthpointTerminalDateTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _healthpointTerminalDateTime))
                {
                    throw new Exception("healthpointTerminalDateTime not in correct format: " + healthpointTerminalDateTime);
                }

                decimal paymentAmount = Convert.ToDecimal(healthpointTotalBenefitAmount) / 100;
                decimal gapAmount     = saveType == SaveType.Claim ? Convert.ToDecimal(healthpointGapAmount) / 100 : 0;

                TyroHealthClaimDB.UpdateByTyroTransactionID(
                    tyro_transaction_id,
                    result,
                    healthpointRefTag,
                    paymentAmount,
                    _healthpointSettlementDateTime,
                    _healthpointTerminalDateTime,
                    healthpointMemberNumber,
                    healthpointProviderId,
                    healthpointServiceType,
                    gapAmount,
                    healthpointPhfResponseCode,
                    healthpointPhfResponseCodeDescription);

                TyroHealthClaim tyroHealthClaim = TyroHealthClaimDB.GetByByTyroTransactionID(tyro_transaction_id);

                while (reader.ReadToFollowing("claimItem"))
                {
                    string claimAmount      = reader.GetAttribute("claimAmount");
                    string rebateAmount     = reader.GetAttribute("rebateAmount");
                    string serviceCode      = reader.GetAttribute("serviceCode");
                    string description      = reader.GetAttribute("description");
                    string serviceReference = reader.GetAttribute("serviceReference");
                    string patientId        = reader.GetAttribute("patientId");
                    string serviceDate      = reader.GetAttribute("serviceDate");
                    string responseCode     = reader.GetAttribute("responseCode");

                    DateTime _serviceDate;
                    if (serviceDate == "undefined")
                    {
                        _serviceDate = DateTime.MinValue;
                    }
                    else if (!DateTime.TryParseExact(serviceDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _serviceDate))
                    {
                        throw new Exception("serviceDate not in correct format: " + serviceDate);
                    }

                    TyroHealthClaimItemDB.Insert(
                        tyroHealthClaim.TyroHealthClaimID,
                        Convert.ToDecimal(claimAmount) / 100,
                        Convert.ToDecimal(rebateAmount) / 100,
                        serviceCode,
                        description,
                        serviceReference,
                        patientId,
                        _serviceDate,
                        responseCode);
                }


                if (result == "APPROVED")
                {
                    decimal totalOwed  = invoice.TotalDue - paymentAmount;
                    bool    isOverPaid = totalOwed < 0;
                    bool    isPaid     = totalOwed <= 0;

                    ReceiptDB.Insert(null, 365, tyroHealthClaim.InvoiceID, paymentAmount, 0, false, isOverPaid, DateTime.MaxValue, -8);

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

                    if (isOverPaid)
                    {
                        // send email to someone .. to fix up the overpayment....
                        Emailer.SimpleAlertEmail(
                            "Tyro healthpoint invoice late payment added and is overpaid.<br />tyro_health_claim_id: " + tyroHealthClaim.TyroHealthClaimID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + Session["DB"],
                            "Tyro Healthpoint Invoice OverPaid: " + invoice.InvoiceID,
                            true);
                    }
                }

                string cancelLink = "<a href='TyroHealthPointClaimV2.aspx?invoice=" + invoice.InvoiceID + "&reftag=" + healthpointRefTag + "'>Click Here</a>";
                lblResult.Text = "Result: " + result + (result == "APPROVED" ? "<br />Updated Paid Amounts Shown Above<br />To Cancel This Claim " + cancelLink : "") + "<br /><br />";
            }
            else
            {
                if (result == "APPROVED")
                {
                    TyroHealthClaimDB.UpdateCancelled(healthpointRefTag);

                    // set receipt as reversed
                    TyroHealthClaim tyroHealthClaim = TyroHealthClaimDB.GetByRefTag(healthpointRefTag);

                    Receipt[] receipts = ReceiptDB.GetByInvoice(tyroHealthClaim.InvoiceID, false);
                    if (receipts.Length != 1 || receipts[0].ReceiptPaymentType.ID != 365)
                    {
                        Emailer.SimpleAlertEmail(
                            "Tyro claim reversed (by Tyro) but multiple receipts or receipt not of type 'Tyro HC Claim'.<br />healthpointRefTag = " + healthpointRefTag + "<br />DB: " + Session["DB"],
                            "Tyro claim reversed (by Tyro) but multiple receipts or receipt not of type 'Tyro HC Claim'",
                            true
                            );
                    }

                    ReceiptDB.Reverse(receipts[0].ReceiptID, Convert.ToInt32(Session["StaffID"]));
                }

                lblResult.Text = "Cancellation Result: " + result + (result == "APPROVED" ? "<br />Updated Paid Amounts Shown Above" : "") + "<br /><br />";
            }
        }

        SetInvoiceInfo(InvoiceDB.GetByID(invoice.InvoiceID));
    }
    protected void SetInvoiceInfo(Invoice invoice)
    {
        bool isDebug          = Request["debug"] != null && Request["debug"] == "1";
        bool useOnlyTestItems = false;

        SaveType saveType = Request.QueryString["reftag"] != null ? SaveType.Cancellation : SaveType.Claim;

        string receiptString = string.Empty;

        foreach (Receipt receipt in ReceiptDB.GetByInvoice(invoice.InvoiceID, false))
        {
            receiptString += (receiptString.Length == 0 ? "" : ", ") + "$" + receipt.Total.ToString();
        }

        string invoiceViewURL = "/Invoice_ViewV2.aspx?invoice_id=" + invoice.InvoiceID;

        lblInvoiceID.Text      = "<a href=\"" + invoiceViewURL + "\" onclick=\"open_new_tab('" + invoiceViewURL + "');return false;\">" + invoice.InvoiceID + "</a>";
        lblInvoiceTotal.Text   = "$" + invoice.Total.ToString();
        lblInvoiceOwing.Text   = "$" + invoice.TotalDue.ToString();
        lblReceiptedTotal.Text = "$" + invoice.ReceiptsTotal.ToString() + (invoice.CreditNotesTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.CreditNotesTotal.ToString() + " Credit Noted)") + (invoice.RefundsTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.RefundsTotal.ToString() + " Refunds)");
        lblDebtor.Text         = invoice.GetDebtor(true);
        lblBkDate.Text         = invoice.Booking.DateStart.ToString("d MMM, yyyy");
        lblBkOrgText.Text      = invoice.Booking.Organisation.IsAgedCare? "Facility" : "Clinic";
        lblBkOrg.Text          = invoice.Booking.Organisation.Name;

        System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "field_id=" + invoice.Booking.Provider.Field.ID, "", "field_id", "descr");
        invoice.Booking.Provider.Field = IDandDescrDB.Load(tbl.Rows[0], "field_id", "descr");

        RegisterStaff regStaff = RegisterStaffDB.GetByStaffIDAndOrganisationID(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID);

        if (regStaff == null)
        {
            throw new CustomMessageException("Staff Member Not Set To This Clinic/Fac.");
        }

        InvoiceLine[] invLines = InvoiceLineDB.GetByInvoiceID(invoice.InvoiceID);
        Hashtable     patientHealthCardCache = PatientsHealthCardsCacheDB.GetBullkActive(invLines.Select(x => x.Patient.PatientID).ToArray());

        List <TyroHealthPointClaimIten> claimItems = new List <TyroHealthPointClaimIten>();

        for (int i = 0; i < invLines.Length; i++)
        {
            HealthCard hc = GetHealthCardFromCache(patientHealthCardCache, invLines[i].Patient.PatientID);

            string ptURL  = "PatientDetailV2.aspx?type=view&id=" + invLines[i].Patient.PatientID;
            string ptLink = "<a href=\"" + ptURL + "\" onclick=\"open_new_tab('" + ptURL + "');return false;\">" + invLines[i].Patient.Person.FullnameWithoutMiddlename + "</a>";

            if (hc == null)
            {
                throw new CustomMessageException("No healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ")");
            }
            if (hc.Organisation.OrganisationType.OrganisationTypeID != 150)
            {
                throw new CustomMessageException("Healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ") Is Not An Insurance Card");
            }

            /*
             * claim-amount:      claim amount in cents                    - max 10 digits
             * service-code:      item number service code                 - max 5  characters
             * description:       description of item to appear on receipt - max 32 characters
             * service-reference: body part or tooth number suffix         - max 3  characters
             * patient-id:        patient ID on card                       - exactly 2 digits
             * service-date:      claim date in YYYYMMDD format
             */

            isDebug = true;

            claimItems.Add(new TyroHealthPointClaimIten(
                               ((int)(invLines[i].Price * 100)).ToString(),
                               isDebug ? "F1234" : invLines[i].Offering.TacCompanyCode,
                               isDebug ? "Face"  : invLines[i].AreaTreated,
                               invLines[i].ServiceReference,
                               "",      // family number on card -- legally they have to enter it themselves
                               isDebug ? DateTime.Today.ToString("yyyyMMdd") : invoice.Booking.DateStart.ToString("yyyyMMdd")));
        }


        //useOnlyTestItems = true;

        // save variables & JSON array on the page accessable to JS to send to Tyro
        if (useOnlyTestItems)
        {
            claimItems = new List <TyroHealthPointClaimIten>();

            claimItems.Add(new TyroHealthPointClaimIten(
                               "10000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            claimItems.Add(new TyroHealthPointClaimIten(
                               "15000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                var _providerId       = '4237955J';
                var _serviceType      = 'D';
                var _claimItemsCount  = '2';
                var _totalClaimAmount = '25000';
                var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) + @"; 
             </script>");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                    var _providerId       = '" + (isDebug ? "4237955J" : (regStaff.ProviderNumber.Length > 0 ? regStaff.ProviderNumber : invoice.Booking.Provider.ProviderNumber)) + @"';
                    var _serviceType      = '" + GetServiceTypeHashtable()[invoice.Booking.Provider.Field.Descr.ToLower()].ToString() + @"';
                    var _claimItemsCount  = '" + invLines.Length.ToString() + @"';
                    var _totalClaimAmount = '" + ((int)(invLines.Sum(item => item.Price) * 100)).ToString() + @"';
                    var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) /* convert to JSON array */ + @"; 
                    " + (saveType == SaveType.Cancellation ? "var _refTag = " + Request.QueryString["reftag"] : string.Empty) + @"
                 </script>");
        }
    }
Exemplo n.º 8
0
    public void CreateXML(Invoice[] invoices, bool validate = true)
    {
        if (validate)
        {
            Invoice[] tooOldList = GetInvoicesTooOldToClaim(invoices);
            if (tooOldList.Length > 0)
            {
                string invalids = string.Empty;
                foreach (Invoice i in tooOldList)
                {
                    invalids += (invalids.Length == 0 ? "" : ",") + i.InvoiceID.ToString();
                }
                throw new Exception("The following invoices are too old to claim: " + "<br />" + invalids);
            }
        }

        // get bulk invoice lines for less db calls in individual invoice create xml method  [invoiceID => list of invoicelines]
        Hashtable bulkInvoiceLineHash = InvoiceLineDB.GetBulkInvoiceLinesByInvoiceID(invoices);

        ArrayList allInvoiceLines = new ArrayList();

        foreach (DictionaryEntry pair in bulkInvoiceLineHash)
        {
            allInvoiceLines.AddRange((InvoiceLine[])pair.Value);
        }

        // get bluk health cards  [patientID=>healthcard]
        //
        // NB:
        // A DVA invoice can only use a DVA card
        // A Medicare invoice can only use a Medicare card
        // The system can only create a DVA invoice is if DVA is set as the active card (vice versa for Medicare)
        // So when a DVA invoice is created the DVA card was active, and then someone switches it to be the Medicare card thatis active.
        // So, it's correct to get only the DVA cards for DVA invoices (and Medicare cards for Medicare invoices), and also would be correct to ignore the active flag and just get the most recent.
        int[]     allPatientIDs      = GetAllPatientIDs((InvoiceLine[])allInvoiceLines.ToArray(typeof(InvoiceLine)));
        Hashtable bulkHealthCardHash = PatientsHealthCardsCacheDB.GetBullkMostRecent(allPatientIDs, claimType == ClaimType.Medicare ? -1 : -2);

        // get bluk staff provider numbers from registerstaff table
        int[]     allProviderStaffIDs   = GetAllProviderStaffIDs(invoices);
        Hashtable bulkRegisterStaffHash = RegisterStaffDB.Get2DHashByStaffIDOrgID(allProviderStaffIDs);
        Hashtable bulkStaffHash         = StaffDB.GetAllInHashtable(false, true, false, false);

        // get bluk healthcard actions to get EPC signed dates
        Hashtable bulkHealthCardActionsHash = HealthCardActionDB.GetReceivedActionsByPatientIDs(allPatientIDs);

        // get bluk epcreferrers
        Hashtable bulkEPCReferrersHash = PatientReferrerDB.GetEPCReferrersOf(allPatientIDs, false);

        // get all sites in one call
        Hashtable bulkSites = SiteDB.GetAllInHashtable();


        Hashtable claimNumberInvoiceGroups = new Hashtable();

        for (int i = 0; i < invoices.Length; i++)
        {
            if (claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] == null)
            {
                claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] = new ArrayList();
            }

            ((ArrayList)claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber]).Add(invoices[i]);
        }


        string noPatientFailures    = string.Empty;
        string noHealthcardFailures = string.Empty;

        foreach (string claimNbr in claimNumberInvoiceGroups.Keys)
        {
            Invoice[] invoiceList = (Invoice[])((ArrayList)claimNumberInvoiceGroups[claimNbr]).ToArray(typeof(Invoice));

            try
            {
                CreateXML(invoiceList, bulkInvoiceLineHash, bulkHealthCardHash, bulkRegisterStaffHash, bulkStaffHash, bulkSites, bulkHealthCardActionsHash, bulkEPCReferrersHash);
            }
            catch (HINXNoPatientOnInvoiceLineException ex)
            {
                noPatientFailures += (noPatientFailures.Length == 0 ? "" : "<br />") + ex.Message;
            }
            catch (HINXNoHealthcardException ex)
            {
                noHealthcardFailures += (noHealthcardFailures.Length == 0 ? "" : "<br />") + ex.Message;
            }
        }



        string errors = string.Empty;

        if (noPatientFailures.Length > 0)
        {
            errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have invoices lines with no patient set (Fix this and re-generate): <br />" + noPatientFailures;
        }
        if (noHealthcardFailures.Length > 0)
        {
            errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have patients with no " + (claimType == ClaimType.Medicare ? "Medicare" : "DVA") + " card set (Fix this and re-generate): <br />" + noHealthcardFailures;
        }
        if (errors.Length > 0)
        {
            throw new HINXUnsuccessfulItemsException(errors);
        }
    }
Exemplo n.º 9
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (GetUrlParamType() == UrlParamType.View)
        {
            maintable.Visible = false; // hide this so that we don't send all the page data (all suburbs, etc) to display before it redirects
            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "edit"));
        }
        else if (GetUrlParamType() == UrlParamType.Edit)
        {
            try
            {
                UrlParamCreditType urlParamCreditType = GetUrlParamCreditType();

                if (urlParamCreditType != UrlParamCreditType.Add)
                {
                    throw new CustomMessageException("Can no edit a '" + GetUrlParamCreditType().ToString() + "'");
                }

                if (!ddlExpiryValidateAllOrNoneSet.IsValid)
                {
                    return;
                }

                Credit credit = CreditDB.GetByID(GetFormID());

                /*
                 * txtAmount.Text = txtAmount.Text.Trim();
                 * if (txtAmount.Text.StartsWith("$")) txtAmount.Text = txtAmount.Text.Substring(1);
                 * decimal amount;
                 * if (!decimal.TryParse(txtAmount.Text, out amount))
                 *  throw new CustomMessageException("Amount must be a valid amount.");
                 */

                if (urlParamCreditType == UrlParamCreditType.Add)
                {
                    CreditDB.Update(credit.CreditID, credit.CreditType.ID, credit.EntityID, credit.Amount, txtDescr.Text.Trim(), GetExpiryFromForm(), credit.VoucherCredit == null ? -1 : credit.VoucherCredit.CreditID, credit.InvoiceID, credit.TyroPaymentPendingID, Convert.ToInt32(Session["StaffID"]));
                }


                Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view"));
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
            }
        }
        else if (GetUrlParamType() == UrlParamType.Add)
        {
            try
            {
                UrlParamCreditType urlParamCreditType = GetUrlParamCreditType();

                if (urlParamCreditType != UrlParamCreditType.Add)
                {
                    throw new CustomMessageException("Can no add a '" + GetUrlParamCreditType().ToString() + "'");
                }

                if (!ddlExpiryValidateAllOrNoneSet.IsValid)
                {
                    return;
                }

                int entityID = GetFormID();

                txtAmount.Text = txtAmount.Text.Trim();
                if (txtAmount.Text.StartsWith("$"))
                {
                    txtAmount.Text = txtAmount.Text.Substring(1);
                }
                decimal amount;
                if (!decimal.TryParse(txtAmount.Text, out amount))
                {
                    throw new CustomMessageException("Amount must be a valid amount.");
                }

                int credit_type_id = -1;
                if (urlParamCreditType == UrlParamCreditType.Add)
                {
                    credit_type_id = 1;
                }
                else if (urlParamCreditType == UrlParamCreditType.Use)
                {
                    credit_type_id = 2;
                }
                else if (urlParamCreditType == UrlParamCreditType.CashoutTyroToMC)
                {
                    credit_type_id = 3;
                }
                else if (urlParamCreditType == UrlParamCreditType.CashoutMCtoPT)
                {
                    credit_type_id = 4;
                }
                else
                {
                    throw new CustomMessageException("Invalid URL Field ct");
                }


                bool refresh_on_close = Request.QueryString["refresh_on_close"] != null && Request.QueryString["refresh_on_close"] == "1";

                if (urlParamCreditType == UrlParamCreditType.Add)
                {
                    int creditID = CreditDB.Insert_AddVoucher(entityID, amount, txtDescr.Text.Trim(), GetExpiryFromForm(), Convert.ToInt32(Session["StaffID"]));

                    // need non booking org .. to put on invoice .....
                    // so need to put it in gui .. only for adding type 1

                    Patient patient       = PatientDB.GetByEntityID(entityID);
                    int     invID         = InvoiceDB.Insert(108, -1, 0, patient.PatientID, Convert.ToInt32(ddlClinic.SelectedValue), "", "", Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(Session["SiteID"]), amount, 0, false, false, false, DateTime.MinValue);
                    int     invoiceLineID = InvoiceLineDB.Insert(invID, patient.PatientID, -1, creditID, 1, amount, 0, "", "", -1);

                    System.Drawing.Size size = Receipt.GetPopupWindowAddSize();
                    size = new System.Drawing.Size(size.Width + 15, size.Height + 60);
                    Response.Redirect("~/Invoice_ReceiptAndCreditNoteAddV2.aspx?id=" + invID + "&returnValue=false&window_size=" + size.Width + "_" + size.Height + (refresh_on_close ? "&refresh_on_close=1" : ""), false);
                    return;
                }



                // close this window

                maintable.Visible = false;

                if (refresh_on_close)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.opener.location.href=window.opener.location.href;self.close();</script>");
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=false;self.close();</script>");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
            }
        }
        else
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
        }
    }