protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    CustomerInformationManager cim = new CustomerInformationManager();

                    Customer cust = cim.GetCustomer("9925034");

                    if (cust == null)
                    {
                        cust = cim.CreateCustomer("*****@*****.**", "test user");
                    }

                    Address addrShipping = new Address
                    {
                        City    = "tampa",
                        Company = "some comp",
                        Country = "US",
                        First   = "Dev",
                        Last    = "Ryan",
                        Phone   = "123-234-3456",
                        State   = "FL",
                        Street  = "600 Westshore Blvd",
                        Zip     = "33609",
                        Fax     = ""
                    };

                    string addShipResponse = cim.AddShippingAddress(cust, addrShipping);

                    if (cust != null && string.IsNullOrWhiteSpace(cust.ID))
                    {
                        cust.ID = "123456";

                        cim.UpdateCustomer(cust);
                    }

                    string addCCResponse = cim.AddCreditCard(cust, "4111111111111111", 6, 2013, "123", addrShipping);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        private void LoadModule()
        {
            AuthNetConfig authNetConfig = new AuthNetConfig();

            ltlAuthNetName.Text           = authNetConfig.Settings.Name;
            ltlAuthNetApiKey.Text         = authNetConfig.Settings.ApiKey;
            ltlAuthNetTransactionKey.Text = authNetConfig.Settings.TransactionKey;
            ltlAuthNetMode.Text           = authNetConfig.Settings.TestMode ? "Test Mode" : "Live Mode";

            try
            {
                CustomerInformationManager cim     = new CustomerInformationManager();
                hccUserProfile             profile = hccUserProfile.GetRootProfiles().First(a => a.AuthNetProfileID != null);

                validateCustomerPaymentProfileResponse valProfile =
                    cim.ValidateProfile(profile.AuthNetProfileID, profile.ActivePaymentProfile.AuthNetPaymentProfileID, AuthorizeNet.ValidationMode.TestMode);

                if (valProfile.messages.resultCode == messageTypeEnum.Ok)
                {
                    lblTest.Text = "Test Validation Successful.";
                }
                else
                {
                    lblTest.Text = "Test Validation Failed.";
                }
            }
            catch (Exception ex)
            {
                lblTest.Text = "Test Connection Failed." + ex.Message + ex.StackTrace;
            }
            //List<TestCard> cards = new List<TestCard>();

            //foreach(TestCard card in credentials.TestCards)
            //{
            //    cards.Add(card);
            //}

            //TestCards.DataSource = cards;
            //TestCards.DataBind();
        }
        public string UpdateCarts(List <UpdateCartItem> carts)
        {
            try
            {
                UpdateCartItem     updatecart   = carts[0];
                hccCart            CurrentCart  = hccCart.GetById(updatecart.cartId);
                hccUserProfile     ownerProfile = CurrentCart.OwnerProfile;
                hccAddress         snapBillAddr = null;
                List <hccCartItem> cartItems    = null;
                bool      isAuthNet             = false;
                hccLedger ledger = null;
                string    retVal = string.Empty;

                if (CurrentCart != null && ownerProfile != null)
                {
                    hccAddress billAddr = null;
                    hccUserProfilePaymentProfile activePaymentProfile = ownerProfile.ActivePaymentProfile;

                    if (updatecart.updateStatus && CurrentCart.StatusID != updatecart.statusId)
                    {
                        CurrentCart.StatusID     = updatecart.statusId;
                        CurrentCart.ModifiedBy   = (Guid)Helpers.LoggedUser.ProviderUserKey;
                        CurrentCart.ModifiedDate = DateTime.Now;

                        if (updatecart.statusId == (int)Enums.CartStatus.Paid)
                        {
                            if (!CurrentCart.PurchaseBy.HasValue)
                            {
                                CurrentCart.PurchaseBy = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            }

                            if (!CurrentCart.PurchaseDate.HasValue)
                            {
                                CurrentCart.PurchaseDate = DateTime.Now;
                            }
                        }
                        CurrentCart.Save();
                    }

                    if (updatecart.updateAddresses) // re-snap addresses
                    {
                        if (ownerProfile.BillingAddressID.HasValue)
                        {
                            billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                        }
                        else
                        {
                            retVal += "Profile has no billing address on record.";
                        }

                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            hccAddress shipAddr = null;

                            if (snapBillAddr != null)
                            {
                                ci.SnapBillAddrId = snapBillAddr.AddressID;
                            }

                            if (ci.UserProfile == null)
                            {
                                ci.UserProfileID = ownerProfile.UserProfileID;
                            }

                            if (ci.UserProfile.ShippingAddressID.HasValue)
                            {
                                shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                            }

                            if (shipAddr != null)
                            {
                                hccAddress snapShipAddr = new hccAddress
                                {
                                    Address1              = shipAddr.Address1,
                                    Address2              = shipAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                    City                  = shipAddr.City,
                                    Country               = shipAddr.Country,
                                    DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                    FirstName             = shipAddr.FirstName,
                                    IsBusiness            = shipAddr.IsBusiness,
                                    LastName              = shipAddr.LastName,
                                    Phone                 = shipAddr.Phone,
                                    PostalCode            = shipAddr.PostalCode,
                                    State                 = shipAddr.State,
                                    ProfileName           = ci.UserProfile.ProfileName
                                };
                                snapShipAddr.Save();
                                ci.SnapShipAddrId = snapShipAddr.AddressID;
                            }

                            ci.Save();
                        });
                    }

                    if (updatecart.rerunAuthNet)
                    {
                        CurrentCart.StatusID     = (int)Enums.CartStatus.Unfinalized;
                        CurrentCart.PurchaseBy   = null;
                        CurrentCart.PurchaseDate = null;

                        if (ownerProfile != null)
                        {
                            AuthNetConfig ANConfig = new AuthNetConfig();

                            if (ANConfig.Settings.TestMode)
                            {
                                CurrentCart.IsTestOrder = true;
                            }

                            if (CurrentCart.PaymentDue > 0.00m)
                            {
                                try
                                {   // if total balance remains
                                    CustomerInformationManager cim = new CustomerInformationManager();

                                    if (activePaymentProfile != null)
                                    {
                                        AuthorizeNet.Order order = new AuthorizeNet.Order(ownerProfile.AuthNetProfileID,
                                                                                          activePaymentProfile.AuthNetPaymentProfileID, null);

                                        // charge CIM account with PaymentDue balance
                                        order.Amount        = CurrentCart.PaymentDue;
                                        order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                        order.Description   = "Healthy Chef Creations Purchase #" + CurrentCart.PurchaseNumber.ToString();

                                        AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" + rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" + rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                        }
                                        catch (Exception) { }

                                        if (rsp.ResponseCode.StartsWith("1"))
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.PurchaseDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                            isAuthNet = true;
                                        }
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        return("No active payment profile.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex is InvalidOperationException)
                                    {
                                        if (CurrentCart.IsTestOrder)
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.AuthNetResponse  = ex.Message;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                            CurrentCart.Save();
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            else
                            {      // no balance left to pay on order, set as paid
                                CurrentCart.AuthNetResponse = "Paid with account balance.";
                                CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.ModifiedDate    = DateTime.Now;
                                CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.PurchaseDate    = DateTime.Now;
                                CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                                CurrentCart.Save();
                            }
                        }
                    }

                    if (updatecart.createLedgerEntry)
                    {
                        if (ledger == null)
                        {
                            ledger = hccLedger.GetBy(CurrentCart.CartID);
                        }

                        if (ledger == null)
                        {
                            SaveLedger(ledger, CurrentCart, ownerProfile);
                        }
                    }

                    if (updatecart.createNewSnapshot)
                    {
                        if (((Enums.CartStatus)CurrentCart.StatusID) == Enums.CartStatus.Paid)
                        {
                            if (ledger == null)
                            {
                                ledger = hccLedger.GetBy(CurrentCart.CartID);
                            }

                            if (ledger == null) // it still equals null
                            {
                                SaveLedger(ledger, CurrentCart, ownerProfile);
                            }

                            // create snapshot here
                            hccCartSnapshot snap = new hccCartSnapshot
                            {
                                CartId           = CurrentCart.CartID,
                                MembershipId     = ownerProfile.MembershipID,
                                LedgerId         = ledger.LedgerID,
                                AccountBalance   = ownerProfile.AccountBalance,
                                AuthNetProfileId = ownerProfile.AuthNetProfileID,
                                CreatedBy        = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate      = DateTime.Now,
                                DefaultCouponId  = ownerProfile.DefaultCouponId,
                                Email            = ownerProfile.ASPUser.Email,
                                FirstName        = ownerProfile.FirstName,
                                LastName         = ownerProfile.LastName,
                                ProfileName      = ownerProfile.ProfileName
                            };

                            if (isAuthNet)
                            {
                                if (activePaymentProfile != null)
                                {
                                    snap.AuthNetPaymentProfileId = activePaymentProfile.AuthNetPaymentProfileID;
                                    snap.CardTypeId = activePaymentProfile.CardTypeID;
                                    snap.CCLast4    = activePaymentProfile.CCLast4;
                                    snap.ExpMon     = activePaymentProfile.ExpMon;
                                    snap.ExpYear    = activePaymentProfile.ExpYear;
                                    snap.NameOnCard = activePaymentProfile.NameOnCard;
                                }
                                else
                                {
                                    return("No active payment profile.");
                                }
                            }
                            else
                            {
                                snap.AuthNetPaymentProfileId = string.Empty;
                                snap.CardTypeId = 0;
                                snap.CCLast4    = string.Empty;
                                snap.ExpMon     = 0;
                                snap.ExpYear    = 0;
                                snap.NameOnCard = string.Empty;
                            }
                            snap.Save();

                            if (billAddr == null && ownerProfile.BillingAddressID.HasValue)
                            {
                                billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);
                            }

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = billAddr.AddressTypeID,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                            else
                            {
                                retVal += "Profile has no billing address on record.";
                            }

                            // copy and replace of all addresses for snapshot
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            cartItems.ToList().ForEach(delegate(hccCartItem ci)
                            {
                                if (snapBillAddr != null)
                                {
                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                }

                                hccAddress shipAddr = null;
                                if (ci.UserProfile.ShippingAddressID.HasValue)
                                {
                                    shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                }

                                if (shipAddr != null)
                                {
                                    hccAddress snapShipAddr = new hccAddress
                                    {
                                        Address1              = shipAddr.Address1,
                                        Address2              = shipAddr.Address2,
                                        AddressTypeID         = shipAddr.AddressTypeID,
                                        City                  = shipAddr.City,
                                        Country               = shipAddr.Country,
                                        DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                        FirstName             = shipAddr.FirstName,
                                        IsBusiness            = shipAddr.IsBusiness,
                                        LastName              = shipAddr.LastName,
                                        Phone                 = shipAddr.Phone,
                                        PostalCode            = shipAddr.PostalCode,
                                        State                 = shipAddr.State,
                                        ProfileName           = ci.UserProfile.ProfileName
                                    };
                                    snapShipAddr.Save();
                                    ci.SnapShipAddrId = snapShipAddr.AddressID;
                                }
                                else
                                {
                                    retVal += "Profile has no billing address on record.";
                                }

                                ci.Save();
                            });
                        }
                    }

                    if (updatecart.sendCustomerEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationMerchant(ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml(), CurrentCart.CartID);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Merchant Mail Failed", this, ex); }
                    }

                    if (updatecart.sendMerchantEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationCustomer(ownerProfile.ASPUser.Email, ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml());
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send customer Mail Failed", this, ex); }
                    }

                    if (updatecart.repairCartCals)
                    {
                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }
                        // wrap in programs

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            if (ci.ItemType == Enums.CartItemType.DefinedPlan)
                            {
                                hccProgramPlan cp = hccProgramPlan.GetById(ci.Plan_PlanID.Value);

                                if (cp != null)
                                {
                                    for (int i = 0; i < cp.NumWeeks; i++)
                                    {
                                        hccProductionCalendar cal;
                                        cal = hccProductionCalendar.GetBy(ci.DeliveryDate.AddDays(7 * i));

                                        if (cal != null)
                                        {
                                            hccCartItemCalendar existCal = hccCartItemCalendar.GetBy(ci.CartItemID, cal.CalendarID);
                                            if (existCal == null)
                                            {
                                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                                    CalendarID = cal.CalendarID, CartItemID = ci.CartItemID, IsFulfilled = false
                                                };
                                                cartCal.Save();
                                            }
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                                "No production calendar found for Delivery Date: " + ci.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                        }
                                    }
                                }
                            }
                        });
                    }

                    if (updatecart.reCalcItemTax)
                    {
                        try
                        {
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            List <ProfileCart> CurrentProfileCarts = new List <ProfileCart>();

                            if (cartItems.Count > 0)
                            {
                                hccUserProfile parentProfile = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                //List<hccProductionCalendar> pc = new List<hccProductionCalendar>();

                                foreach (hccCartItem cartItem in cartItems)
                                {
                                    ProfileCart profCart;
                                    int         shippingAddressId;

                                    //if (!pc.Exists(a => a.DeliveryDate == cartItem.DeliveryDate))
                                    //    pc.Add(hccProductionCalendar.GetBy(cartItem.DeliveryDate));

                                    //hccProductionCalendar cpc = pc.SingleOrDefault(a => a.DeliveryDate == cartItem.DeliveryDate);

                                    //if (cpc != null && (cpc.OrderCutOffDate.AddDays(1) >= DateTime.Now || (HttpContext.Current.Request.Url.OriginalString.Contains("Admin"))))
                                    //{
                                    if (cartItem.UserProfile != null && (cartItem.UserProfile.UseParentShipping || cartItem.UserProfile.ShippingAddressID.HasValue))
                                    {
                                        if (cartItem.UserProfile.UseParentShipping)
                                        {
                                            shippingAddressId = parentProfile.ShippingAddressID.Value;
                                        }
                                        else
                                        {
                                            shippingAddressId = cartItem.UserProfile.ShippingAddressID.Value;
                                        }

                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == shippingAddressId && a.DeliveryDate == cartItem.DeliveryDate);
                                    }
                                    else
                                    {
                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == 0 &&
                                                                    a.DeliveryDate == cartItem.DeliveryDate);

                                        shippingAddressId = 0;
                                    }

                                    if (profCart == null)
                                    {
                                        profCart = new ProfileCart(shippingAddressId, cartItem.DeliveryDate);
                                        CurrentProfileCarts.Add(profCart);
                                    }

                                    profCart.CartItems.Add(cartItem);
                                    //}
                                    //else
                                    //{
                                    //    //cartItem.Delete();
                                    //    //lblFeedbackCart.Text = "Item(s) removed from cart due to expiration of availability.";

                                    //}
                                }
                            }

                            //// display totals
                            CurrentCart.CalculateTotals(CurrentProfileCarts);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Attempt to recalculate taz for cart items failed.", this, ex); }
                    }
                }
                return("Cart Updated: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void ProcessNewOrder(int cartId)
        {
            //bool dupTransaction = false;
            hccCart CurrentCart = null;

            try
            {
                // TODO: Check the cart for more then one recurring item

                CurrentCart = hccCart.GetById(cartId);

                hccUserProfile profile  = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                hccAddress     billAddr = null;

                var ppName =
                    hccUserProfile.GetParentProfileBy((Guid)hccCart.GetById(cartId).AspNetUserID).ParentProfileName;
                var pName = hccUserProfile.GetParentProfileBy((Guid)hccCart.GetById(cartId).AspNetUserID).ASPUser.Email;

                //if (CurrentCart.StatusID == (int)Enums.CartStatus.Unfinalized)
                if (CurrentCart.StatusID == (int)Enums.CartStatus.Unfinalized)
                {
                    if (profile != null)
                    {
                        AuthNetConfig ANConfig = new AuthNetConfig();
                        hccUserProfilePaymentProfile activePaymentProfile = profile.ActivePaymentProfile;
                        bool isDuplicateTransaction = false;
                        bool isAuthNet = false;

                        if (ANConfig.Settings.TestMode)
                        {
                            CurrentCart.IsTestOrder = true;
                        }

                        // Check for existing account balance, calculate total balance
                        if (CurrentCart.PaymentDue > 0.00m)
                        {
                            try
                            {
                                // if total balance remains
                                CustomerInformationManager cim = new CustomerInformationManager();

                                if (activePaymentProfile != null)
                                {
                                    // do not validate, per Duncan, YouTrack HC1-339
                                    //string valProfile = cim.ValidateProfile(profile.AuthNetProfileID,
                                    //    activePaymentProfile.AuthNetPaymentProfileID, AuthorizeNet.ValidationMode.TestMode);

                                    AuthorizeNet.Order order = new AuthorizeNet.Order(profile.AuthNetProfileID,
                                                                                      activePaymentProfile.AuthNetPaymentProfileID, null);

                                    // charge CIM account with PaymentDue balance
                                    order.Amount        = CurrentCart.PaymentDue;
                                    order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                    order.Description   = "Healthy Chef Creations Purchase #" +
                                                          CurrentCart.PurchaseNumber.ToString();
                                    // Add a PO number to make purchases unique as subsequent transactions with the same amount are rejected by Auth.net as duplicate
                                    // order.PONumber = "PO" + CurrentCart.PurchaseNumber.ToString();

                                    AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                    try
                                    {
                                        CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                      + "|" + rsp.AuthorizationCode + "|" +
                                                                      rsp.InvoiceNumber + "|" + rsp.Message
                                                                      + "|" + rsp.TransactionID + "|" +
                                                                      rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                    }
                                    catch (Exception)
                                    {
                                    }

                                    if (rsp.ResponseCode.StartsWith("1"))
                                    {
                                        CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.ModifiedDate     = DateTime.Now;
                                        CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.PurchaseDate     = DateTime.Now;
                                        CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                        CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                        isAuthNet = true;
                                    }
                                    else if (rsp.Message.Contains("E00027")) // Duplicate transaction
                                    {
                                        order = new AuthorizeNet.Order(profile.AuthNetProfileID,
                                                                       activePaymentProfile.AuthNetPaymentProfileID, null)
                                        {
                                            Amount = CurrentCart.PaymentDue - .01m,
                                            // Subtract a penny from payment to make the value distinct
                                            InvoiceNumber = CurrentCart.PurchaseNumber.ToString(),
                                            Description   =
                                                "Healthy Chef Creations Purchase #" +
                                                CurrentCart.PurchaseNumber.ToString()
                                        };

                                        // charge CIM account with PaymentDue balance
                                        rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" +
                                                                          rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" +
                                                                          rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" +
                                                                          rsp.Amount.ToString() + "|" + rsp.CardNumber;

                                            if (rsp.ResponseCode.StartsWith("1"))
                                            {
                                                //CurrentCart.PaymentDue = CurrentCart.PaymentDue - .01m;
                                                CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                                CurrentCart.ModifiedDate     = DateTime.Now;
                                                CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                                CurrentCart.PurchaseDate     = DateTime.Now;
                                                CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                                CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                                isAuthNet = true;
                                            }
                                            else
                                            {
                                                lblConfirmFeedback.Text += "Authorize.Net " + rsp.Message + @" (" +
                                                                           ppName + @", " + pName + @")" + @"<br />";
                                                // CurrentCart.AuthNetResponse;
                                                lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                            }
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        lblConfirmFeedback.Text += "Authorize.Net " + rsp.Message + @" (" + ppName +
                                                                   @", " + pName + @")" + @"<br />";
                                        // CurrentCart.AuthNetResponse;
                                        lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                    }
                                    CurrentCart.Save();
                                }
                                else
                                {
                                    lblConfirmFeedback.Text += "No payment profile found." + @" (" + ppName + @", " +
                                                               pName + @")" + @"<br />";
                                }
                            }
                            catch (Exception ex)
                            {
                                lblConfirmFeedback.Text += "Authorize.Net " + ex.Message + @" (" + ppName + @", " +
                                                           pName + @")" + @"<br />";
                                lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                if (ex is InvalidOperationException)
                                {
                                    if (CurrentCart.IsTestOrder)
                                    {
                                        CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.ModifiedDate     = DateTime.Now;
                                        CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                        CurrentCart.AuthNetResponse  = ex.Message;
                                        CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        lblConfirmFeedback.Visible = true;
                                        lblConfirmFeedback.Text   += "Authorize.Net " + ex.Message + @" (" + ppName +
                                                                     @", " + pName + @")" + @"<br />";
                                        lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                    }
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            // no balance left to pay on order, set as paid
                            CurrentCart.AuthNetResponse = "Paid with account balance.";
                            CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            CurrentCart.ModifiedDate    = DateTime.Now;
                            CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            CurrentCart.PurchaseDate    = DateTime.Now;
                            CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                            CurrentCart.Save();
                        }

                        if ((Enums.CartStatus)CurrentCart.StatusID == Enums.CartStatus.Paid)
                        //&& !isDuplicateTransaction
                        {
                            hccLedger ledger = new hccLedger
                            {
                                //PaymentDue = dupTransaction ? CurrentCart.PaymentDue : CurrentCart.PaymentDue - .01m,
                                //TotalAmount = dupTransaction ? CurrentCart.TotalAmount : CurrentCart.TotalAmount - .01m,
                                PaymentDue   = CurrentCart.PaymentDue,
                                TotalAmount  = CurrentCart.TotalAmount,
                                AspNetUserID = CurrentCart.AspNetUserID.Value,
                                AsscCartID   = CurrentCart.CartID,
                                CreatedBy    = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate  = DateTime.Now,
                                Description  =
                                    "Cart Order Payment - Purchase Number: " + CurrentCart.PurchaseNumber.ToString(),
                                TransactionTypeID = (int)Enums.LedgerTransactionType.Purchase
                            };

                            if (CurrentCart.IsTestOrder)
                            {
                                ledger.Description += " - Test Mode";
                            }

                            if (CurrentCart.CreditAppliedToBalance > 0)
                            {
                                profile.AccountBalance   = profile.AccountBalance - CurrentCart.CreditAppliedToBalance;
                                ledger.CreditFromBalance = CurrentCart.CreditAppliedToBalance;
                            }

                            hccLedger lastLedger =
                                hccLedger.GetByMembershipID(profile.MembershipID, null)
                                .OrderByDescending(a => a.CreatedDate)
                                .FirstOrDefault();
                            bool isDuplicateLedger = false;

                            if (lastLedger != null)
                            {
                                if (ledger.CreatedBy == lastLedger.CreatedBy &&
                                    ledger.CreditFromBalance == lastLedger.CreditFromBalance &&
                                    ledger.Description == lastLedger.Description &&
                                    ledger.PaymentDue == lastLedger.PaymentDue &&
                                    ledger.TransactionTypeID == lastLedger.TransactionTypeID &&
                                    ledger.TotalAmount == lastLedger.TotalAmount)
                                {
                                    isDuplicateLedger = true;
                                }
                            }

                            if (!isDuplicateLedger)
                            {
                                ledger.PostBalance = profile.AccountBalance;
                                ledger.Save();
                                profile.Save();

                                // create snapshot here
                                hccCartSnapshot snap = new hccCartSnapshot
                                {
                                    CartId                  = cartId,
                                    MembershipId            = profile.MembershipID,
                                    LedgerId                = ledger.LedgerID,
                                    AccountBalance          = profile.AccountBalance,
                                    AuthNetProfileId        = profile.AuthNetProfileID,
                                    CreatedBy               = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                    CreatedDate             = DateTime.Now,
                                    DefaultCouponId         = profile.DefaultCouponId,
                                    Email                   = profile.ASPUser.Email,
                                    FirstName               = profile.FirstName,
                                    LastName                = profile.LastName,
                                    ProfileName             = profile.ProfileName,
                                    AuthNetPaymentProfileId =
                                        (isAuthNet == true ? activePaymentProfile.AuthNetPaymentProfileID : string.Empty),
                                    CardTypeId = (isAuthNet == true ? activePaymentProfile.CardTypeID : 0),
                                    CCLast4    = (isAuthNet == true ? activePaymentProfile.CCLast4 : string.Empty),
                                    ExpMon     = (isAuthNet == true ? activePaymentProfile.ExpMon : 0),
                                    ExpYear    = (isAuthNet == true ? activePaymentProfile.ExpYear : 0),
                                    NameOnCard = (isAuthNet == true ? activePaymentProfile.NameOnCard : string.Empty)
                                };
                                snap.Save();

                                hccUserProfile parentProfile =
                                    hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                if (parentProfile.BillingAddressID.HasValue)
                                {
                                    billAddr = hccAddress.GetById(parentProfile.BillingAddressID.Value);
                                }

                                hccAddress snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = parentProfile.ProfileName
                                };
                                snapBillAddr.Save();

                                // copy and replace of all addresses for snapshot
                                List <hccCartItem> cartItems = hccCartItem.GetBy(CurrentCart.CartID);

                                cartItems.ToList().ForEach(delegate(hccCartItem ci)
                                {
                                    hccAddress shipAddr = null;
                                    if (ci.UserProfile.ShippingAddressID.HasValue)
                                    {
                                        shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                    }

                                    if (shipAddr != null)
                                    {
                                        hccAddress snapShipAddr = new hccAddress
                                        {
                                            Address1              = shipAddr.Address1,
                                            Address2              = shipAddr.Address2,
                                            AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                            City                  = shipAddr.City,
                                            Country               = shipAddr.Country,
                                            DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                            FirstName             = shipAddr.FirstName,
                                            IsBusiness            = shipAddr.IsBusiness,
                                            LastName              = shipAddr.LastName,
                                            Phone                 = shipAddr.Phone,
                                            PostalCode            = shipAddr.PostalCode,
                                            State                 = shipAddr.State,
                                            ProfileName           = ci.UserProfile.ProfileName
                                        };
                                        snapShipAddr.Save();
                                        ci.SnapShipAddrId = snapShipAddr.AddressID;
                                    }

                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                    ci.Save();
                                });


                                try
                                {
                                    Email.EmailController ec = new Email.EmailController();
                                    ec.SendMail_OrderConfirmationMerchant(profile.FirstName + " " + profile.LastName,
                                                                          CurrentCart.ToHtml(), cartId);
                                    ec.SendMail_OrderConfirmationCustomer(profile.ASPUser.Email,
                                                                          profile.FirstName + " " + profile.LastName, CurrentCart.ToHtml());
                                }
                                catch (Exception ex)
                                {
                                    BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Mail Failed", this, ex);
                                } //throw; }

                                //if (IsForPublic)
                                //{
                                //    Response.Redirect(string.Format("~/cart/order-confirmation.aspx?pn={0}&tl={1}&tx={2}&ts={3}&ct={4}&st={5}&cy={6}",
                                //        CurrentCart.PurchaseNumber, CurrentCart.TotalAmount, CurrentCart.TaxableAmount, CurrentCart.ShippingAmount,
                                //        billAddr.City, billAddr.State, billAddr.Country), false);
                                //}
                                //else
                                //{
                                //    CurrentCart = hccCart.GetCurrentCart(profile.ASPUser);
                                //    CurrentCartId = CurrentCart.CartID;

                                //    pnlCartDisplay.Visible = true;
                                //    pnlConfirm.Visible = false;

                                //    Clear();
                                //    Bind();
                                //}
                                //OnCartSaved(new CartEventArgs(CurrentCartId));
                            }
                        }
                        //else
                        //{
                        //    BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Duplicate transaction attempted: " + CurrentCart.PurchaseNumber.ToString(), this, new Exception("Duplicate transaction attempted by:" + Helpers.LoggedUser.UserName));
                        //}
                    }
                    else
                    {
                        Response.Redirect("~/login.aspx", true);
                    }
                }
                //else
                //{
                //if (IsForPublic)
                //{
                //    //Response.Redirect("~/cart/order-confirmation.aspx?cid=" + CurrentCartId.ToString(), false);
                //    Response.Redirect(string.Format("~/cart/order-confirmation.aspx?pn={0}&tl={1}&tx={2}&ts={3}&ct={4}&st={5}&cy={6}",
                //                    CurrentCart.PurchaseNumber, CurrentCart.TotalAmount, CurrentCart.TaxableAmount, CurrentCart.ShippingAmount,
                //                    billAddr.City, billAddr.State, billAddr.Country), false);
                //}
                //else
                //{
                //    CurrentCart = hccCart.GetCurrentCart(profile.ASPUser);
                //    CurrentCartId = CurrentCart.CartID;

                //    pnlCartDisplay.Visible = true;
                //    pnlConfirm.Visible = false;

                //    Clear();
                //    Bind();

                //    OnCartSaved(new CartEventArgs(CurrentCartId));
                //}
                //}
            }
            catch (Exception ex)
            {
                BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Data + " " + ex.InnerException, this,
                                                                        new Exception("Recurring order error in method ProcessNewOrder: " + Helpers.LoggedUser.UserName));
            }
        }
Example #5
0
        protected override void SaveForm()
        {
            hccUserProfile userProfile = hccUserProfile.GetById(CurrentUserProfileID);
            Address        billAddr    = null;

            if (userProfile != null)
            {
                //Save CardInfo
                if (pnlCardInfo.Visible)
                {
                    CurrentCardInfo.NameOnCard   = txtNameOnCard.Text.Trim();
                    CurrentCardInfo.CardNumber   = txtCCNumber.Text.Trim();
                    CurrentCardInfo.CardType     = ValidateCardNumber(txtCCNumber.Text.Trim());
                    CurrentCardInfo.ExpMonth     = int.Parse(ddlExpMonth.SelectedValue);
                    CurrentCardInfo.ExpYear      = int.Parse(ddlExpYear.SelectedValue);
                    CurrentCardInfo.SecurityCode = txtCCAuthCode.Text.Trim();
                }

                if (userProfile.BillingAddressID.HasValue)
                {
                    billAddr = hccAddress.GetById(userProfile.BillingAddressID.Value).ToAuthNetAddress();
                }

                if (CurrentCardInfo.HasValues && billAddr != null)
                {
                    try
                    {
                        //send card to Auth.net for Auth.net profile
                        CustomerInformationManager cim = new CustomerInformationManager();
                        Customer cust         = null;
                        string   autnetResult = string.Empty;

                        if (!string.IsNullOrWhiteSpace(userProfile.AuthNetProfileID))
                        {
                            cust = cim.GetCustomer(userProfile.AuthNetProfileID);
                        }

                        //Will Martinez - Commented out on 7/30/2013.
                        //This code scans all existing Profiles generated to check for duplicated email addresses, however the site registration prevents that
                        //commented out since this process had a significant performance effect on the site.
                        //if (cust == null)
                        //    cust = cim.GetCustomerByEmail(userProfile.ASPUser.Email);

                        if (cust == null)
                        {
                            cust = cim.CreateCustomer(userProfile.ASPUser.Email, userProfile.ASPUser.UserName);
                        }

                        // had to add it back in, unable to create records with duplicate email addresses caused by IT desynching data.
                        // this should only be called infrequently since we try to create the account first.
                        if (cust.ProfileID == null)
                        {
                            cust = cim.GetCustomerByEmail(userProfile.ASPUser.Email, out autnetResult);
                        }
                        if (cust != null)
                        {
                            if (userProfile.AuthNetProfileID != cust.ProfileID)
                            {
                                userProfile.AuthNetProfileID = cust.ProfileID;
                                userProfile.Save();
                            }

                            List <PaymentProfile> payProfiles = cust.PaymentProfiles.ToList();

                            if (payProfiles.Count > 0)
                            {
                                payProfiles.ForEach(a => cim.DeletePaymentProfile(userProfile.AuthNetProfileID, a.ProfileID));
                            }

                            // create new payment profile
                            autnetResult = cim.AddCreditCard(cust, CurrentCardInfo.CardNumber, CurrentCardInfo.ExpMonth,
                                                             CurrentCardInfo.ExpYear, CurrentCardInfo.SecurityCode, billAddr);

                            if (!string.IsNullOrWhiteSpace(autnetResult))
                            {
                                // Validate card profile
                                validateCustomerPaymentProfileResponse valProfile = cim.ValidateProfile(userProfile.AuthNetProfileID,
                                                                                                        autnetResult, AuthorizeNet.ValidationMode.TestMode);

                                if (valProfile.messages.resultCode == messageTypeEnum.Ok)
                                {
                                    hccUserProfilePaymentProfile activePaymentProfile = null;
                                    activePaymentProfile = userProfile.ActivePaymentProfile;

                                    if (userProfile.ActivePaymentProfile == null)
                                    {
                                        activePaymentProfile = new hccUserProfilePaymentProfile();
                                    }

                                    activePaymentProfile.CardTypeID    = (int)CurrentCardInfo.CardType;
                                    activePaymentProfile.CCLast4       = CurrentCardInfo.CardNumber.Substring(CurrentCardInfo.CardNumber.Length - 4, 4);
                                    activePaymentProfile.ExpMon        = CurrentCardInfo.ExpMonth;
                                    activePaymentProfile.ExpYear       = CurrentCardInfo.ExpYear;
                                    activePaymentProfile.NameOnCard    = CurrentCardInfo.NameOnCard;
                                    activePaymentProfile.UserProfileID = userProfile.UserProfileID;
                                    activePaymentProfile.IsActive      = true;

                                    activePaymentProfile.AuthNetPaymentProfileID = autnetResult;
                                    activePaymentProfile.Save();
                                    this.PrimaryKeyIndex = activePaymentProfile.PaymentProfileID;

                                    OnSaved(new ControlSavedEventArgs(this.PrimaryKeyIndex));
                                    lblFeedback.Text = "Payment Profile has been created and validated.";
                                }
                                else
                                {
                                    lblFeedback.Text = "Payment Profile has been created, but validation failed.";
                                }
                            }
                            else
                            {
                                lblFeedback.Text = "Authorize.Net response is empty.";
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(autnetResult))
                            {
                                lblErrorOnAuth.Text = autnetResult;
                            }
                            OnCardInfoSaveFailed(new CardInfoSaveFailedEventArgs(new Exception(autnetResult)));
                        }
                    }
                    catch { throw; }
                }
            }
        }