示例#1
0
		//REMOVED BY DAVEB 10/01
		//private static void RefundTicket(Usr actionUsr, Ticket ticket)
		//{
		//    RefundTicket(actionUsr, ticket, false);
		//}

		private static void RefundTicket(Usr actionUsr, Ticket ticket, bool refundIncludeBookingFee, bool areFundsAlreadyReleased)
        {
            try
            {
                if (ticket.IsAllowedToRefund(actionUsr, Math.Round(ticket.Price + (refundIncludeBookingFee ? ticket.BookingFee : 0), 2)))
                {
                    InvoiceDataHolder creditDH = ticket.Invoice.CreateCredit();
                    creditDH.ActionUsrK = actionUsr.K;
                    // Remove all invoice items, except that of tickets
                    for (int i = creditDH.InvoiceItemDataHolderList.Count - 1; i >= 0; i--)
                    {
                        // Remove only the ticket invoice item (and booking fee if refundIncludeBookingFee)
                        if (creditDH.InvoiceItemDataHolderList[i].BuyableObjectK != ticket.K || creditDH.InvoiceItemDataHolderList[i].BuyableObjectType != Model.Entities.ObjectType.Ticket
                            || (creditDH.InvoiceItemDataHolderList[i].Type != InvoiceItem.Types.EventTickets
                                && (creditDH.InvoiceItemDataHolderList[i].Type != InvoiceItem.Types.EventTicketsBookingFee || !refundIncludeBookingFee)))
                        {
                            creditDH.InvoiceItemDataHolderList.RemoveAt(i);
                        }
                    }

                    if (ticket.Invoice.AmountAllowedToCredit < Math.Abs(creditDH.Total))
                        throw new Exception("Cannot credit more than " + ticket.Invoice.AmountAllowedToCredit.ToString("c") + " for Invoice #" + ticket.Invoice.K.ToString());

					decimal refundAmountRemaining = Math.Abs(creditDH.Total);
                    SecPay secPay = new SecPay();

                    // Refund that amount from transfers
                    foreach (InvoiceTransfer invoiceTransfer in ticket.Invoice.SuccessfulInvoiceTransfers)
                    {
                        try
                        {
                            if (refundAmountRemaining <= 0)
                                break;

							decimal refundAmount = Math.Round(invoiceTransfer.Amount, 2) < Math.Round(refundAmountRemaining, 2) ? Math.Round(invoiceTransfer.Amount, 2) : Math.Round(refundAmountRemaining, 2);

                            // refund refundAmount from that transfer, the subtract that from refundAmountRemaining
                            Transfer transferToRefund = new Transfer(invoiceTransfer.TransferK);

                            secPay.MakeRefund(transferToRefund, Guid.NewGuid(), Usr.Current.K, refundAmount);
                            if (secPay.Transfer.Status == Transfer.StatusEnum.Success)
                            {
                                refundAmountRemaining = Math.Round(refundAmountRemaining - refundAmount, 2);
                                transferToRefund.UpdateAndResolveOverapplied();
                                Utilities.EmailTransfer(secPay.Transfer, true, false);
                            }
                            else
                                throw new Exception("SecPay refund #");// + secPay.Transfer.K.ToString() + " failed, by user: "******", for ticket #" + ticket.K.ToString());
                        }
                        catch (Exception ex)
                        {
                            Utilities.AdminEmailAlert("Exception in Ticket.RefundTicket(Ticket ticket)", "Exception in Ticket.RefundTicket(Ticket ticket)", ex, ticket);
                        }
                    }

                    if (Math.Round(refundAmountRemaining, 2) <= 0)
                    {
                        creditDH.DueDateTime = Time.Now;
                        Invoice credit = creditDH.UpdateInsertDelete();
                        // Get latest invoice from DB
                        ticket.Invoice = null;
                        ticket.Invoice.ApplyCreditToThisInvoice(credit);

                        if (!ticket.Invoice.Paid)
                            throw new Exception("Invoice #" + ticket.Invoice.K.ToString() + " was not refunded completely, please verify manually.");

                        ticket.Cancelled = true;
						ticket.CancelledBeforeFundsRelease = !areFundsAlreadyReleased;
						ticket.CancelledDateTime = Time.Now;
                        ticket.Update();
						if (ticket.BuyerUsr != null)
						{
							ticket.BuyerUsr.SetPrefsNextTicketFeedbackDate();
						}
                        Utilities.EmailTicket(ticket);
                    }
                }
            }
            catch (Exception ex)
            {
                Utilities.AdminEmailAlert("Exception in Ticket.RefundTicket(Ticket ticket)", "Exception in Ticket.RefundTicket(Ticket ticket)", ex, ticket);
                throw ex;
            }
        }
		protected void SaveButton_Click(object sender, EventArgs e)
		{
			Page.Validate("");
			if (Page.IsValid)
			{
				bool succeeded = false;
				Transfer.StatusEnum previousStatus = currentTransfer.Status;

				SecPay secPay = new SecPay();
				try
				{
					LoadTransferFromScreen();

                    //if (CurrentTransfer.K == 0)
                    //{
                    //    CurrentTransfer.SetDSIBankAccount();
                    //}

					if (currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) || currentTransfer.Amount < 0)
					{
						// Verify its Dave, Tim, Gee, Neil, or John
						if (!Usr.Current.IsSuperAdmin)
							throw new Exception("You do not have permission to refund. Please ask a super admin for assistance.");

                        if (currentTransfer.TransferRefundedK > 0 && currentTransfer.K == 0)
                        {
                            Transfer transferToRefund = new Transfer(currentTransfer.TransferRefundedK);
                            var transferToRefundAmountRemaining = TransferToRefund.AmountRemaining();
                            if (transferToRefundAmountRemaining < Math.Abs(currentTransfer.Amount))
                                throw new Exception("Cannot refund " + currentTransfer.Amount.ToString("c") + " because transfer to refund only has " + transferToRefundAmountRemaining.ToString("c") + " remaining.");
                        }
					}

					if (!Transfer.DoesDuplicateGuidExistInDb((Guid)this.ViewState["DuplicateGuid"]) || currentTransfer.K > 0)
					{
						if (currentTransfer.Type.Equals(Transfer.TransferTypes.Payment) && currentTransfer.Amount <= 0)
							throw new Exception("Payment must have positive amount > 0");

						if (currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.Amount >= 0)
							throw new Exception("Refund must have negative amount < 0");

						if (currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.Method.Equals(Transfer.Methods.Card) && currentTransfer.TransferRefundedK == 0)
							throw new Exception("Cannot process card refund without an original succesful card transfer.");

						// Set DateTimeCreated for new Transfers
						if (currentTransfer.K == 0 || currentTransfer.DateTimeCreated.Equals(DateTime.MinValue))
						{
							currentTransfer.DateTimeCreated = DateTime.Now;
						}

						// If Transfer is now set to completed and DateTimeComplete is not set, then set it to NOW
						if (!currentTransfer.Status.Equals(Transfer.StatusEnum.Pending) && currentTransfer.DateTimeComplete.Equals(DateTime.MinValue))
						{
							currentTransfer.DateTimeComplete = DateTime.Now;
						}
						// If saving new refund, first verify that original transfer amount >= new refund + original transfer amount refunded already
                        if (currentTransfer.K == 0 && currentTransfer.Status.Equals(Transfer.StatusEnum.Pending) && currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.TransferRefundedK > 0)
						{
							var amountRefunded = TransferToRefund.AmountRefunded();
							if (Math.Round(amountRefunded + Math.Abs(currentTransfer.Amount),2) > Math.Round(TransferToRefund.Amount,2))
							{
								throw new Exception("Refund cannot exceed original transfer amount. " + amountRefunded.ToString("c") + " already refunded "
													+ currentTransfer.Amount.ToString("c") + " is greater than the original transfer amount " + transferToRefund.Amount.ToString("c"));
							}
							if (Math.Round(Math.Abs(currentTransfer.Amount), 2) == Math.Round(transferToRefund.Amount, 2))
								currentTransfer.RefundStatus = Transfer.RefundStatuses.FullRefund;
							else
								currentTransfer.RefundStatus = Transfer.RefundStatuses.PartialRefund;
						}
						// for new card transactions that are marked as Pending, then process via SecPay
						if (currentTransfer.K == 0 && currentTransfer.Method.Equals(Transfer.Methods.Card) && currentTransfer.Status.Equals(Transfer.StatusEnum.Pending))
						{

							if (currentTransfer.Type.Equals(Transfer.TransferTypes.Payment))
							{
								// Process card via SecPay
								secPay.MakePayment(new List<InvoiceDataHolder>(), currentTransfer.Amount, new Usr(currentTransfer.UsrK), currentTransfer.PromoterK, Usr.Current.K, currentTransfer.CardName,
													currentTransfer.CardAddress1, currentTransfer.CardAddressArea, currentTransfer.CardAddressTown, currentTransfer.CardAddressCounty, currentTransfer.CardAddressCountryK, currentTransfer.CardPostcode, "UK", this.CardNumberTextBox.Text.Trim().Replace(" ", ""),
													currentTransfer.CardExpires, currentTransfer.CardCV2, Transfer.FraudCheckEnum.Relaxed, false, currentTransfer.DuplicateGuid, currentTransfer.CardStart, 
													currentTransfer.CardIssue > 0 ? currentTransfer.CardIssue.ToString() : "");
								
								// Since SecPay doesnt store CardAddress2, we need to save it here.

								secPay.Transfer.CardAddressArea = currentTransfer.CardAddressArea;
								secPay.Transfer.CardAddressTown = currentTransfer.CardAddressTown;
								secPay.Transfer.CardAddressCounty = currentTransfer.CardAddressCounty;
								secPay.Transfer.CardAddressCountryK = currentTransfer.CardAddressCountryK;

									secPay.Transfer.Update();

								currentTransfer = secPay.Transfer;
							}
							else if (currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.TransferRefundedK > 0)
							{
								secPay.MakeRefund(TransferToRefund, (Guid)ViewState["DuplicateGuid"], Usr.Current.K, currentTransfer.Amount);
								currentTransfer = secPay.Transfer;

								if (this.NotesAddOnlyTextBox.ReadOnlyTextBox.Text.Length > 0)
								{
									// Clear old notes, as they will be in the Notes textbox
									if (TransferToRefund.Notes.Length > 0)
										currentTransfer.Notes = currentTransfer.Notes.Replace(TransferToRefund.Notes, "") + "\n";
									else
										currentTransfer.Notes = "";

									currentTransfer.Notes += this.NotesAddOnlyTextBox.ReadOnlyTextBox.Text;
								}
								TransferToRefund.AddNote("This transfer has been refunded " + currentTransfer.Amount.ToString("c") + " on refund transfer #" + currentTransfer.K.ToString(), "System");
								TransferToRefund.UpdateAndResolveOverapplied();
								Utilities.EmailTransfer(TransferToRefund, false, false);
							}
							if (!currentTransfer.Status.Equals(Transfer.StatusEnum.Success))
							{
								throw new Exception("SecPay transaction was not successful.");
								//TransferK = CurrentTransfer.K;
								//LoadScreenFromTransfer();

								//this.ProcessingCustomValidator.IsValid = false;

								//this.ProcessingCustomValidator.ErrorMessage = "Transfer #" + secPay.SecPayTransfer.K.ToString() + " failed. Please contact administrator for further details";
								//return;
							}
						}
						else
						{
                            if (currentTransfer.K == 0 && currentTransfer.Method == Transfer.Methods.BankTransfer && currentTransfer.Type == Transfer.TransferTypes.Refund)
                                currentTransfer = Transfer.RefundViaBACS(currentTransfer);
                            else
    							currentTransfer.Update();
							if ((currentTransfer.Status.Equals(Transfer.StatusEnum.Pending) || currentTransfer.Status.Equals(Transfer.StatusEnum.Success)) && currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.TransferRefundedK > 0)
							{
								TransferToRefund.AddNote("This transfer has been refunded " + currentTransfer.Amount.ToString("c") + " on refund transfer #" + currentTransfer.K.ToString(), "System");
								TransferToRefund.UpdateAndResolveOverapplied();
								Utilities.EmailTransfer(TransferToRefund, false, false);
							}
                            else if (currentTransfer.Status.Equals(Transfer.StatusEnum.Cancelled) && currentTransfer.Type.Equals(Transfer.TransferTypes.Refund) && currentTransfer.TransferRefundedK > 0)
                            {
                                // This scenario only occurs in very rare situations and handled only by SuperAdmins.
                                TransferToRefund.UpdateAndResolveOverapplied();
                            }
						}
						if (this.InvoiceK > 0 && currentTransfer.K > 0)
						{
							InvoiceTransfer invoiceTransfer;
							try
							{
								invoiceTransfer = new InvoiceTransfer(this.InvoiceK, currentTransfer.K);
							}
							catch (Exception)
							{
								invoiceTransfer = new InvoiceTransfer();
								invoiceTransfer.InvoiceK = this.InvoiceK;
								invoiceTransfer.TransferK = currentTransfer.K;
							}
							invoiceTransfer.Amount = new Invoice(this.InvoiceK).Total;

							if (invoiceTransfer.Amount > currentTransfer.Amount)
								invoiceTransfer.Amount = currentTransfer.Amount;

							invoiceTransfer.Update();
						}
						// Update Invoices that are affected by this transfer
						currentTransfer.UpdateAffectedInvoices();

						succeeded = true;
					}
					// Do not process if duplicate exists. User probably tried refreshing the page.
					else
					{
						throw new Exception("Duplicate transfer already exists in the database.");
					}
				}

				catch (Exception ex)
				{
					// If processing SecPay card transfer and error occurred, but transfer saved
					if (secPay.Transfer != null && secPay.Transfer.K > 0 && this.TransferK == 0)
					{
						Mailer sm = new Mailer();
						if (Vars.DevEnv)
						{
							sm.Subject = "Test - ";
							sm.To = "*****@*****.**";
						}
						else
							sm.To = "[email protected], [email protected], [email protected]";

						sm.Body = "<p>Exception occurred using SecPay! - Usr = "******" (" + Usr.Current.K + "), PromoterK=" + secPay.Transfer.PromoterK.ToString() + "</p>";
						sm.Body += "<p>Message: " + ex.Message + "</p>";
						sm.Body += "<p>Transfer K: " + secPay.Transfer.K.ToString() + "</p>";
						sm.Body += secPay.Transfer.AsHTML();
						sm.TemplateType = Mailer.TemplateTypes.AdminNote;
						sm.Subject = "Exception occurred using SecPay! Transfer K:" + secPay.Transfer.K.ToString();

						sm.Send();

						string redirectUrl = "";
						if (this.InvoiceK > 0)
							redirectUrl = secPay.Transfer.UrlAdminRetryFailedTransfer(this.InvoiceK);
						else
							redirectUrl = secPay.Transfer.UrlAdminRetryFailedTransfer();

						string response = "<script type=\"text/javascript\">alert('Transfer #" + secPay.Transfer.K.ToString() + " " + secPay.Transfer.Status.ToString();

						if (secPay.Transfer.Status.Equals(Transfer.StatusEnum.Success))
						{
							try
							{
								secPay.Transfer.UpdateAndResolveOverapplied();
							}
							catch (Exception)
							{ }
							response += ". There was an exception during saving: " + ex.Message + "'); open('" + secPay.Transfer.UrlAdmin() + "?" + Cambro.Misc.Utility.GenRandomText(5) + "', '_self');</script>";
						}
						else
							response += ". Please try again.'); open('" + redirectUrl + "', '_self');history.go(1);</script>";
						ViewState["DuplicateGuid"] = Guid.NewGuid();
						Response.Write(response);

						//Response.End();
					}
					else
					{
						// Display error message
						this.ProcessingVal.ErrorMessage = ex.Message;
						this.ProcessingVal.IsValid = false;
					}
				}

				// Having Server.Transfer or Response.Redirect in Try{} caused an error during debugging.
				if (succeeded == true)
				{
					// Send email to promoter and to DSI accounts
					bool madeSuccessful = false;
					if (!previousStatus.Equals(Transfer.StatusEnum.Success) && currentTransfer.Status.Equals(Transfer.StatusEnum.Success))
						madeSuccessful = true;

					// New successful transfers via SecPay will be auto emailed.
					// Only new non-SecPay transfers or non-SecPay transfers made successful shall be emailed.
					if (secPay.Transfer.K == 0 && (TransferK == 0 || madeSuccessful))
						Utilities.EmailTransfer(currentTransfer, TransferK == 0, madeSuccessful);

					string response = "<script type=\"text/javascript\">alert('Transfer #" + currentTransfer.K.ToString() + " saved successfully'); open('" + currentTransfer.UrlAdmin() + "?" + Cambro.Misc.Utility.GenRandomText(5) + "', '_self');</script>";
					Response.Write(response);
					Response.End();
				}
			}
		}