예제 #1
0
    public static void Reverse(int receipt_id, int reversed_by)
    {
        Receipt receipt = ReceiptDB.GetByID(receipt_id);

        if (receipt == null)
        {
            throw new ArgumentException("Invalid receipt id :" + receipt_id);
        }
        if (receipt.IsReversed)
        {
            throw new ArgumentException("Receipt already reversed");
        }
        if (receipt.IsReconciled)
        {
            throw new ArgumentException("Can not reverse a receipt that has been reconciled");
        }


        // remove any overpayment records for this receipt
        OverpaymentDB.DeleteByReceiptID(receipt_id);

        // set total=0, set not overpaid, set who and when it was reversed, and original amount
        string sql = "UPDATE Receipt SET total = 0, is_overpaid = 0 ,reversed_by = " + reversed_by + ",reversed_date = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',pre_reversed_amount = " + receipt.Total + " WHERE receipt_id = " + receipt_id.ToString();

        DBBase.ExecuteNonResult(sql);

        // set invoice as not paid
        InvoiceDB.UpdateIsPaid(null, receipt.Invoice.InvoiceID, false);

        // update the GL for the year this was done
    }
예제 #2
0
    public static Hashtable GetBulkReceiptsByInvoiceID(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;
        }
        Receipt[] allcurReceipts = ReceiptDB.GetByInvoiceIDs(invoiceIDs);

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

            hash[curInvoice.InvoiceID] = (Receipt[])curReceipts.ToArray(typeof(Receipt));
        }

        return(hash);
    }
예제 #3
0
    protected void GrdSummaryReport_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "SetReconciled")
        {
            int receiptID = Convert.ToInt32(e.CommandArgument);
            ReceiptDB.SetReconciled(receiptID);
            FillGrid();

            Receipt receipt = ReceiptDB.GetByID(receiptID);
            SetErrorMessage("Receipt " + receiptID + " for Invoice " + receipt.Invoice.InvoiceID + " set as reconciled");
        }
    }
예제 #4
0
    protected void ReverseReceipt_Command(object sender, CommandEventArgs e)
    {
        try
        {
            // for some reason, it doesn't keep the command argument when set in
            // the code behind in a nested repeater, so set it in a hidden control and its fine

            //int receiptID = Convert.ToInt32(e.CommandArgument);

            int receiptID = -1;
            foreach (Control c in ((Control)sender).Parent.Controls)
            {
                if (c.ID == "lblHiddenReceiptID")
                {
                    receiptID = Convert.ToInt32(((HiddenField)c).Value);
                }
            }


            Receipt receipt = ReceiptDB.GetByID(receiptID);
            if (receipt == null)
            {
                throw new CustomMessageException("Invalid receipt - does not exist");
            }
            if (receipt.IsReversed)
            {
                throw new CustomMessageException("Receipt already reversed");
            }
            if (receipt.IsReconciled)
            {
                throw new CustomMessageException("Can not reverse a receipt that has been reconciled");
            }
            //if (receipt.ReceiptPaymentType.ID == 365)
            //    throw new CustomMessageException("Can not reverse a 'Tyro HC Claim' receipt");

            ReceiptDB.Reverse(receipt.ReceiptID, Convert.ToInt32(Session["StaffID"]));

            FillInvoicesList();
        }
        catch (CustomMessageException cmEx)
        {
            SetErrorMessage(cmEx.Message);
        }
        catch (Exception ex)
        {
            SetErrorMessage("", ex.ToString());
        }
    }
예제 #5
0
    protected void Update()
    {
        string tyro_transaction_id      = UrlTyroTransactionID;
        string out_result               = UrlOutResult;
        string out_cardType             = UrlOutCardType;
        string out_transactionReference = UrlOutTransactionReference;
        string out_authorisationCode    = UrlOutAuthorisationCode;
        string out_issuerActionCode     = UrlOutIssuerActionCode;

        if (tyro_transaction_id == null)
        {
            throw new Exception("Invalid url field tyro_transaction_id");
        }
        if (out_result == null)
        {
            throw new Exception("Invalid url field out_result");
        }
        if (out_cardType == null)
        {
            throw new Exception("Invalid url field out_cardType");
        }
        if (out_transactionReference == null)
        {
            throw new Exception("Invalid url field out_transactionReference");
        }
        if (out_authorisationCode == null)
        {
            throw new Exception("Invalid url field out_authorisationCode");
        }
        if (out_issuerActionCode == null)
        {
            throw new Exception("Invalid url field out_issuerActionCode");
        }

        TyroPaymentPendingDB.UpdateByTyroTransactionID(null, tyro_transaction_id, out_result, out_cardType, out_transactionReference, out_authorisationCode, out_issuerActionCode, DateTime.Now);

        if (out_result == "APPROVED")
        {
            TyroPaymentPending tyroPaymentPending = TyroPaymentPendingDB.GetByByTyroTransactionID(null, tyro_transaction_id);

            Invoice invoice = InvoiceDB.GetByID(tyroPaymentPending.InvoiceID);

            int staffID = Session == null || Session["StaffID"] == null ? -8 : Convert.ToInt32(Session["StaffID"]);

            if (tyroPaymentPending.TyroPaymentTypeID == 1) // payment
            {
                decimal totalOwed  = invoice.TotalDue - tyroPaymentPending.Amount;
                bool    isOverPaid = totalOwed < 0;
                bool    isPaid     = totalOwed <= 0;

                ReceiptDB.Insert(null, 364, tyroPaymentPending.InvoiceID, tyroPaymentPending.Amount, 0, false, isOverPaid, DateTime.MaxValue, staffID);

                if (tyroPaymentPending.Cashout > 0)
                {
                    CreditDB.Insert_Cashout(tyroPaymentPending.Cashout, tyroPaymentPending.TyroPaymentPendingID, staffID);
                }

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

                if (isOverPaid)
                {
                    // send email to someone .. to fix up the overpayment....
                    Emailer.SimpleAlertEmail(
                        "Invoice tyro payment added and is overpaid.<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + (Session == null || Session["DB"] == null ? "" : Session["DB"]),
                        "Tyro Invoice OverPaid: " + invoice.InvoiceID,
                        true);
                }
            }
            if (tyroPaymentPending.TyroPaymentTypeID == 2) // refund
            {
                decimal totalOwed = invoice.TotalDue + tyroPaymentPending.Amount;
                bool    isPaid    = totalOwed <= 0;

                RefundDB.Insert(tyroPaymentPending.InvoiceID, tyroPaymentPending.Amount, 308, "", staffID);

                if (totalOwed > 0)
                {
                    InvoiceDB.UpdateIsPaid(null, tyroPaymentPending.InvoiceID, false);
                }
            }
        }

        Response.Write("1"); // to indicate it was successful
    }
예제 #6
0
    protected void lstReceipts_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataRowView dr = (DataRowView)e.Item.DataItem;
            if (dr == null || dr.Row == null)
            {
                return;
            }
            DataRow row = dr.Row;


            Label       lnkViewReceipt             = (Label)e.Item.FindControl("lnkViewReceipt");
            Label       lblPaidBy                  = (Label)e.Item.FindControl("lblPaidBy");
            Label       lblReceiptDate             = (Label)e.Item.FindControl("lblReceiptDate");
            Label       lblPaymentType             = (Label)e.Item.FindControl("lblPaymentType");
            Label       lblReceiptTotal            = (Label)e.Item.FindControl("lblReceiptTotal");
            Label       lblReceiptAmountReconciled = (Label)e.Item.FindControl("lblReceiptAmountReconciled");
            Label       lblStatus                  = (Label)e.Item.FindControl("lblStatus");
            Label       lnkReconcile               = (Label)e.Item.FindControl("lnkReconcile");
            LinkButton  lnkReverse                 = (LinkButton)e.Item.FindControl("lnkReverse");
            HiddenField lblHiddenReceiptID         = (HiddenField)e.Item.FindControl("lblHiddenReceiptID");


            lnkViewReceipt.Text             = row["receipt_url"].ToString();
            lblPaidBy.Text                  = "<a href=javascript:void(0)'  style='text-decoration:none;' onclick='return false;' title='Entered By: " + row["person_firstname"] + " " + row["person_surname"] + "'> * </a>";
            lblReceiptDate.Text             = Convert.ToDateTime(row["receipt_date_added"]).ToString("dd-MM-yyyy");
            lblPaymentType.Text             = row["descr"].ToString();
            lblReceiptTotal.Text            = row["total"].ToString();
            lblReceiptAmountReconciled.Text = row["amount_reconciled"].ToString();

            lblStatus.Text    = row["status"].ToString();
            lblStatus.Visible = row["show_status"].ToString() == "1";

            lnkReconcile.Text    = row["reconcile_link"].ToString() + "<br />";
            lnkReconcile.Visible = row["show_reconcile_link"].ToString() == "1";

            lnkReverse.CommandArgument = row["receipt_id"].ToString();
            lnkReverse.Visible         = row["show_reverse_link"].ToString() == "1";
            lnkReverse.OnClientClick   = "javascript:if (!confirm('Are you sure you want to reverse this record?')) return false;";
            lblHiddenReceiptID.Value   = row["receipt_id"].ToString();


            // if tyro healthclaim invoice .. then open new tab to remove claim throught tyro
            Receipt receipt = ReceiptDB.GetByID(Convert.ToInt32(row["receipt_id"]));
            if (receipt.ReceiptPaymentType.ID == 365 && !receipt.IsReversed)  // Tyro HC Claim
            {
                TyroHealthClaim[] claims = TyroHealthClaimDB.GetByInvoice(receipt.Invoice.InvoiceID);
                //if (true)
                if (claims.Length != 1)
                {
                    Emailer.SimpleAlertEmail(
                        "Receipt " + receipt.ReceiptPaymentType.ID + " is of type 'Tyro HC Claim' but " + claims.Length + " approved uncancelled rows found in TyroHealthClaimDB<br />DB:" + Session["DB"],
                        "Tyro Problem - Multiple Approved Uncancelled TyroPayment Rows Found For Single Receipt",
                        true);

                    lnkReverse.OnClientClick = "alert('Receipt " + receipt.ReceiptPaymentType.ID + " is of type 'Tyro HC Claim' but " + claims.Length + " approved uncancelled rows found in TyroHealthClaimDB.\r\nPlease contact the system administrator to check into this');return false;";
                }
                else
                {
                    lnkReverse.OnClientClick = "open_new_tab('TyroHealthPointClaimV2.aspx?invoice=" + receipt.Invoice.InvoiceID + "&reftag=" + claims[0].OutHealthpointRefTag + "');return false;";
                }
            }
        }
    }
예제 #7
0
    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;
        }
    }
예제 #8
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);
    }
    public static void Reconcile(string DB, DateTime date, string xml)
    {
        /*
         * string xmlString =
         *    @"<?xml version=""1.0"" encoding=""UTF-8""?>
         *      <reconciliation-detail mid=""200"" tid=""200"" terminal-business-day=""2015-04-14"" total=""1620.00"">
         *      <transaction type=""purchase"" card-type=""visa"" amount=""100.00"" tip=""10.00"" transaction-local-date-time=""2015-04-14 12:30:30"" tyro-reference=""870020"" merchant-reference=""071061048231306351219677"" settlement-date=""2015-04-16""/>
         *      <transaction type=""purchase"" card-type=""mastercard"" amount=""200.00"" transaction-local-date-time=""2015-04-14 12:31:20"" tyro-reference=""885214"" merchant-reference=""071061048231306351219678"" settlement-date=""2015-04-16""/>
         *      <transaction type=""purchase"" card-type=""jcb"" amount=""40.00"" transaction-local-date-time=""2015-04-14 12:33:23"" tyro-reference=""896534"" merchant-reference=""071061048231306351219679""/>
         *      <transaction type=""purchase"" card-type=""amex"" amount=""30.00"" transaction-local-date-time=""2015-04-14 12:36:35"" tyro-reference=""905845"" merchant-reference=""071061048231306351219680""/>
         *      <transaction type=""purchase"" card-type=""eftpos"" amount=""650.00"" cash-out=""50.00"" transaction-local-date-time=""2015-04-14 12:40:30"" tyro-reference=""912556"" merchant-reference=""071061048231306351219681"" settlement-date=""2015-04-16""/>
         *      <transaction type=""purchase"" card-type=""eftpos"" amount=""450.00"" transaction-local-date-time=""2015-04-14 12:50:30"" tyro-reference=""920187"" merchant-reference=""071061048231306351219682"" settlement-date=""2015-04-16""/>
         *      <transaction type=""purchase"" card-type=""diners"" amount=""70.00"" transaction-local-date-time=""2015-04-14 13:30:30"" tyro-reference=""935587"" merchant-reference=""071061048231306351219683""/>
         *      <transaction type=""void"" card-type=""mastercard"" amount=""-80.00"" transaction-local-date-time=""2015-04-14 13:50:30"" tyro-reference=""946585"" merchant-reference=""071061048231306351219684"" settlement-date=""2015-04-16""/>
         *      <transaction type=""purchase"" card-type=""visa"" amount=""170.00"" transaction-local-date-time=""2015-04-14 14:23:25"" tyro-reference=""953594"" merchant-reference=""071061048231306351219685"" settlement-date=""2015-04-16""/>
         *      <transaction type=""refund"" card-type=""visa"" amount=""-70.00"" transaction-local-date-time=""2015-04-14 15:41:12"" tyro-reference=""962548"" merchant-reference=""071061048231306351219685"" settlement-date=""2015-04-16""/>
         *      </reconciliation-detail>";
         */

        StringBuilder debutOutput = new StringBuilder();

        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            reader.ReadToFollowing("reconciliation-detail");

            string mid = reader.GetAttribute("mid");
            string tid = reader.GetAttribute("tid");
            string terminal_business_day = reader.GetAttribute("terminal-business-day");
            string total = reader.GetAttribute("total");

            debutOutput.AppendLine("reconciliation-detail :  " +
                                   " mid:" + mid +
                                   " tid:" + tid +
                                   " terminal_business_day:" + terminal_business_day +
                                   " total:" + total);

            while (reader.ReadToFollowing("transaction"))
            {
                string type      = reader.GetAttribute("type");
                string card_type = reader.GetAttribute("card-type");
                string _amount   = reader.GetAttribute("amount");
                string cash_out  = reader.GetAttribute("cash-out");
                string tip       = reader.GetAttribute("tip");
                string transaction_local_date_time = reader.GetAttribute("transaction-local-date-time");
                string tyro_reference     = reader.GetAttribute("tyro-reference");
                string merchant_reference = reader.GetAttribute("merchant-reference");                 // transactionId that we sent in = tyro_payment_pending_id
                string settlement_date    = reader.GetAttribute("settlement-date");

                debutOutput.AppendLine("transaction :  " +
                                       " type:" + type +
                                       " card_type:" + card_type +
                                       " amount:" + _amount +
                                       " cash_out:" + cash_out +
                                       " tip:" + tip +
                                       " transaction_local_date_time:" + transaction_local_date_time +
                                       " tyro_reference:" + tyro_reference +
                                       " merchant_reference:" + merchant_reference +
                                       " settlement_date:" + settlement_date
                                       );


                /*
                 * select * from TyroPaymentPending
                 *
                 * update TyroPaymentPending
                 * set
                 *      tyro_transaction_id = '071061048231306351219677',
                 *      amount = 101.00,
                 *      out_date_processed = NULL,
                 *      out_result = '',
                 *      out_cardType = '',
                 *      out_transactionReference = '',
                 *      out_authorisationCode = '',
                 *      out_issuerActionCode = ''
                 * WHERE tyro_payment_pending_id = 1
                 */


                TyroPaymentPending tyroPaymentPending = TyroPaymentPendingDB.GetByByTyroTransactionID(DB, merchant_reference);

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

                int tyro_payment_type_id = -1;
                if (type == "purchase")
                {
                    tyro_payment_type_id = 1;
                }
                else if (type == "refund")
                {
                    tyro_payment_type_id = 2;
                }

                bool sucessfulTransaction = (tyro_payment_type_id == 1 || tyro_payment_type_id == 2);
                if (sucessfulTransaction)
                {
                    decimal amount;
                    if (!Decimal.TryParse(_amount, out amount))
                    {
                        Emailer.SimpleAlertEmail(
                            "Tyro invoice late payment added but amount is not decimal type (" + _amount + ")<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + tyroPaymentPending.InvoiceID + "<br />DB: " + DB + "<br /><br />" + xml.Replace("<", "&lt;").Replace(">", "&gt;").Replace(Environment.NewLine, "<br />"),
                            "Tyro Reconcilliation Amount Not Decimal Type. Invoice : " + tyroPaymentPending.InvoiceID,
                            true);
                        continue;
                    }

                    DateTime transactionDateTime;
                    if (!DateTime.TryParseExact(transaction_local_date_time, "yyyy-dd-MM hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out transactionDateTime))
                    {
                        Emailer.SimpleAlertEmail(
                            "Tyro invoice late payment added but transaction_local_date_time is not parsable (" + transaction_local_date_time + ")<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + tyroPaymentPending.InvoiceID + "<br />DB: " + DB + "<br /><br />" + xml.Replace("<", "&lt;").Replace(">", "&gt;").Replace(Environment.NewLine, "<br />"),
                            "Tyro Reconcilliation Amount Not Decimal Type. Invoice : " + tyroPaymentPending.InvoiceID,
                            true);
                        continue;
                    }

                    TyroPaymentPendingDB.UpdateByTyroTransactionID(DB, merchant_reference, "APPROVED", card_type, tyro_reference, "", "", transactionDateTime);

                    if (amount != tyroPaymentPending.Amount)
                    {
                        Emailer.SimpleAlertEmail(
                            "Tyro invoice late payment added but initial payment amount and reconcilliation ammount differ (" + tyroPaymentPending.Amount + ", " + amount + ")<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + tyroPaymentPending.InvoiceID + "<br />DB: " + DB,
                            "Tyro Reconcilliation Amounts Differ. Invoice : " + tyroPaymentPending.InvoiceID,
                            true);
                    }

                    if (tyroPaymentPending.TyroPaymentTypeID != tyro_payment_type_id)
                    {
                        Emailer.SimpleAlertEmail(
                            "Tyro invoice late payment added but payment types differ (" + tyroPaymentPending.TyroPaymentTypeID + ", " + tyro_payment_type_id + ")<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + tyroPaymentPending.InvoiceID + "<br />DB: " + DB,
                            "Tyro Reconcilliation Types Differ. Invoice : " + tyroPaymentPending.InvoiceID,
                            true);
                    }


                    Invoice invoice = InvoiceDB.GetByID(tyroPaymentPending.InvoiceID, DB);

                    if (tyroPaymentPending.TyroPaymentTypeID == 1) // payment
                    {
                        decimal totalOwed  = invoice.TotalDue - tyroPaymentPending.Amount;
                        bool    isOverPaid = totalOwed < 0;
                        bool    isPaid     = totalOwed <= 0;

                        ReceiptDB.Insert(DB, 364, tyroPaymentPending.InvoiceID, tyroPaymentPending.Amount, 0, false, isOverPaid, DateTime.MaxValue, -8);

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

                        if (isOverPaid)
                        {
                            // send email to someone .. to fix up the overpayment....
                            Emailer.SimpleAlertEmail(
                                "Tyro invoice late payment added and is overpaid.<br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + DB,
                                "Tyro Invoice OverPaid: " + invoice.InvoiceID,
                                true);
                        }
                    }
                    if (tyroPaymentPending.TyroPaymentTypeID == 2) // refund
                    {
                        amount = amount * -1;                      // reconcilliation report shows refund amount as negative amounts

                        decimal totalOwed = invoice.TotalDue + tyroPaymentPending.Amount;
                        bool    isPaid    = totalOwed <= 0;

                        RefundDB.Insert(tyroPaymentPending.InvoiceID, tyroPaymentPending.Amount, 308, "", -8, DB);

                        if (totalOwed > 0)
                        {
                            InvoiceDB.UpdateIsPaid(DB, tyroPaymentPending.InvoiceID, false);
                        }
                    }

                    Emailer.SimpleAlertEmail(
                        "Tyro Invoice Payment Updated Asynchonously (ie Late). <br />tyro_payment_pending_id: " + tyroPaymentPending.TyroPaymentPendingID + "<br />Invoice: " + invoice.InvoiceID + "<br />DB: " + DB,
                        "Tyro Invoice Payment Updated Asynchonously (ie Late). Invoice: " + invoice.InvoiceID,
                        true);
                }
            }
        }

        Logger.LogQuery(debutOutput.ToString());
    }
    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>");
        }
    }
예제 #12
0
    protected void GrdOrgInvoicesOutstanding_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Email")
        {
            int          organisationID = Convert.ToInt32(e.CommandArgument);
            Organisation org            = OrganisationDB.GetByID(organisationID);
            string[]     emails         = ContactDB.GetEmailsByEntityID(org.EntityID);

            if (emails.Length == 0)
            {
                SetErrorMessage("No email address set for '" + org.Name + "'. Please set one to email invoices to them.");
                return;
            }
            else
            {
                DataTable dt  = Session["orginvoicesoutstanding_data"] as DataTable;
                DataRow   row = dt.Select("organisation_id = " + organisationID)[0];

                string invoiceIDsCommaSep = (string)row["invoice_ids_comma_sep"];
                int[]  invoiceIDs         = Array.ConvertAll <string, int>(invoiceIDsCommaSep.Split(','), Convert.ToInt32);


                string tmpLettersDirectory = Letter.GetTempLettersDirectory();
                string originalFile        = Letter.GetLettersDirectory() + (!UserView.GetInstance().IsAgedCareView ? @"OverdueInvoiceTemplate.docx" : @"OverdueInvoiceTemplateAC.docx");
                string tmpDir = FileHelper.GetTempDirectoryName(tmpLettersDirectory);
                System.IO.Directory.CreateDirectory(tmpDir);
                string outputFile = tmpDir + "OverdueInvoices.pdf";


                try
                {
                    Letter.GenerateOutstandingInvoices(originalFile, outputFile, invoiceIDs, -1, organisationID);

                    EmailerNew.SimpleEmail(
                        ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value,
                        ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromName"].Value,
                        string.Join(",", emails),
                        "Overdue Invoices",
                        "Pease find your Invoices attached. <br/>Please call us if you do not agree with the Invoice amount stated.<br /><br />Thank you.",
                        true,
                        new string[] { outputFile },
                        false,
                        null
                        );

                    SetErrorMessage("Invoices Emailed to " + org.Name + " (" + string.Join(",", emails) + ")");
                }
                catch (CustomMessageException cmEx)
                {
                    SetErrorMessage(cmEx.Message);
                }
                catch (Exception ex)
                {
                    SetErrorMessage("", ex.ToString());
                }
                finally
                {
                    try { if (System.IO.File.Exists(outputFile))
                          {
                              System.IO.File.Delete(outputFile);
                          }
                    }
                    catch (Exception) { }

                    // delete temp dir
                    if (tmpDir != null)
                    {
                        try { System.IO.Directory.Delete(tmpDir, true); }
                        catch (Exception) { }
                    }
                }
            }
        }

        if (e.CommandName == "Print")
        {
            int organisationID = Convert.ToInt32(e.CommandArgument);

            DataTable dt  = Session["orginvoicesoutstanding_data"] as DataTable;
            DataRow   row = dt.Select("organisation_id = " + organisationID)[0];

            SetErrorMessage("Org ID: " + row["organisation_id"] + "<br />Invoices: " + row["invoice_ids_comma_sep"]);

            string invoiceIDsCommaSep = (string)row["invoice_ids_comma_sep"];
            int[]  invoiceIDs         = Array.ConvertAll <string, int>(invoiceIDsCommaSep.Split(','), Convert.ToInt32);

            Letter.GenerateOutstandingInvoicesToPrint(Response, invoiceIDs, -1, organisationID, !UserView.GetInstance().IsAgedCareView);
        }

        if (e.CommandName == "SetAllPaid" || e.CommandName == "SetAllWiped")
        {
            try
            {
                int organisationID = Convert.ToInt32(e.CommandArgument);

                DataTable dt  = Session["orginvoicesoutstanding_data"] as DataTable;
                DataRow   row = dt.Select("organisation_id = " + organisationID)[0];

                string invoiceIDsCommaSep = (string)row["invoice_ids_comma_sep"];
                int[]  invoiceIDs         = Array.ConvertAll <string, int>(invoiceIDsCommaSep.Split(','), Convert.ToInt32);


                foreach (int invoiceID in invoiceIDs)
                {
                    Invoice invoice = InvoiceDB.GetByID(invoiceID);
                    if (invoice == null || invoice.IsPaID)
                    {
                        continue;
                    }

                    if (e.CommandName.Equals("SetAllPaid"))
                    {
                        ReceiptDB.Insert(null, 362, invoice.InvoiceID, invoice.TotalDue, Convert.ToDecimal(0.00), false, false, DateTime.MinValue, Convert.ToInt32(Session["StaffID"]));
                        InvoiceDB.UpdateIsPaid(null, invoice.InvoiceID, true);
                    }
                    else if (e.CommandName.Equals("SetAllWiped"))
                    {
                        CreditNoteDB.Insert(invoice.InvoiceID, invoice.TotalDue, string.Empty, Convert.ToInt32(Session["StaffID"]));
                        InvoiceDB.UpdateIsPaid(null, invoice.InvoiceID, true);
                    }
                }

                SetErrorMessage("Invoices Set As " + (e.CommandName.Equals("SetAllPaid") ? "Paid" : "Wiped") + " : " + row["invoice_ids_comma_sep"]);

                GrdOrgInvoicesOutstanding_FillGrid();
            }
            catch (CustomMessageException cmEx)
            {
                SetErrorMessage(cmEx.Message);
            }
            catch (Exception ex)
            {
                SetErrorMessage("", ex.ToString());
            }
        }
    }
예제 #13
0
    protected void CheckReturnFromOnlinePayment()
    {
        string PT_PaymentReference  = Request.Form["PT_PaymentReference"] != null ? Request.Form["PT_PaymentReference"]  : Request.QueryString["PT_PaymentReference"];
        string PT_PaymentResult     = Request.Form["PT_PaymentResult"] != null ? Request.Form["PT_PaymentResult"]     : Request.QueryString["PT_PaymentResult"];
        string PT_PaymentResultCode = Request.Form["PT_PaymentResultCode"] != null ? Request.Form["PT_PaymentResultCode"] : Request.QueryString["PT_PaymentResultCode"];
        string PT_PaymentResultText = Request.Form["PT_PaymentResultText"] != null ? Request.Form["PT_PaymentResultText"] : Request.QueryString["PT_PaymentResultText"];
        string PT_BankReceiptID     = Request.Form["PT_BankReceiptID"] != null ? Request.Form["PT_BankReceiptID"]     : Request.QueryString["PT_BankReceiptID"];
        string PT_PayTechPaymentID  = Request.Form["PT_PayTechPaymentID"] != null ? Request.Form["PT_PayTechPaymentID"]  : Request.QueryString["PT_PayTechPaymentID"];


        if (PT_PaymentReference != null &&
            PT_PaymentResult != null &&
            PT_PaymentResultCode != null &&
            PT_PaymentResultText != null &&
            PT_BankReceiptID != null &&
            PT_PayTechPaymentID != null)
        {
            PaymentPending paymentPending = PaymentPendingDB.GetByID(null, Convert.ToInt32(Request.QueryString["PT_PaymentReference"]));
            Invoice        invoice        = InvoiceDB.GetByID(paymentPending.InvoiceID);

            PaymentPendingDB.Update(
                null,
                DateTime.Now,
                Convert.ToInt32(Request.QueryString["PT_PaymentReference"]),
                PT_PaymentResult,
                PT_PaymentResultCode,
                PT_PaymentResultText,
                PT_BankReceiptID,
                PT_PayTechPaymentID
                );

            if (PT_PaymentResult == "A" && !Convert.ToBoolean(ConfigurationManager.AppSettings["EziDebit_Debugging"]))
            {
                decimal totalOwed  = invoice.TotalDue - paymentPending.PaymentAmount;
                bool    isOverPaid = totalOwed < 0;
                bool    isPaid     = totalOwed <= 0;

                int receiptID = ReceiptDB.Insert(null, 363, paymentPending.InvoiceID, paymentPending.PaymentAmount, 0, false, isOverPaid, DateTime.MinValue, Convert.ToInt32(Session["StaffID"]));

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

                if (isPaid)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "close_form", @"<script language=javascript>self.close();</script>");
                }
            }


            string url = Request.RawUrl;
            //url = UrlParamModifier.Remove(url, "PT_PaymentReference");
            url = UrlParamModifier.Remove(url, "PT_PaymentResult");
            url = UrlParamModifier.Remove(url, "PT_PaymentResultCode");
            url = UrlParamModifier.Remove(url, "PT_PaymentResultText");
            url = UrlParamModifier.Remove(url, "PT_BankReceiptID");
            url = UrlParamModifier.Remove(url, "PT_PayTechPaymentID");
            Response.Redirect(url);
        }
        else if (PT_PaymentReference != null)
        {
            PaymentPending paymentPending = PaymentPendingDB.GetByID(null, Convert.ToInt32(Request.QueryString["PT_PaymentReference"]));
            if (paymentPending.OutPaymentResult == "A")
            {
                SetErrorMessage("Online Payment Approved: $" + paymentPending.PaymentAmount + ".<br />Adjusted Amount Owed Remaining Showing Above.");
            }
            if (paymentPending.OutPaymentResult == "U")
            {
                SetErrorMessage("Online Payment was not able to be processed at this time");
            }
            if (paymentPending.OutPaymentResult == "F")
            {
                SetErrorMessage("<div style=\"height:15px;\"></div><span style=\"font-size: 150%;\">Online Payment Failed: <b>" + paymentPending.OutPaymentResultText + "</b></span><div style=\"height:2px;\"></div>");
            }
        }
    }
예제 #14
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage();
            return;
        }
        Invoice invoice = InvoiceDB.GetByID(GetFormID());

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


        decimal total = 0;


        ArrayList receipts = new ArrayList();

        for (int i = 0; i < lstPayments.Items.Count; i++)
        {
            Label   lblTypeID = (Label)lstPayments.Items[i].FindControl("lblTypeID");
            TextBox txtAmount = (TextBox)lstPayments.Items[i].FindControl("txtAmount");

            txtAmount.Text = txtAmount.Text.Trim();
            if (txtAmount.Text.Length > 0 && lblTypeID != null)
            {
                receipts.Add(new Tuple <int, decimal>(Convert.ToInt32(lblTypeID.Text), Convert.ToDecimal(txtAmount.Text)));
                total += Convert.ToDecimal(txtAmount.Text);
            }
        }


        ArrayList vouchers = new ArrayList();

        for (int i = 0; i < lstVouchers.Items.Count; i++)
        {
            HiddenField hiddenCreditID = (HiddenField)lstVouchers.Items[i].FindControl("hiddenCreditID");
            HiddenField hiddenEntityID = (HiddenField)lstVouchers.Items[i].FindControl("hiddenEntityID");
            TextBox     txtAmount      = (TextBox)lstVouchers.Items[i].FindControl("txtAmount");

            txtAmount.Text = txtAmount.Text.Trim();
            if (txtAmount.Text.Length > 0)
            {
                vouchers.Add(new Tuple <int, int, decimal>(Convert.ToInt32(hiddenCreditID.Value), Convert.ToInt32(hiddenEntityID.Value), Convert.ToDecimal(txtAmount.Text)));
                total += Convert.ToDecimal(txtAmount.Text);
            }
        }


        if (txtCreditNoteTotal.Text == string.Empty)
        {
            txtCreditNoteTotal.Text = "0";
        }
        total += Convert.ToDecimal(txtCreditNoteTotal.Text);

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

        if (isOverPaid)
        {
            SetErrorMessage("Total can not be more than the amount owing.");
            return;
        }


        // put in try/catch block in case someone just used the vouchers and there is more being used than is remaining in the voucher
        ArrayList creditIDsAdded = new ArrayList();

        try
        {
            foreach (Tuple <int, int, decimal> item in vouchers)
            {
                int creditID = CreditDB.Insert_UseVoucher(item.Item2, item.Item3, item.Item1, invoice.InvoiceID, Convert.ToInt32(Session["StaffID"]));
                creditIDsAdded.Add(creditID);
            }
        }
        catch (Exception ex)
        {
            // roll back
            foreach (int creditID in creditIDsAdded)
            {
                CreditDB.Delete(creditID);
            }

            SetErrorMessage(ex.Message);
            return;
        }

        foreach (Tuple <int, decimal> item in receipts)
        {
            ReceiptDB.Insert(null, item.Item1, invoice.InvoiceID, item.Item2, Convert.ToDecimal(0.00), false, isOverPaid, DateTime.MinValue, Convert.ToInt32(Session["StaffID"]));
        }

        if (Convert.ToDecimal(txtCreditNoteTotal.Text) > 0)
        {
            CreditNoteDB.Insert(invoice.InvoiceID, Convert.ToDecimal(txtCreditNoteTotal.Text), txtCreditCardReason.Text, Convert.ToInt32(Session["StaffID"]));
        }

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

        FillEmptyAddForm();

        // close this window
        string returnValue = Request.QueryString["returnValue"] != null ? Request.QueryString["returnValue"] : "false";

        Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=" + returnValue + ";window.opener.location.href = window.opener.location.href;self.close();</script>");
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (GetUrlParamType() == UrlParamType.View)
        {
            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "edit"));
        }
        //else if (GetUrlParamType() == UrlParamType.Edit)
        //{
        //    if (!IsValidFormID())
        //    {
        //        HideTableAndSetErrorMessage();
        //        return;
        //    }
        //    Receipt receipt = ReceiptDB.GetByID(GetFormID());
        //    if (receipt == null)
        //    {
        //        HideTableAndSetErrorMessage("Invalid receipt ID");
        //        return;
        //    }

        //    ReceiptDB.Update(receipt.ReceiptID, Convert.ToInt32(ddlPaymentType.SelectedValue), Convert.ToDecimal(txtTotal.Text), Convert.ToDecimal(txtAmountReconciled.Text), chkFailedToClear.Checked, receipt.IsOverpaid, GetBankProcessedDateFromForm());

        //    Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view_only"));


        //    // close this window
        //    //Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=false;self.close();</script>");
        //}

        else if (GetUrlParamType() == UrlParamType.Reconcile)
        {
            if (!IsValidFormID())
            {
                HideTableAndSetErrorMessage();
                return;
            }
            Receipt receipt = ReceiptDB.GetByID(GetFormID());
            if (receipt == null)
            {
                HideTableAndSetErrorMessage("Invalid receipt ID");
                return;
            }


            ReceiptDB.Update(receipt.ReceiptID, receipt.ReceiptPaymentType.ID, receipt.Total, Convert.ToDecimal(txtAmountReconciled.Text), chkFailedToClear.Checked, receipt.IsOverpaid, DateTime.Now, receipt.ReversedBy == null ? -1 : receipt.ReversedBy.StaffID, receipt.ReversedDate, receipt.PreReversedAmount);

            // close this window
            Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=false;self.close();</script>");
        }

        else if (GetUrlParamType() == UrlParamType.Add)
        {
            if (!IsValidFormID())
            {
                HideTableAndSetErrorMessage();
                return;
            }
            Invoice invoice = InvoiceDB.GetByID(GetFormID());
            if (invoice == null)
            {
                HideTableAndSetErrorMessage("Invalid invoice ID");
                return;
            }

            decimal thisReceitptAmount = Convert.ToDecimal(txtTotal.Text);
            decimal totalOwed          = invoice.TotalDue - thisReceitptAmount;
            bool    isOverPaid         = totalOwed < 0;
            bool    isPaid             = totalOwed <= 0;
            int     receipt_id         = ReceiptDB.Insert(null, Convert.ToInt32(ddlPaymentType.SelectedValue), invoice.InvoiceID, thisReceitptAmount, Convert.ToDecimal(0.00), false, isOverPaid, DateTime.MinValue, Convert.ToInt32(Session["StaffID"]));

            if (isPaid)
            {
                InvoiceDB.UpdateIsPaid(null, invoice.InvoiceID, true);
            }
            if (isOverPaid)
            {
                OverpaymentDB.Insert(receipt_id, -1 * totalOwed, Convert.ToInt32(Session["StaffID"]));
            }


            //string url = Request.RawUrl;
            //url = UrlParamModifier.AddEdit(url, "type", "view_only");
            //url = UrlParamModifier.AddEdit(url, "id", receipt_id.ToString());
            //Response.Redirect(url);
            //return;

            // close this window
            Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.returnValue=false;self.close();</script>");
        }
        else
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
        }
    }
    private void FillEditViewForm(bool isEditMode, bool isReconcileMode)
    {
        if (isEditMode)
        {
            lblHeading.Text = "Edit Receipt";
            Page.Title      = "Edit Receipt";
        }
        else if (isReconcileMode)
        {
            lblHeading.Text = "Reconcile Receipt";
            Page.Title      = "Reconcile Receipt";
        }
        else
        {
            lblHeading.Text = "View Receipt";
            Page.Title      = "View Receipt";
        }

        Receipt receipt = ReceiptDB.GetByID(GetFormID());

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


        lblId.Text          = receipt.ReceiptID.ToString();
        lblInvoiceId.Text   = receipt.Invoice.InvoiceID.ToString();
        lblReceiptDate.Text = receipt.ReceiptDateAdded.ToString("d MMM, yyyy");
        lblIsOverpaid.Text  = receipt.IsOverpaid ? "Yes" : "No";
        lblAddedBy.Text     = receipt.Staff.Person.FullnameWithoutMiddlename;

        lblReceiptDate.Font.Bold = !isEditMode && !isReconcileMode;
        lblPaymentType.Font.Bold = !isEditMode && !isReconcileMode;
        lblTotal.Font.Bold       = !isEditMode && !isReconcileMode;
        lblIsOverpaid.Font.Bold  = !isEditMode && !isReconcileMode;


        if (isEditMode)
        {
            ddlPaymentType.SelectedValue = receipt.ReceiptPaymentType.ID.ToString();

            txtTotal.Text              = receipt.Total.ToString();
            txtAmountReconciled.Text   = receipt.AmountReconciled.ToString();
            chkFailedToClear.Checked   = receipt.IsFailedToClear;
            isReconciledRow.Visible    = false;
            lblReconciliationDate.Text = receipt.ReconciliationDate == DateTime.MinValue ? "--" : receipt.ReconciliationDate.ToString("d MMM, yyyy");

            lblPaymentType.Visible      = false;
            lblTotal.Visible            = false;
            lblAmountReconciled.Visible = false;
            lblFailedToClear.Visible    = false;
        }
        else if (isReconcileMode)
        {
            if (receipt.IsReconciled)
            {
                HideTableAndSetErrorMessage("This receipt has already been reconciled.");
                return;
            }

            lblPaymentType.Text = receipt.ReceiptPaymentType.Descr;

            lblTotal.Text                 = receipt.Total.ToString();
            txtAmountReconciled.Text      = receipt.AmountReconciled == 0 ? receipt.Total.ToString() : receipt.AmountReconciled.ToString();
            chkFailedToClear.Checked      = receipt.IsFailedToClear;
            isReconciledRow.Visible       = false;
            reconciliationDateRow.Visible = false;

            ddlPaymentType.Visible      = false;
            txtTotal.Visible            = false;
            lblAmountReconciled.Visible = false;
            lblFailedToClear.Visible    = false;
        }
        else
        {
            lblPaymentType.Text = receipt.ReceiptPaymentType.Descr;

            lblTotal.Text              = receipt.Total.ToString();
            lblAmountReconciled.Text   = receipt.AmountReconciled.ToString();
            lblFailedToClear.Text      = receipt.IsFailedToClear ? "Yes" : "No";
            lblReconciliationDate.Text = receipt.ReconciliationDate == DateTime.MinValue ? "--" : receipt.ReconciliationDate.ToString("d MMM, yyyy");
            lblIsReconciled.Text       = receipt.IsReconciled    ? "Yes" : "No";

            ddlPaymentType.Visible      = false;
            txtTotal.Visible            = false;
            txtAmountReconciled.Visible = false;
            chkFailedToClear.Visible    = false;

            if (receipt.IsReconciled)
            {
                isReconciledRow.Visible = false;
            }
            else
            {
                reconciliationDateRow.Visible = false;
                amountReconciledRow.Visible   = false;
                failedToClearRow.Visible      = false;
            }
        }



        if (isEditMode)
        {
            btnSubmit.Text = "Update Details";
        }
        else if (isReconcileMode)
        {
            btnSubmit.Text = "Reconcile";
        }
        else // is view mode
        {
            if (GetUrlParamType() == UrlParamType.ViewOnly)
            {
                btnSubmit.Visible = false;
            }
            else
            {
                btnSubmit.Text = "Edit";
            }

            btnCancel.Text = "Close";
        }
    }