Ejemplo n.º 1
0
		private void ProcessException(Exception ex, SecPay secPay, string cardNumber, bool unlockInvoiceItems)
		{
			//if (!(ex is System.Threading.ThreadAbortException))
			//{
				ViewState["DuplicateGuidTransfer"] = Guid.NewGuid();

				ProcessingVal.IsValid = false;

				if (ContainerPage != null && !HideValidationSummary)
					ContainerPage.AnchorSkip(this.ClientID + "_PaymentAnchor");

				Mailer sm = new Mailer();
				sm.TemplateType = Mailer.TemplateTypes.AdminNote;
				sm.Subject = "Exception while sending payment!";
				sm.To = "[email protected], [email protected], [email protected]";

				if (CurrentPromoter != null)
					sm.Body = "<p>Exception while sending payment! - Usr = "******" (" + CurrentUsr.K + "), Promoter = " + CurrentPromoter.Name + " (" + CurrentPromoter.K.ToString() + "), ActionUsr = "******" (" + CurrentUsr.K + ")</p>";
				else
					sm.Body = "<p>Exception while sending payment! - Usr = "******" (" + CurrentUsr.K + "), PromoterK = 0, ActionUsr = "******" (" + CurrentUsr.K + ")</p>";
				sm.Body += "<p>Exception details: " + ex.Message + "</p>";
				sm.Body += "<p>Exception stack trace: " + ex.StackTrace + "</p>";

				sm.Body += "<p>Invoice(s):<br>" + InvoicesToHTML() + "</p>";

				if (this.CampaignCredits.Count > 0)
				{
					sm.Body += "<p>Campaign credit(s):<br>" + CampaignCreditsToHTML() + "</p>";
				}

				if (secPay != null && secPay.Transfer != null)
				{
					sm.Body += "<p>Card number: " + secPay.Transfer.CardNumber + "</p>";
					if (secPay.Transfer.CardResponseMessage.Length > 0)
						sm.Body += "<p>SecPay response message: " + secPay.Transfer.CardResponseMessage + "</p>";
					if (secPay.Transfer.CardResponseAuthCode.Length > 0)
						sm.Body += "<p>SecPay response auth code: " + secPay.Transfer.CardResponseAuthCode + "</p>";
					if (secPay.Transfer.CardResponseCode.Length > 0)
						sm.Body += "<p>SecPay response code: " + secPay.Transfer.CardResponseCode + "</p>";
					if (secPay.Transfer.CardResponseCv2Avs.Length > 0)
						sm.Body += "<p>SecPay response CV2 AVS: " + secPay.Transfer.CardResponseCv2Avs + "</p>";
					if (secPay.Transfer.CardResponseRespCode.Length > 0)
						sm.Body += "<p>SecPay response resp code: " + secPay.Transfer.CardResponseRespCode + "</p>";
				}
				else if (cardNumber.Length > 0)
				{
					sm.Body += "<p>Card number: " + (cardNumber.Length > Utilities.DISPLAY_CARD_LAST_NUMBER_OF_DIGITS ? cardNumber.Substring(cardNumber.Length - Utilities.DISPLAY_CARD_LAST_NUMBER_OF_DIGITS) : cardNumber) + "</p>";
				}
				sm.Body += CurrentBuyer.AsHTML();
				sm.Send();
			//}

            // Unlock items so users may attempt to process again
            try
            {
                if(unlockInvoiceItems)
                    this.UnlockInvoiceItems();
            }
            catch (Exception)
            { }
			return;
		}
Ejemplo n.º 2
0
		private bool ProcessSuccessfulSecPayTransfer(SecPay secPay)
		{
			bool result = true;
            
			if (this.Invoices.Count != secPay.Invoices.Count)
			{
				if (secPay.Invoices.Count == 0)
				{
					result = false;
					ProcessingVal.ErrorMessage = RETRY_INVOICE_ERROR_MSG;
				}
				else
					ProcessingVal.ErrorMessage = CALL_ADMIN_INVOICE_ERROR_MSG;

				string exceptionMessage = "Payment control invoices = " + this.Invoices.Count.ToString() + ". SecPay Invoices = " + secPay.Invoices.Count.ToString() + ". Invoices attempting process:<br>";

				ProcessException(new Exception(exceptionMessage));
			}
			else
				HandleAndVerifyInvoicesProcessed(secPay.Invoices);

			if (secPay.Transfer.IsFullyApplied == false)
			{
				Transfer secPayTransfer = new Transfer(secPay.Transfer.K);
				if (secPay.Transfer.IsFullyApplied == false)
				{
					string msg = "SecPay Transfer (K=" + secPayTransfer.K.ToString() + ") was not fully applied.";
					Utilities.AdminEmailAlert(msg , msg, new DsiUserFriendlyException(msg), secPayTransfer);
				}
			}
			if (result)
			{
				if (PaymentDone != null)
					PaymentDone(this, new PaymentDoneEventArgs(secPay.Invoices, this.CampaignCredits, false, ""));
			}
			if (GetFullAddress)
			{
				Usr usr = Usr.Current;

			}
			return result;
		}
Ejemplo n.º 3
0
		private void ProcessException(Exception ex, SecPay secPay)
		{
			ProcessException(ex, secPay, "", true);
		}
Ejemplo n.º 4
0
        private void HandleFailedSecPayTransfer(SecPay secPay)
		{
			try
			{
				this.UnlockInvoiceItems();

				ProcessingVal.IsValid = false;
				ViewState["DuplicateGuidTransfer"] = Guid.NewGuid();
				if (FraudCheck.Equals(Transfer.FraudCheckEnum.Strict) && secPay.Transfer.CardResponseIsAddressMatch == false)
					ProcessingVal.ErrorMessage = "Please check your address and postcode. Make sure your address and postcode matches the address on your card statement.";
				else if (FraudCheck.Equals(Transfer.FraudCheckEnum.Strict) && secPay.Transfer.CardResponseIsPostCodeMatch == false)
					ProcessingVal.ErrorMessage = "Please check your address and postcode. Make sure your address and postcode matches the postcode on your card statement.";
				else if (FraudCheck.Equals(Transfer.FraudCheckEnum.Strict) && secPay.Transfer.CardResponseIsCv2Match == false)
					ProcessingVal.ErrorMessage = "Please check your CV2 code. The CV2 code is the last three digits on the signature strip on the reverse of your card.";
				else if (secPay.Transfer.CardResponseMessage.Contains("Luhn Check Failed"))
					ProcessingVal.ErrorMessage = "Please check your card number. Contact an administrator if this problem continues.";
				else if (secPay.Transfer.CardResponseMessage.Contains("DECLINED"))
					ProcessingVal.ErrorMessage = "Your card was declined. Please try another card. Contact your bank for card declined details.";
				else if (secPay.Transfer.CardResponseMessage.Contains("REFERRAL"))
				{
					ProcessingVal.ErrorMessage = "Your bank requires voice referral. Please try another card or contact your bank for card referral verification.";
					throw new DsiUserFriendlyException("SecPay payment failed. Card's bank requires voice referral.");
				}
				else
				{
					ProcessingVal.ErrorMessage = "Payment #" + secPay.Transfer.K.ToString() + " failed. Please contact an administrator for further details.";
                    throw new DsiUserFriendlyException("SecPay payment #" + secPay.Transfer.K.ToString() + " failed. See SecPay response for details.");
				}
			}
			catch (Exception ex)
			{
				ProcessException(ex, secPay);
			}
			if (ContainerPage != null && !HideValidationSummary)
				ContainerPage.AnchorSkip(this.ClientID + "_PaymentAnchor");
		}
Ejemplo n.º 5
0
		public void PayWithNewCard_Click(object o, System.EventArgs e)
		{
			CheckSslStatus();

			try
			{
				PaymentClickEventArgs paymentClickEventArgs = new PaymentClickEventArgs();
				if (PaymentClick != null)
					PaymentClick(this, paymentClickEventArgs);

				if (paymentClickEventArgs.Abort)
					return;

				if (Page.IsValid)
				{
					this.CardNumberHash = Cambro.Misc.Utility.Hash(CardNumber.Text.Replace(" ", ""));
					if (this.ValidateAndLockInvoices())
					{
						secPay = new SecPay();
						try
						{
							string cardFullName = "";
							
							
							
							string cardNumber = "";
							string cardCV2 = "";
							DateTime cardStartDate = DateTime.MinValue;
							DateTime cardExpiryDate = DateTime.MinValue;
							string cardIssueNumber = "";
							
							
							cardFullName = Name.Text;
							string cardAddressStreet = Address.Text;
							string cardAddressPostCode = Postcode.Text.ToUpper();
							string cardAddressArea = uiAddressArea.Text;
							string cardAddressTown = uiAddressTown.Text;
							string cardAddressCounty = uiAddressCounty.Text;


							int cardAddressCountryK = LockedCountryK ?? ((CountryTable.Visible && FraudCheck.Equals(Transfer.FraudCheckEnum.Strict)) ? int.Parse(CountryDropDownList.SelectedValue) : 224);
							string cardAddressCountry = (CountryTable.Visible && FraudCheck.Equals(Transfer.FraudCheckEnum.Strict)) ? CountryDropDownList.SelectedItem.Text : "UK";
							

							cardNumber = CardNumber.Text;
							cardCV2 = Cv2.Text;

							int cardEndYear = Convert.ToInt32(EndDateYear.Text.Trim());
							cardEndYear += ((cardEndYear < 80) ? 2000 : 1900);
							cardExpiryDate = new DateTime(cardEndYear, Convert.ToInt32(EndDateMonth.Text.Trim()), 1);
							if (StartDateMonth.Text.Length > 0)
							{
								int cardStartYear = Convert.ToInt32(StartDateYear.Text.Trim());
								cardStartYear += ((cardStartYear < 80) ? 2000 : 1900);
								cardStartDate = new DateTime(cardStartYear, Convert.ToInt32(StartDateMonth.Text.Trim()), 1);
							}
							if (Issue.Text.Length > 0)
								cardIssueNumber = Issue.Text;

							bool creatingInvoices = false;

							foreach (InvoiceDataHolder idh in Invoices)
							{
								creatingInvoices = idh.K == 0;

								SetInvoiceDatesUsrsGuid(idh);
							}

							int promoterK = 0;
							if (CurrentPromoter != null)
								promoterK = CurrentPromoter.K;

							if (Vars.DevEnv)
								System.Threading.Thread.Sleep(1000);

							secPay.MakePayment(
								Invoices,
								InvoiceTotalAfterBalanceAndCredit,
								CurrentUsr,
								promoterK,
								CurrentUsr.K,
								cardFullName,
								cardAddressStreet,
								cardAddressArea,
								cardAddressTown,
								cardAddressCounty,
								cardAddressCountryK,
								cardAddressPostCode,
								cardAddressCountry,
								cardNumber,
								cardExpiryDate,
								cardCV2,
								FraudCheck,
								this.SaveCardCheckBox.Checked,
								(Guid)ViewState["DuplicateGuidTransfer"],
								cardStartDate,
								cardIssueNumber);
							if (GetFullAddress)
							{
								Usr usr = Usr.Current;
								usr.AddressStreet = cardAddressStreet;
								usr.AddressTown = cardAddressTown;
								usr.AddressCounty = cardAddressCounty;
								usr.AddressCountryK = cardAddressCountryK;
								usr.AddressPostcode = cardAddressPostCode;
								usr.Update();

							}
						}
						catch (Exception ex)
						{
							ProcessingVal.ErrorMessage = RETRY_INVOICE_ERROR_MSG;
							//try
							//{
							//    this.UnlockInvoiceItems();
							//}
							//catch (Exception)
							//{ }
							ProcessException(ex, CardNumber.Text);
							return;
						}

						if (secPay.Transfer.Status.Equals(Transfer.StatusEnum.Success))
							this.ProcessSuccessfulSecPayTransfer(secPay);
						else
							this.HandleFailedSecPayTransfer(secPay);
					}
				}
				else
				{
					if (ContainerPage != null && !HideValidationSummary)
						ContainerPage.AnchorSkip(this.ClientID + "_PaymentAnchor");
				}
			}
			catch (Exception ex)
			{
				ProcessingVal.ErrorMessage = RETRY_INVOICE_ERROR_MSG;
				ProcessException(ex);
				return;
			}
		}
Ejemplo n.º 6
0
		public void PayWithSavedCard_Click(object o, System.EventArgs e)
		{
			CheckSslStatus();

			try
			{
				if (IsValidTotal() && AllowSavedCards)
				{
					PaymentClickEventArgs paymentClickEventArgs = new PaymentClickEventArgs();
					if (PaymentClick != null)
						PaymentClick(this, paymentClickEventArgs);

					if (paymentClickEventArgs.Abort)
						return;

					if (Page.IsValid)
					{

						Transfer prevSavedTransfer = new Transfer(Convert.ToInt32(this.SavedCardDropDownList.SelectedValue));
						this.CardNumberHash = prevSavedTransfer.CardNumberHash;
						//check for duplicate invoices
						if (ValidateAndLockInvoices())
						{
							secPay = new SecPay();
							//bool creatingInvoices = false;
							//int savedTransferK = Convert.ToInt32(this.SavedCardDropDownList.SelectedValue);

							if (!CurrentUsr.CheckPassword(PasswordTextBox.Text))
							{
								ProcessingVal.IsValid = false;
								ProcessingVal.ErrorMessage = "Incorrect password";
								this.UnlockInvoiceItems();

								if (ContainerPage != null && !HideValidationSummary)
									ContainerPage.AnchorSkip(this.ClientID + "_PaymentAnchor");
							}
							else
							{
								try
								{
									foreach (InvoiceDataHolder idh in Invoices)
									{
										//creatingInvoices = idh.K == 0;
										SetInvoiceDatesUsrsGuid(idh);
									}

									secPay.MakePaymentUsingSavedTransferDetails(
										Invoices,
										InvoiceTotalAfterBalanceAndCredit,
										CurrentUsr,
										prevSavedTransfer,
										FraudCheck,
										(Guid)ViewState["DuplicateGuidTransfer"]);
								}
								catch (Exception ex)
								{
									this.ProcessingVal.ErrorMessage = RETRY_INVOICE_ERROR_MSG;
									//try
									//{
									//    this.UnlockInvoiceItems();
									//}
									//catch (Exception)
									//{ }
									this.ProcessException(ex, prevSavedTransfer.CardNumberEnd);
									return;
								}

								if (secPay.Transfer.Status.Equals(Transfer.StatusEnum.Success))
									this.ProcessSuccessfulSecPayTransfer(secPay);
								else
									this.HandleFailedSecPayTransfer(secPay);
							}
						}
					}
					else
					{
						if (ContainerPage != null && !HideValidationSummary)
							ContainerPage.AnchorSkip(this.ClientID + "_PaymentAnchor");
					}

				}
				else
				{
					// Re evaluate.
					this.Initialize();
					
				}
			}
			catch (Exception ex)
			{
				ProcessingVal.ErrorMessage = RETRY_INVOICE_ERROR_MSG;
				ProcessException(ex);
				return;
			}
			
		}
Ejemplo n.º 7
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;
            }
        }
Ejemplo n.º 8
0
		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();
				}
			}
		}