Exemple #1
0
		static void appendTransferAndInvoiceTransfer(StringBuilder sb, Transfer t, InvoiceTransfer it)
		{
			sb.Append(SALES_RECEIPT_TRANSACTION_TYPE);
			sb.Append(DELIMITER);
			sb.Append(t.PromoterK);
			sb.Append(DELIMITER);
			sb.Append(t.Type.ToString());
			sb.Append(DELIMITER);
			sb.Append(t.Method.ToString());
			sb.Append(DELIMITER);
			sb.Append(t.DateTimeComplete.ToString("dd/MM/yy"));
			sb.Append(DELIMITER);
			sb.Append(t.Amount.ToString("0.00"));
			sb.Append(DELIMITER);
			sb.Append(TRANSFER_K_PREFIX);							// Prefix + K.ToString() <= 8 characters
			sb.Append(t.K.ToString("000000"));				        // Up to 6 digit K number. for K of 10^6 or greater, reduce the prefix size
			if (it != null)
			{
				sb.Append(DELIMITER);
				sb.Append(INVOICE_K_PREFIX);
				sb.Append(it.InvoiceK.ToString("000000"));
				sb.Append(DELIMITER);
				sb.Append(it.Amount.ToString("0.00"));
			}
			else
			{
				sb.Append(DELIMITER);
				sb.Append(DELIMITER);
			}
			sb.Append(NEWLINE);
		}
		//protected void GenBannerStats_Click(object sender, EventArgs eventArgs)
		//{
		//    Banner.GeneratePositionStats();
		//}
		#endregion

		#region UpdateOldDBInvoices_Click
		public void UpdateOldDBInvoices_Click(object o, System.EventArgs e)
		{
			Cambro.Web.Helpers.WriteAlertHeader();

			Cambro.Web.Helpers.WriteAlert("Selecting xxx...", 1);

			Query InvoiceQuery = new Query();
			InvoiceQuery.OrderBy = new OrderBy(Invoice.Columns.K, OrderBy.OrderDirection.Ascending);

			InvoiceSet bs = new InvoiceSet(InvoiceQuery);

			for (int count = 0; count < bs.Count; count++)
			{
				Invoice invoice = bs[count];

				try
				{
					invoice.Type = Invoice.Types.Invoice;
					invoice.IsImmediateCreditCardPayment = true;
					invoice.ActionUsrK = invoice.UsrK;
					invoice.VatCode = Invoice.VATCodes.T1;
					decimal invoicePrice = 0;
					decimal invoiceVat = 0;
					decimal invoiceTotal = 0;

					foreach (InvoiceItem invoiceItem in invoice.Items)
					{
						//invoiceItem.Price = Math.Round(invoiceItem.Price, 2);
						//invoiceItem.Vat = Math.Round(invoiceItem.Vat, 2);
						//invoiceItem.Total = Math.Round(invoiceItem.Total, 2);

						invoicePrice += invoiceItem.Price;
						invoiceVat += invoiceItem.Vat;
						invoiceTotal += invoiceItem.Total;

						if (invoiceItem.Type == InvoiceItem.Types.CharityDonation)
							invoiceItem.VatCode = InvoiceItem.VATCodes.T9;
						else if(invoiceItem.Vat.Equals(0))
							invoiceItem.VatCode = InvoiceItem.VATCodes.T0;
						else
							invoiceItem.VatCode = InvoiceItem.VATCodes.T1;

						if (invoiceItem.Type == InvoiceItem.Types.Banner || invoiceItem.Type == InvoiceItem.Types.BannerEmail || invoiceItem.Type == InvoiceItem.Types.BannerHotbox
							|| invoiceItem.Type == InvoiceItem.Types.BannerPhoto || invoiceItem.Type == InvoiceItem.Types.BannerSkyscraper || invoiceItem.Type == InvoiceItem.Types.BannerTop)
						{
							try
							{
								Banner banner = new Banner(invoiceItem.KeyData);
								invoiceItem.RevenueStartDate = banner.FirstDay;
								invoiceItem.RevenueEndDate = banner.LastDay;
							}
							catch (Exception)
							{ }
						}
						else
						{
							invoiceItem.RevenueStartDate = invoice.CreatedDateTime;
							invoiceItem.RevenueEndDate = invoice.CreatedDateTime;
						}
						invoiceItem.Update();
					}

					invoice.Price = Math.Round(invoicePrice,2);
					invoice.Vat = Math.Round(invoiceVat,2);
					invoice.Total = Math.Round(invoiceTotal, 2);

					if (invoice.DueDateTime.Equals(DateTime.MinValue))
						invoice.DueDateTime = invoice.CreatedDateTime.AddDays(30);

					invoice.UpdateAndSetPaidStatus();

					// If there arent transfers paying for this invoices yet, then create them.
					decimal amountPaid = invoice.AmountPaid;
					if (Math.Round(invoice.Total,2) > Math.Round(amountPaid,2))
					{
						InvoiceTransferSet invoiceTransferSet = new InvoiceTransferSet(new Query(new Q(InvoiceTransfer.Columns.InvoiceK, invoice.K)));
						if (invoiceTransferSet.Count == 0)
						{
							Transfer transfer = new Transfer();
							transfer.ActionUsrK = invoice.UsrK;
							transfer.Amount = Math.Round(invoice.Total - amountPaid, 2);
							transfer.DateTimeComplete = invoice.CreatedDateTime;
							transfer.DateTimeCreated = invoice.CreatedDateTime;
							transfer.Method = Transfer.Methods.Card;
							transfer.AddNote("Autogenerated Transfer to create transfer for old system invoice.", "System");
							transfer.PromoterK = invoice.PromoterK;
							transfer.Status = Transfer.StatusEnum.Success;
							transfer.Type = Transfer.TransferTypes.Payment;
							transfer.UsrK = invoice.UsrK;
							// Will be fully applied
							transfer.IsFullyApplied = true;

							transfer.CardAddress1 = invoice.Address;
							transfer.CardName = invoice.Name;
							transfer.CardPostcode = invoice.Postcode;

							transfer.Update();

							InvoiceTransfer invoiceTransfer = new InvoiceTransfer();
							invoiceTransfer.InvoiceK = invoice.K;
							invoiceTransfer.TransferK = transfer.K;
							invoiceTransfer.Amount = transfer.Amount;

							invoiceTransfer.Update();

							invoice.UpdateAndSetPaidStatus();
						}
					}
					invoice.PaidDateTime = invoice.CreatedDateTime;
					invoice.Update();
					if (count % 10 == 0)
						Cambro.Web.Helpers.WriteAlert("Done " + count + "/" + bs.Count, 2);
				}
				catch (Exception ex)
				{
					Cambro.Web.Helpers.WriteAlert("Exception " + count + "/" + bs.Count + " - " + ex.ToString(), 3);
				}

				bs.Kill(count);
			}
			Cambro.Web.Helpers.WriteAlert("Done!", 3);
			Cambro.Web.Helpers.WriteAlertFooter();
		}
        protected void CreditTransferGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
			if (e.CommandName.ToUpper().Equals("ADD"))
			{
				// add new row from footer to db
				InvoiceTransfer newCreditTransfer = new InvoiceTransfer();

				GridViewRow row = CreditTransferGridView.FooterRow;

				newCreditTransfer.Amount = Utilities.ConvertMoneyStringToDecimal(((TextBox)row.FindControl("NewAmountTextBox")).Text);
				newCreditTransfer.TransferK = Convert.ToInt32(((DropDownList)row.FindControl("NewTransferKDropDownList")).SelectedValue);
				newCreditTransfer.InvoiceK = CreditK;

				decimal totalRefundAmount = 0;

				bool doNotAdd = Math.Round(newCreditTransfer.Amount, 2) == 0;

				foreach (InvoiceTransferDataHolder itdh in this.CreditTransferDataHolderList)
				{
					if (itdh.TransferK == newCreditTransfer.TransferK)
					{
						this.ProcessingVal.ErrorMessage = "Cannot add money from transfer #" + itdh.TransferK + " more than once";
						this.ProcessingVal.IsValid = false;
						doNotAdd = true;
					}
					totalRefundAmount += itdh.Amount;
				}
				if (doNotAdd == false)
				{
					if (new Transfer(newCreditTransfer.TransferK).AmountRemaining() > newCreditTransfer.Amount)
					{
						this.ProcessingVal.ErrorMessage = "Insufficient funds available on refund #" + newCreditTransfer.TransferK;
						this.ProcessingVal.IsValid = false;
						doNotAdd = true;
					}
				}
				if (doNotAdd == false)
				{
					foreach (InvoiceCreditDataHolder icdh in this.CreditInvoiceDataHolderList)
					{
						totalRefundAmount -= icdh.Amount;
					}

					if (totalRefundAmount + newCreditTransfer.Amount < Convert.ToDecimal(TotalTextBox.Text.Replace("£", "")))
					{
						this.ProcessingVal.ErrorMessage = "Adding " + newCreditTransfer.Amount.ToString("c") + " from transfer #" + newCreditTransfer.TransferK + " would exceed the total amount of this credit";
						this.ProcessingVal.IsValid = false;
						doNotAdd = true;
					}
				}
				if (doNotAdd == false)
				{
					InvoiceTransferDataHolder itdh = new InvoiceTransferDataHolder(newCreditTransfer);
					itdh.State = DataHolderState.Added;
					CreditTransferDataHolderList.Add(itdh);

					ViewState["CreditTransferDataHolderList"] = CreditTransferDataHolderList;

					CalculateCreditItemVatAndTotals();
				}
				else
				{
					CreditAndSubItemsBindData();
				}
			}
        }
 public InvoiceTransferDataHolder(InvoiceTransfer invoiceTransfer)
 {
     this.invoiceK = invoiceTransfer.InvoiceK;
     this.transferK = invoiceTransfer.TransferK;
     this.amount = invoiceTransfer.Amount;
     Transfer transfer = new Transfer(invoiceTransfer.TransferK);
     this.type = transfer.Type;
     this.method = transfer.Method;
     this.status = transfer.Status;
     this.usrK = transfer.UsrK;
 }
        public InvoiceTransfer ExportToInvoiceTransfer()
        {
            InvoiceTransfer invoiceTransfer = new InvoiceTransfer();
            
			try
			{
				invoiceTransfer = new InvoiceTransfer(this.invoiceK, this.transferK);
			}
			catch (Exception)
			{
				// if it doesnt already exist in the database, then it is new.
				this.State = DataHolderState.Added;
				invoiceTransfer.InvoiceK = this.invoiceK;
				invoiceTransfer.TransferK = this.transferK;
			}                
            invoiceTransfer.Amount = this.amount;

            return invoiceTransfer;
        }
Exemple #6
0
		private void ProcessPaymentResults()
		{
			this.transfer.DateTimeComplete = this.transfer.DateTimeCreated;

			this.transfer.Update();

			if (this.transfer.Status.Equals(Transfer.StatusEnum.Success))
			{
				try
				{
					Invoice invoice = new Invoice();
					// Apply to invoices
					foreach (InvoiceDataHolder idh in invoiceDataHolders)
					{
						bool creatingInvoice = false;

						// Get Invoice.K for unsaved invoices
						if (idh.K == 0)
						{
							creatingInvoice = true;
							idh.Type = Invoice.Types.Invoice;
							idh.VatCode = Invoice.VATCodes.T1;
							invoice = idh.UpdateInsertDelete();
						}
						else
						{
							invoice = new Invoice(idh.K);
						}
                        
						InvoiceTransfer invoiceTransfer = new InvoiceTransfer();
						invoiceTransfer.InvoiceK = invoice.K;
						invoiceTransfer.TransferK = this.transfer.K;
						if (amount >= invoice.Total)
							invoiceTransfer.Amount = invoice.Total;
						else
							invoiceTransfer.Amount = amount;

						amount -= invoiceTransfer.Amount;

						invoiceTransfer.Update();

						if (invoiceTransfer.Amount == invoice.Total && creatingInvoice)
							invoice.IsImmediateCreditCardPayment = true;
                        invoice.AssignBuyerType();
						invoice.UpdateAndAutoApplySuccessfulTransfersWithAvailableMoney();//.UpdateAndSetPaidStatus();
						if (creatingInvoice)
						{
							if (invoice.Paid && invoice.DueDateTime > invoice.PaidDateTime)
							{
								invoice.DueDateTime = invoice.PaidDateTime;
								invoice.Update();
							}
							invoice.Process();
						}
						this.invoices.Add(invoice);
					}

					if (Math.Round(amount, 2) == 0)
					{
						this.transfer.IsFullyApplied = true;
						this.transfer.Update();
					}
					Utilities.EmailTransfer(transfer, true, true);
				}
				catch (Exception ex)
				{
					EmailSecPayException(ex);
				}
			}
		}
Exemple #7
0
		public void ApplyTransfersToThisInvoice(List<Transfer> transfers)
		{
			bool complete = false;
			var amountDue = this.AmountDue;
			var availableMoney = 0m;
			if (this.Promoter != null)
				availableMoney = this.Promoter.GetAvailableMoney();
			else if (this.Usr != null)
				availableMoney = this.Usr.GetBalance();

			foreach (Transfer transfer in transfers)
			{
				decimal amountRemaining = transfer.AmountRemaining();

				// This transfer should be fully applied
				if (Math.Round(amountRemaining, 2) <= 0)
				{
					transfer.IsFullyApplied = true;
					transfer.Update();
					continue;
				}

				if (Math.Round(availableMoney, 2) <= 0)
					break;

				// As refunds can be given and not applied specifically as credits, we need to check the promoter balance so that we dont apply more money than is actually available on their account
				if (Math.Round(amountRemaining, 2) > Math.Round(availableMoney, 2))
					amountRemaining = Math.Round(availableMoney, 2);

				InvoiceTransfer invoiceTransfer;

				// If there already exists an InvoiceTransfer but for not the total amount, then update it with more ���
				try
				{
					invoiceTransfer = new InvoiceTransfer(this.K, transfer.K);
				}
				catch (Exception)
				{
					invoiceTransfer = new InvoiceTransfer();
					invoiceTransfer.InvoiceK = this.K;
					invoiceTransfer.TransferK = transfer.K;
					invoiceTransfer.Amount = 0;
				}

				if (Math.Round(amountRemaining, 2) >= Math.Round(amountDue, 2))
				{
					invoiceTransfer.Amount += Math.Round(amountDue, 2);
					complete = true;
				}
				else
				{
					invoiceTransfer.Amount += Math.Round(amountRemaining, 2);
					amountDue -= Math.Round(invoiceTransfer.Amount, 2);
					availableMoney -= Math.Round(amountRemaining, 2);
				}

				if (transfer.Method == Transfer.Methods.TicketSales)
				{
				//	decimal amountApplied = Math.Round(amountRemaining, 2) >= Math.Round(amountDue, 2) ? Math.Round(amountDue, 2) : Math.Round(amountRemaining, 2);
				//	BankExport.GenerateBankExportForTicketFundsUsed(transfer, amountApplied, this);
				}
				this.AddNote("Automatically added " + invoiceTransfer.Amount.ToString("c") + " from transfer #" + invoiceTransfer.TransferK.ToString() + " to this invoice", "System");

				if (invoiceTransfer.TransferK > 0 && invoiceTransfer.InvoiceK > 0)
					invoiceTransfer.Update();

				if (transfer.AmountRemaining() == 0)
				{
					transfer.IsFullyApplied = true;
					transfer.Update();
				}

				if (complete == true)
					break;
			}
			//return complete;
		}
        protected void InvoiceTransferGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToUpper().Equals("ADD"))
            {
                // add new row from footer to db
                InvoiceTransfer newInvoiceTransfer = new InvoiceTransfer();

                GridViewRow row = InvoiceTransferGridView.FooterRow;

                newInvoiceTransfer.Amount = Utilities.ConvertMoneyStringToDecimal(((TextBox)row.FindControl("NewAmountTextBox")).Text);
                newInvoiceTransfer.TransferK = Convert.ToInt32(((DropDownList)row.FindControl("NewTransferKDropDownList")).SelectedValue);
                newInvoiceTransfer.InvoiceK = InvoiceK;

				decimal totalTransferAmount = 0;

				bool doNotAdd = Math.Round(newInvoiceTransfer.Amount, 2) == 0;

				foreach (InvoiceTransferDataHolder itdh in this.InvoiceTransferDataHolderList)
				{
					if (itdh.TransferK == newInvoiceTransfer.TransferK)
					{
						ProcessingVal.ErrorMessage = "Cannot add money from transfer #" + itdh.TransferK + " more than once";
						ProcessingVal.IsValid = false;
						doNotAdd = true;
					}

					totalTransferAmount += itdh.Amount;
				}

				if (doNotAdd == false)
				{
					if (new Transfer(newInvoiceTransfer.TransferK).AmountRemaining() < newInvoiceTransfer.Amount)
					{
						ProcessingVal.ErrorMessage = "Insufficient funds available on transfer #" + newInvoiceTransfer.TransferK;
						ProcessingVal.IsValid = false;
						doNotAdd = true;
					}
				}
				if (doNotAdd == false)
				{
					foreach (InvoiceCreditDataHolder icdh in this.InvoiceCreditDataHolderList)
					{
						totalTransferAmount -= icdh.Amount;
					}
		public void ConfirmButton_Click(object o, System.EventArgs e)
		{
			if (Usr.Current != null)
			{
				// Check for duplicate invoices
				int transferK = GetDuplicateGuidTransferK();

				// Create new transfer
				if (transferK == 0)
				{
					CurrentTransfer = new Transfer();
					try
					{
						CurrentTransfer.Status = Transfer.StatusEnum.Pending;

						decimal totalAmountDue = 0;
						foreach (InvoiceDataHolder idh in Invoices)
						{
							totalAmountDue += idh.AmountDue;
						}
						CurrentTransfer.Amount = Math.Round(totalAmountDue, 2);
						CurrentTransfer.UsrK = Usr.Current.K;
						CurrentTransfer.ActionUsrK = Usr.Current.K;
						CurrentTransfer.DuplicateGuid = (Guid)this.ViewState["DuplicateGuidTransfer"];
						if (this.PayOptionRadioButtonSetupBankTransferPayment.Checked)
							CurrentTransfer.Method = Transfer.Methods.BankTransfer;
						else if (this.PayOptionRadioButtonSetupChequePayment.Checked)
							CurrentTransfer.Method = Transfer.Methods.Cheque;
						CurrentTransfer.PromoterK = PromoterK;
						CurrentTransfer.Type = Transfer.TransferTypes.Payment;
						CurrentTransfer.DateTimeCreated = DateTime.Now;

						CurrentTransfer.Update();
						CurrentTransfer = CurrentTransfer;
						
						foreach (InvoiceDataHolder idh in Invoices)
						{
							InvoiceTransfer invoiceTransfer = new InvoiceTransfer();
							invoiceTransfer.Amount = idh.AmountDue;
							invoiceTransfer.InvoiceK = idh.K;
							invoiceTransfer.TransferK = CurrentTransfer.K;

							invoiceTransfer.Update();

							totalAmountDue -= idh.AmountDue;
						}

						if (Math.Round(totalAmountDue, 2) != 0)
						{
							throw new Exception("Transfer amount not correctly applied. Difference = " + Math.Round(totalAmountDue, 2).ToString("c"));
						}
						Utilities.EmailTransfer(CurrentTransfer, true, false);
						CheckCompleted();
					}
					catch (Exception ex)
					{
						// Rollback transfer and invoiceTransfers
						this.RollbackTransfer();
						Utilities.AdminEmailAlert("<p>Exception occurred during setup of transfer in SetupPayment control</p><p>Transfer K=" + CurrentTransfer.K.ToString() + "</p>",
													"Exception occurred during setup of transfer (K=" + CurrentTransfer.K.ToString() + ") in SetupPayment control", ex, CurrentTransfer);
					}
				}
				else if (CurrentTransfer == null)
				{
					CurrentTransfer = new Transfer(transferK);
					CheckCompleted();
				}
			}
			if (ContainerPage != null)
				ContainerPage.AnchorSkip(this.ClientID + "_SetupPaymentAnchor");
		}
		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();
				}
			}
		}