public decimal GetProfileTaxRate(hccAddress shippAddress)
        {
            var taxRate = 0.00m;

            // if shipping address is FL, add tax for taxable items
            if (shippAddress != null && shippAddress.State == "FL")
            {
                TaxLookup taxInfo = TaxLookup.RequestTax(shippAddress.PostalCode);
                if (!taxInfo.State.Contains("Error"))
                {
                    taxRate = decimal.Parse(taxInfo.Sales_Tax_Rate);
                    return(taxRate);
                }
                return(taxRate);
            }
            return(taxRate);
        }
Пример #2
0
 public hccAddress GetCloningAddress()
 {
     try
     {
         hccAddress cloneAddress = new hccAddress
         {
             Address1              = txtAddress1.Text.Trim(),
             Address2              = txtAddress2.Text.Trim(),
             City                  = txtCity.Text.Trim(),
             FirstName             = txtFirstName.Text.Trim(),
             LastName              = txtLastName.Text.Trim(),
             Phone                 = txtPhone.Text.Trim(),
             PostalCode            = txtZipCode.Text.Trim(),
             State                 = ddlUSStates.SelectedItem.Value,
             DefaultShippingTypeID = int.Parse(ddlDeliveryTypes.SelectedValue)
         };
         return(cloneAddress);
     }
     catch { return(null); }
 }
        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;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["pn"] != null && !string.IsNullOrWhiteSpace(Request.QueryString["pn"].ToString()))
                {
                    int purchaseNum;
                    if (int.TryParse(Request.QueryString["pn"], out purchaseNum))
                    {
                        CurrentCart = hccCart.GetBy(purchaseNum);
                    }
                }

                if (CurrentCart != null && Helpers.LoggedUser != null &&
                    (CurrentCart.AspNetUserID == (Guid)Helpers.LoggedUser.ProviderUserKey ||
                     Roles.IsUserInRole(Helpers.LoggedUser.UserName, "Administrators")))
                {
                    lblCompleteDetail.Text = CurrentCart.ToHtml();

                    if (CurrentCart.OwnerProfile != null && CurrentCart.OwnerProfile.ASPUser != null)
                    {
                        lblCompleteEmail.Text = CurrentCart.OwnerProfile.ASPUser.Email;
                    }

                    //hdnPurchaseNum.Value = this.PurchaseNumber.ToString();
                    //hdnTotal.Value = this.TotalAmount.ToString("f2");
                    //hdnTax.Value = this.TaxAmount.ToString("f2");
                    //hdnShipping.Value = this.ShippingAmount.ToString("f2");

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

                        if (billAddr != null)
                        {
                            CurrentCity    = billAddr.City;
                            CurrentState   = billAddr.State;
                            CurrentCountry = billAddr.Country;
                            //CurrentUserName = billAddr.FirstName;
                            //CurrentUserEmail = billProf.aspnet_Membership.Email;
                        }
                        else
                        {
                            CurrentCity    = string.Empty;
                            CurrentState   = string.Empty;
                            CurrentCountry = string.Empty;
                            //CurrentUserName = string.Empty;
                            //CurrentUserEmail = string.Empty;
                        }
                    }
                    else
                    {
                        CurrentCity    = string.Empty;
                        CurrentState   = string.Empty;
                        CurrentCountry = string.Empty;
                        //CurrentUserName = string.Empty;
                        //CurrentUserEmail = string.Empty;
                    }
                    //string TrackAmount = "'" + CurrentCart.TotalAmount.ToString("f2") + "'";
                    //Session["trackAmount"] = TrackAmount;
                    //track_id.Attributes["src"] = ResolveUrl("https://shareasale.com/sale.cfm?amount=TrackAmount&[email protected]&transtype=lead&merchantID=11");

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("var _gaq = _gaq || [];");
                    sb.AppendLine("_gaq.push(['_setAccount', 'UA-32947650-1']);");
                    sb.AppendLine("_gaq.push(['_trackPageview']);");
                    sb.AppendLine("_gaq.push(['_addTrans',");
                    sb.AppendLine("'" + CurrentCart.PurchaseNumber.ToString() + "',           // transaction ID - required");
                    sb.AppendLine("'Healthy Chef Creations',  // affiliation or store name");
                    sb.AppendLine("'" + CurrentCart.TotalAmount.ToString("f2") + "',          // total - required");
                    sb.AppendLine("'" + CurrentCart.TaxAmount.ToString("f2") + "',           // tax");
                    sb.AppendLine("'" + CurrentCart.ShippingAmount.ToString("f2") + "',              // shipping");
                    sb.AppendLine("'" + CurrentCity + "',       // city");
                    sb.AppendLine("'" + CurrentState + "',     // state or province");
                    sb.AppendLine("'" + CurrentCountry + "'             // country");
                    //sb.AppendLine("'" + CurrentUserName + "'    User Name//");
                    //sb.AppendLine("'" + CurrentUserEmail + "'    User Email//");
                    sb.AppendLine("]);");
                    sb.AppendLine("_gaq.push(['_trackTrans']); //submits transaction to the Analytics servers");
                    sb.AppendLine("(function() {");
                    sb.AppendLine("var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;");
                    sb.AppendLine("ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';");
                    sb.AppendLine("var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);");
                    sb.AppendLine("})();");

                    if (!ClientScript.IsStartupScriptRegistered("GoogleTrack"))
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "GoogleTrack", sb.ToString(), true);
                    }
                    Response.Redirect(string.Format("~/thankyou.aspx?pn={0}&tl={1}&tx={2}&ts={3}&ct={4}&st={5}&cy={6}",
                                                    CurrentCart.PurchaseNumber, CurrentCart.TotalAmount, CurrentCart.TaxableAmount, CurrentCart.ShippingAmount,
                                                    hccAddress.GetById(CurrentCart.OwnerProfile.BillingAddressID.Value).City,
                                                    hccAddress.GetById(CurrentCart.OwnerProfile.BillingAddressID.Value).State,
                                                    hccAddress.GetById(CurrentCart.OwnerProfile.BillingAddressID.Value).Country), true);
                }
                else
                {
                    pnlComplete.Visible = false;
                    lblFeedback.Text    = "You are not authorized to view this information.";
                }

                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    aLogin.Visible   = false;
                    aProfile.Visible = true;
                    aSignOut.Visible = true;
                }
                else
                {
                    aCart.Visible    = true;
                    aLogin.Visible   = true;
                    aProfile.Visible = false;
                    aSignOut.Visible = false;
                }


                SetCartCount();
            }
        }
        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));
            }
        }
Пример #6
0
        protected override void SaveForm()
        {
            try
            {
                if (hdnAddId.Value == null || hdnAddId.Value == "")
                {
                    hdnAddId.Value = "0";
                }

                int AddressId = Convert.ToInt32(hdnAddId.Value);

                hccAddress address;

                if (CurrentAddress == null)
                {
                    address = new hccAddress {
                        Country = "US", AddressTypeID = (int)this.AddressType
                    }
                }
                ;
                else
                {
                    address = CurrentAddress;
                }
                int addrId = address.AddressID;
                address.FirstName  = txtFirstName.Text.Trim();
                address.LastName   = txtLastName.Text.Trim();
                address.Address1   = txtAddress1.Text.Trim();
                address.Address2   = txtAddress2.Text.Trim();
                address.City       = txtCity.Text.Trim();
                address.State      = ddlUSStates.SelectedValue;
                address.PostalCode = txtZipCode.Text.Trim();
                address.Phone      = txtPhone.Text.Trim();

                if (ShowIsBusiness)
                {
                    address.IsBusiness = chkIsBusiness.Checked;
                }
                else
                {
                    address.IsBusiness = false;
                }

                if (ddlDeliveryTypes.Items.Count > 0)
                {
                    address.DefaultShippingTypeID = int.Parse(ddlDeliveryTypes.SelectedItem.Value);
                }

                if (ddlDeliveryTypes.SelectedItem.Value == "2")
                {
                    string          ZipCode   = txtZipCode.Text;
                    hccShippingZone hccshopin = new hccShippingZone();
                    DataSet         ds        = hccshopin.BindZoneByZipCodeNew(ZipCode);
                    int             ZoneId    = Convert.ToInt32(ds.Tables[0].Rows[0]["ZoneID"].ToString());
                    DataTable       ds1       = hccshopin.BindGridShippingZoneByZoneID(ZoneId);
                    string          IsPickup  = ds1.Rows[0]["IsPickupShippingZone"].ToString();

                    if (IsPickup == "True")
                    {
                        address.Save();

                        lblFeedback0.Text = ValidationMessagePrefix + " information saved: " + DateTime.Now.ToString("MM/dd/yyyy h:mm:ss");

                        lblFeedback0.ForeColor = System.Drawing.Color.Green;

                        this.PrimaryKeyIndex = address.AddressID;

                        OnSaved(new Common.Events.ControlSavedEventArgs(this.PrimaryKeyIndex));
                    }
                    else
                    {
                        address.Save();
                        lblFeedback0.Text = "Customer pickup is not available at this Zip Code";

                        lblFeedback0.ForeColor = System.Drawing.Color.Red;

                        this.PrimaryKeyIndex = address.AddressID;
                        OnSaved(new Common.Events.ControlSavedEventArgs(this.PrimaryKeyIndex));
                    }
                }
                else
                {
                    address.Save();

                    lblFeedback0.Text = ValidationMessagePrefix + " information saved: " + DateTime.Now.ToString("MM/dd/yyyy h:mm:ss");

                    lblFeedback0.ForeColor = System.Drawing.Color.Green;

                    this.PrimaryKeyIndex = address.AddressID;

                    OnSaved(new Common.Events.ControlSavedEventArgs(this.PrimaryKeyIndex));
                }
            }
            catch
            { throw; }
        }