Example #1
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;
			}
		}
		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();
				}
			}
		}