public ActionResult ShippingMethod()
        {
            var customer        = HttpContext.GetCustomer();
            var storeId         = AppLogic.StoreID();
            var cart            = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, storeId);
            var shippingAddress = EffectiveShippingAddressProvider.GetEffectiveShippingAddress(customer);
            var checkoutContext = PersistedCheckoutContextProvider.LoadCheckoutContext(customer);

            var shippingMethodModels = CachedShippingMethodCollectionProvider
                                       .Get(customer, shippingAddress, cart.CartItems, storeId)
                                       .Select(shippingMethod => new ShippingMethodRenderModel(
                                                   id: shippingMethod.Id,
                                                   name: shippingMethod.GetNameForDisplay(),
                                                   rateDisplay: GetShippingMethodRateDisplay(shippingMethod, customer, cart),
                                                   imageFileName: shippingMethod.ImageFileName));

            var selectedShippingMethodModel = shippingMethodModels
                                              .Where(shippingMethod => shippingMethod.Id == checkoutContext.SelectedShippingMethodId)
                                              .FirstOrDefault();

            var model = new SelectShippingMethodViewModel
            {
                RenderModel = new SelectShippingMethodRenderModel(
                    shippingMethods: shippingMethodModels,
                    selectedShippingMethod: selectedShippingMethodModel,
                    showShippingIcons: AppConfigProvider.GetAppConfigValue <bool>("ShowShippingIcons"),
                    cartIsAllFreeShipping: !AppConfigProvider.GetAppConfigValue <bool>("FreeShippingAllowsRateSelection") && cart.IsAllFreeShippingComponents(),
                    numberOfMethodsToShow: AppConfigProvider.GetAppConfigValue <int>("NumberOfShippingMethodsToDisplay"),
                    hideShippingOptions: AppConfigProvider.GetAppConfigValue <bool>("shipping.hide.options")),
                SelectedShippingMethodId = checkoutContext.SelectedShippingMethodId,
            };

            return(PartialView(ViewNames.ShippingMethodPartial, model));
        }
        public ActionResult CheckoutCart()
        {
            var customer      = HttpContext.GetCustomer();
            var cart          = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var cartViewModel = GetShoppingCartViewModel(cart, customer);

            return(PartialView(ViewNames.CheckoutCartPartial, cartViewModel));
        }
        public ActionResult AddGiftCard()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var model = new GiftCardViewModel
            {
                Code = cart.Coupon.CouponCode
            };

            return(PartialView(ViewNames.AddGiftCardPartial, model));
        }
        public CartContext Apply(PreCheckoutRuleContext context)
        {
            var shippingAddress = EffectiveShippingAddressProvider.GetEffectiveShippingAddress(context.Customer);

            var availableShippingMethods = CachedShippingMethodCollectionProvider
                                           .Get(context.Customer, shippingAddress, context.CartContext.Cart.CartItems, AppLogic.StoreID());

            // If there are no available shipping methods, the customer hasn't selected one, or the customer selected an invalid one, selectedShipping will be null.
            var selectedShippingMethod = availableShippingMethods
                                         .Where(shippingMethod => shippingMethod.Id == context.PersistedCheckoutContext.SelectedShippingMethodId)
                                         .FirstOrDefault();

            // No matter what shipping method was selected but the customer, if there is only one available shipping method, set the customers selection to it.
            if (availableShippingMethods.Count() == 1)
            {
                selectedShippingMethod = availableShippingMethods.First();
            }

            // Update all cart items to the updated selection. If the selection is null, then it clears the selection from the cart items and the customer has to select a new one.
            ShippingMethodCartItemApplicator.UpdateCartItemsShippingMethod(
                context.Customer,
                context.CartContext.Cart,
                selectedShippingMethod);

            return(new CartContext(
                       cartContext: context.CartContext,
                       cart: CachedShoppingCartProvider.Get(context.Customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
        public ActionResult OrderOption()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var options = cart
                          .AllOrderOptions
                          .Select(option => new OrderOptionItemViewModel
            {
                OrderOptionGuid = option.UniqueID,
                Id          = option.ID,
                Name        = option.Name,
                Description = option.Description,
                Cost        = Localization.CurrencyStringForDisplayWithExchangeRate(option.Cost, customer.CurrencySetting),
                Checked     = cart.OrderOptions.Select(orderOption => orderOption.ID).Contains(option.ID),
                TaxClassId  = option.TaxClassID,
                ImageUrl    = option.ImageUrl,
                HasImage    = !string.IsNullOrEmpty(option.ImageUrl) && !option.ImageUrl.Contains("nopictureicon")
            });

            var model = new OrderOptionViewModel
            {
                Options = options
            };

            return(PartialView(ViewNames.OrderOptionPartial, model));
        }
        public CartContext Apply(PreCheckoutRuleContext preCheckoutRuleContext)
        {
            var customerId = preCheckoutRuleContext
                             .Customer
                             .CustomerID;

            var shippingAddressId = preCheckoutRuleContext.Customer.PrimaryShippingAddressID;

            DB.ExecuteSQL(@"
				update
					dbo.ShoppingCart
				set
					ShippingAddressId = @shippingAddressId
				where
					CustomerId = @CustomerId
					and CartType in (0,1)
					and StoreId = @StoreId
					AND ShippingAddressid <> @shippingAddressId"                    ,

                          new SqlParameter("@StoreId", AppLogic.StoreID()),
                          new SqlParameter("@CustomerId", customerId),
                          new SqlParameter("@ShippingAddressId", shippingAddressId));

            return(new CartContext(
                       cartContext: preCheckoutRuleContext.CartContext,
                       cart: CachedShoppingCartProvider.Get(preCheckoutRuleContext.Customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
Beispiel #7
0
        public ActionResult PaymentMethod(bool?paymentMethodComplete)
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var paymentOptions = PaymentOptionProvider.GetPaymentOptions(customer, cart)
                                 .Where(paymentOption => paymentOption.Available);

            var selectedPaymentMethod = PaymentOptionProvider.GetCustomerSelectedPaymentOption(paymentOptions, customer);

            var onSitePaymentOptions = paymentOptions
                                       .Where(paymentOption => !paymentOption.IsOffsiteForDisplay)
                                       .OrderBy(paymentOption => paymentOption.DisplayOrder);

            var model = new PaymentMethodRenderModel(
                onSitePaymentOptions: onSitePaymentOptions,
                selectedPaymentMethod: selectedPaymentMethod != null
                                        ? selectedPaymentMethod.Info.Name
                                        : null,
                selectedPaymentMethodDisplayName: selectedPaymentMethod != null
                                        ? selectedPaymentMethod.Info.DisplayName
                                        : null,
                paymentMethodComplete: paymentMethodComplete ?? false,
                editUrl: selectedPaymentMethod != null
                                        ? selectedPaymentMethod.IsEditable
                                                ? selectedPaymentMethod.EditUrl
                                                : null
                                        : null);

            return(PartialView(ViewNames.PaymentMethodPartial, model));
        }
        public CartContext Apply(PreCheckoutRuleContext preCheckoutRuleContext)
        {
            var persistedCheckout = preCheckoutRuleContext
                                    .PersistedCheckoutContext;

            var customer = preCheckoutRuleContext
                           .Customer;

            // If an offsite payment method has flagged billing or shipping as required, any changes by the customer will be reverted.
            if (persistedCheckout.OffsiteRequiredBillingAddressId.HasValue &&
                customer.PrimaryBillingAddressID != persistedCheckout.OffsiteRequiredBillingAddressId)
            {
                customer.UpdateCustomer(
                    billingAddressId: persistedCheckout.OffsiteRequiredBillingAddressId.Value);
                NoticeProvider.PushNotice(AppLogic.GetString("checkout.offsites.billing.reverted"), NoticeType.Warning);
            }

            if (persistedCheckout.OffsiteRequiredShippingAddressId.HasValue &&
                customer.PrimaryShippingAddressID != persistedCheckout.OffsiteRequiredShippingAddressId)
            {
                customer.UpdateCustomer(
                    shippingAddressId: persistedCheckout.OffsiteRequiredShippingAddressId.Value);
                NoticeProvider.PushNotice(AppLogic.GetString("checkout.offsites.shipping.reverted"), NoticeType.Warning);
            }

            return(new CartContext(
                       cartContext: preCheckoutRuleContext.CartContext,
                       cart: CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
Beispiel #9
0
        AvaTaxRate ObjectBuilder(AvaTaxRateCacheContext objectContext)
        {
            var cart = CachedShoppingCartProvider.Get(objectContext.Customer, CartTypeEnum.ShoppingCart, objectContext.StoreId);

            var taxRate = new AvaTax().GetTaxRate(objectContext.Customer, cart.CartItems, cart.OrderOptions);

            return(new AvaTaxRate(objectContext.Customer, objectContext.StoreId, objectContext.CartType, taxRate));
        }
Beispiel #10
0
        public ActionResult BraintreeThreeDSecurePass(string nonce)
        {
            var customer    = HttpContext.GetCustomer();
            var context     = PersistedCheckoutContextProvider.LoadCheckoutContext(customer);
            var cart        = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var orderNumber = customer.ThisCustomerSession.SessionUSInt("3Dsecure.OrderNumber");

            var updatedCheckoutContext = new PersistedCheckoutContext(
                creditCard: context.CreditCard,
                payPalExpress: context.PayPalExpress,
                purchaseOrder: context.PurchaseOrder,
                braintree: new BraintreeDetails(
                    nonce: nonce,                       //We got a new nonce after the 3dSecure request
                    token: context.Braintree.Token,
                    paymentMethod: context.Braintree.PaymentMethod,
                    threeDSecureApproved: true),
                amazonPayments: context.AmazonPayments,
                termsAndConditionsAccepted: context.TermsAndConditionsAccepted,
                over13Checked: context.Over13Checked,
                shippingEstimateDetails: context.ShippingEstimateDetails,
                offsiteRequiresBillingAddressId: null,
                offsiteRequiresShippingAddressId: null,
                email: context.Email,
                selectedShippingMethodId: context.SelectedShippingMethodId);

            PersistedCheckoutContextProvider.SaveCheckoutContext(customer, updatedCheckoutContext);

            customer.ThisCustomerSession[AppLogic.Braintree3dSecureKey]   = "true";
            customer.ThisCustomerSession[AppLogic.BraintreeNonceKey]      = nonce;
            customer.ThisCustomerSession[AppLogic.BraintreePaymentMethod] = context.Braintree.PaymentMethod;

            var status = Gateway.MakeOrder(string.Empty, AppLogic.TransactionMode(), cart, orderNumber, string.Empty, string.Empty, string.Empty, string.Empty);

            ClearThreeDSecureSessionInfo(customer);

            if (status == AppLogic.ro_OK)
            {
                return(RedirectToAction(
                           ActionNames.Confirmation,
                           ControllerNames.CheckoutConfirmation,
                           new { @orderNumber = orderNumber }));
            }

            NoticeProvider.PushNotice(string.Format("Unknown Result. Message={0}. Please retry your credit card.", status), NoticeType.Failure);
            return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
        }
Beispiel #11
0
        public ActionResult AddPromoCode()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var promotions = !cart.PromotionsEnabled
                                ? Enumerable.Empty <PromotionViewModel>()
                                : cart
                             .DiscountResults
                             .Where(discountResult => discountResult != null)
                             .Select(discountResult => new PromotionViewModel(
                                         code: discountResult.Promotion.Code,
                                         description: discountResult.Promotion.Description));

            var model = new PromotionsViewModel(
                enteredPromoCode: string.Empty,
                promotions: promotions);

            return(PartialView(ViewNames.AddPromoCodePartial, model));
        }
Beispiel #12
0
        public ActionResult TwoCheckout()
        {
            var customer  = HttpContext.GetCustomer();
            var cart      = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var returnUrl = Url.Action(ActionNames.TwoCheckoutReturn, ControllerNames.TwoCheckout, null, this.Request.Url.Scheme);

            var model = new TwoCheckoutViewModel
            {
                LiveServerUrl       = AppLogic.AppConfig("2CHECKOUT_Live_Server"),
                ReturnUrl           = returnUrl,
                Login               = AppLogic.AppConfig("2CHECKOUT_VendorID"),
                Total               = Localization.CurrencyStringForGatewayWithoutExchangeRate(cart.Total(true)),
                InvoiceNumber       = CommonLogic.GetNewGUID(),
                Email               = customer.EMail,
                BillingAddress      = customer.PrimaryBillingAddress,
                UseLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions")
            };

            return(View(model));
        }
        public ActionResult GiftCardSetup()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var model = new EmailGiftCardsViewModel
            {
                EmailGiftCardsInCart = LoadEmailGiftCardsFromCart(customer, cart)
            };

            return(View(model));
        }
        public ActionResult OrderNotes()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var model = new OrderNotesViewModel
            {
                OrderNotes = cart.OrderNotes
            };

            return(PartialView(ViewNames.OrderNotesPartial, model));
        }
        public ActionResult BraintreeThreeDSecurePass(string nonce)
        {
            var customer        = HttpContext.GetCustomer();
            var checkoutContext = PersistedCheckoutContextProvider.LoadCheckoutContext(customer);
            var cart            = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var orderNumber     = customer.ThisCustomerSession.SessionUSInt("3Dsecure.OrderNumber");

            var updatedCheckoutContext = new PersistedCheckoutContextBuilder()
                                         .From(checkoutContext)
                                         .WithBraintree(new BraintreeDetails(
                                                            nonce: nonce, //We got a new nonce after the 3dSecure request
                                                            token: checkoutContext.Braintree.Token,
                                                            paymentMethod: checkoutContext.Braintree.PaymentMethod,
                                                            threeDSecureApproved: true))
                                         .WithoutOffsiteRequiredBillingAddressId()
                                         .WithoutOffsiteRequiredShippingAddressId()
                                         .Build();

            PersistedCheckoutContextProvider.SaveCheckoutContext(customer, updatedCheckoutContext);

            customer.ThisCustomerSession[AppLogic.Braintree3dSecureKey]   = "true";
            customer.ThisCustomerSession[AppLogic.BraintreeNonceKey]      = nonce;
            customer.ThisCustomerSession[AppLogic.BraintreePaymentMethod] = checkoutContext.Braintree.PaymentMethod;

            var status = Gateway.MakeOrder(string.Empty, AppLogic.TransactionMode(), cart, orderNumber, string.Empty, string.Empty, string.Empty, string.Empty);

            ClearThreeDSecureSessionInfo(customer);

            if (status == AppLogic.ro_OK)
            {
                return(RedirectToAction(
                           ActionNames.Confirmation,
                           ControllerNames.CheckoutConfirmation,
                           new { orderNumber = orderNumber }));
            }

            NoticeProvider.PushNotice(string.Format(StringResourceProvider.GetString("secureprocess.aspx.5"), status), NoticeType.Failure);
            return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
        }
Beispiel #16
0
        public CartContext Apply(PreCheckoutRuleContext preCheckoutRuleContext)
        {
            // Age the cart
            var ageCartDays = preCheckoutRuleContext.CheckoutConfiguration.AgeCartDays == 0
                                ? 7
                                : preCheckoutRuleContext.CheckoutConfiguration.AgeCartDays;

            CartActionProvider.RemoveItemsBeyondMaxAge(preCheckoutRuleContext.Customer, preCheckoutRuleContext.CartContext.Cart.CartType, ageCartDays);
            CartActionProvider.ClearDeletedAndUnPublishedProducts(preCheckoutRuleContext.Customer);

            return(new CartContext(
                       cartContext: preCheckoutRuleContext.CartContext,
                       cart: CachedShoppingCartProvider.Get(preCheckoutRuleContext.Customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
Beispiel #17
0
        public ActionResult Index()
        {
            var customer = HttpContext.GetCustomer();

            return(PartialView(ViewNames.UserLinksPartial, new UserLinksViewModel {
                UserIsRegistered = customer.IsRegistered,
                UserFirstName = customer.FirstName,
                Email = customer.EMail,
                UserLastName = customer.LastName,
                MinicartEnabled = AppLogic.AppConfigBool("Minicart.Enabled"),
                MiniwishlistEnabled = AppLogic.AppConfigBool("ShowWishButtons"),
                CheckoutInProgress = AppLogic.GetCurrentPageType() == PageTypes.Checkout,
                CartHasItems = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())
                               .CartItems
                               .Any()
            }));
        }
        public CartContext Apply(PreCheckoutRuleContext preCheckoutRuleContext)
        {
            var customer = preCheckoutRuleContext
                           .Customer;

            // Ensure the payment method on the billing address matches the selected payment method
            if (customer.PrimaryBillingAddressID != 0 &&
                customer.PrimaryBillingAddress.PaymentMethodLastUsed != customer.RequestedPaymentMethod)
            {
                customer.PrimaryBillingAddress.PaymentMethodLastUsed = customer.RequestedPaymentMethod;
                customer.PrimaryBillingAddress.UpdateDB();
            }

            return(new CartContext(
                       cartContext: preCheckoutRuleContext.CartContext,
                       cart: CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
        public CartContext Apply(PreCheckoutRuleContext preCheckoutRuleContext)
        {
            InventoryTrimmedReason inventoryTrimmedReason =
                CartActionProvider
                .ValidateCartQuantitiesAgainstInventory(preCheckoutRuleContext.Customer, preCheckoutRuleContext.CartContext.Cart.CartType);

            //Display inventory adjustment notice if necessary
            var cartTrimmedMessage = preCheckoutRuleContext.CartContext.Cart.GetInventoryTrimmedUserMessage(inventoryTrimmedReason);

            if (!string.IsNullOrEmpty(cartTrimmedMessage))
            {
                NoticeProvider.PushNotice(cartTrimmedMessage, NoticeType.Info);
            }

            return(new CartContext(
                       cartContext: preCheckoutRuleContext.CartContext,
                       cart: CachedShoppingCartProvider.Get(preCheckoutRuleContext.Customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())));
        }
Beispiel #20
0
        public ActionResult ShoppingCartUpsells(UpsellProductsViewModel model)
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            foreach (var upsellItem in model.UpsellProducts.Where(item => item.Selected))
            {
                if (upsellItem.ProductId == 0)
                {
                    continue;
                }

                var variantId = AppLogic.GetProductsDefaultVariantID(upsellItem.ProductId);
                if (variantId == 0)
                {
                    continue;
                }

                var newCartRecord = cart.AddItem(
                    customer: customer,
                    shippingAddressId: customer.PrimaryShippingAddressID,
                    productId: upsellItem.ProductId,
                    variantId: variantId,
                    quantity: 1,
                    chosenColor: string.Empty,
                    chosenColorSkuModifier: string.Empty,
                    chosenSize: string.Empty,
                    chosenSizeSkuModifier: string.Empty,
                    textOption: string.Empty,
                    cartType: CartTypeEnum.ShoppingCart,
                    updateCartObject: true,
                    isRequired: false,
                    customerEnteredPrice: decimal.Zero);

                var price = AppLogic.GetUpsellProductPrice(0, upsellItem.ProductId, customer.CustomerLevelID);
                DB.ExecuteSQL(
                    "update shoppingcart set IsUpsell=1, ProductPrice= @price where ShoppingCartRecID = @cartRecID",
                    new SqlParameter("price", price),
                    new SqlParameter("cartRecID", newCartRecord));
            }

            return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
        }
Beispiel #21
0
        public ActionResult StartPayPalExpress(bool isPayPalCredit = false)
        {
            var customer = HttpContext.GetCustomer();

            if (!PaymentOptionProvider.PaymentMethodSelectionIsValid(AppLogic.ro_PMPayPalExpress, customer))
            {
                NoticeProvider.PushNotice(
                    message: AppLogic.GetString("checkout.paymentmethodnotallowed"),
                    type: NoticeType.Failure);

                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
            }

            var cart = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            Address shippingAddress = null;

            if (customer.IsRegistered && customer.PrimaryShippingAddressID != 0)
            {
                shippingAddress = new Address();
                shippingAddress.LoadByCustomer(customer.CustomerID, customer.PrimaryShippingAddressID, AddressTypes.Shipping);
            }

            var checkoutOptions = new Dictionary <string, string>();

            if (isPayPalCredit)
            {
                checkoutOptions.Add("UserSelectedFundingSource", "BML");
            }

            var payPalExpressRedirectUrl = Gateway.StartExpressCheckout(
                cart: cart,
                boolBypassOrderReview: false,
                checkoutOptions: checkoutOptions);

            // PPE gets the redirect URL via an AJAX request, so we have to return it in the content.
            if (Request.IsAjaxRequest() && !isPayPalCredit)
            {
                return(Content(payPalExpressRedirectUrl));
            }

            return(Redirect(payPalExpressRedirectUrl));
        }
Beispiel #22
0
        public CartContext LoadCartContext(CheckoutConfiguration configuration, Customer customer, PersistedCheckoutContext persistedCheckoutContext, PaymentMethodInfo selectedPaymentMethod)
        {
            var cartContext = new CartContext(
                cart: CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID()));

            var preRuleCheckoutContext = new PreCheckoutRuleContext(
                checkoutConfiguration: configuration,
                customer: customer,
                persistedCheckoutContext: persistedCheckoutContext,
                cartContext: cartContext,
                paymentMethodInfo: selectedPaymentMethod);

            foreach (var rule in PreCheckoutRules)
            {
                cartContext = rule.Apply(preRuleCheckoutContext);
            }

            return(cartContext);
        }
        public ActionResult MicroPayDetail()
        {
            var customer = HttpContext.GetCustomer();

            if (!PaymentOptionProvider.PaymentMethodSelectionIsValid(AppLogic.ro_PMMicropay, customer))
            {
                NoticeProvider.PushNotice(
                    message: "Invalid payment method!  Please choose another.",
                    type: NoticeType.Failure);
                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
            }

            var cart = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var model = new MicroPayViewModel
            {
                Balance             = Localization.CurrencyStringForDisplayWithExchangeRate(customer.MicroPayBalance, customer.CurrencySetting),
                BalanceIsSufficient = customer.MicroPayBalance >= cart.Total(true)
            };

            return(PartialView(ViewNames.MicroPayPartial, model));
        }
Beispiel #24
0
        public ActionResult DebugRealTimeShipping()
        {
            if (!AppLogic.AppConfigBool("RTShipping.DumpDebugXmlOnCheckout"))
            {
                return(Content(string.Empty));
            }

            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            if (Shipping.GetActiveShippingCalculationID() != Shipping.ShippingCalculationEnum.UseRealTimeRates)
            {
                return(Content(string.Empty));
            }

            var model = BuildModel(customer);

            if (ControllerContext.IsChildAction)
            {
                return(PartialView(model));
            }

            return(View(model));
        }
Beispiel #25
0
        KitAddToCartViewModel BuildDefaultKitAddToCartViewModel(
            KitProductData kitData,
            Product product,
            ProductVariant variant,
            int quantity,
            Customer customer,
            int?cartRecordId)
        {
            var cartType = cartRecordId == null
                                ? CartTypeEnum.ShoppingCart // we won't use this, so what it's set to doesn't matter
                                : CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID())
                           .CartItems
                           .Where(c => c.ShoppingCartRecordID == cartRecordId)
                           .Any()
                                ? CartTypeEnum.ShoppingCart
                                : CartTypeEnum.WishCart;

            var isUnorderable = false;

            if (!AppLogic.AppConfigBool("KitInventory.AllowSaleOfOutOfStock") &&
                (!kitData.HasStock || kitData.HasRequiredOrReadOnlyButUnOrderableKitGroup))
            {
                isUnorderable = true;
            }

            var isCallToOrder = product.IsCalltoOrder;

            kitData.ComputePrices(quantity);

            var kitGroups = new List <KitGroupViewModel>();

            foreach (var group in kitData.Groups)
            {
                var kitItems = new List <KitItemViewModel>();
                foreach (var item in group.Items)
                {
                    var priceDeltaDisplay = FormatCurrencyDisplay(item.PriceDelta, customer, variant.IsTaxable);
                    var showOutOfStock    = item.HasMappedVariant &&
                                            !item.VariantHasStock &&
                                            !AppLogic.AppConfigBool("KitInventory.AllowSaleOfOutOfStock") &&
                                            AppLogic.AppConfigBool("KitInventory.ShowOutOfStockMessage");

                    var kitItemRelativePriceDeltaDisplayText = KitItemRelativePriceDeltaDisplayText(item, customer.CurrencySetting, variant.IsTaxable, kitData);

                    kitItems.Add(new KitItemViewModel
                    {
                        Name        = item.Name,
                        NameDisplay = !string.IsNullOrEmpty(kitItemRelativePriceDeltaDisplayText)
                                                        ? string.Format("{0} [{1}]", item.Name, kitItemRelativePriceDeltaDisplayText)
                                                        : item.Name,
                        Description       = item.Description,
                        IsDefault         = item.IsDefault,
                        PriceDelta        = item.PriceDelta,
                        PriceDeltaDisplay = priceDeltaDisplay,
                        WeightDelta       = item.WeightDelta,
                        DisplayOrder      = item.DisplayOrder,
                        Id         = item.Id,
                        IsSelected = item.IsSelected,
                        TextOption = item.TextOption,
                        ImageUrl   = item.HasImage
                                                        ? item.ImagePath
                                                        : string.Empty,
                        OutOfStockMessage = showOutOfStock
                                                        ? "Out of stock"
                            : string.Empty
                    });
                }

                var selectedItemId = group.FirstSelectedItem != null
                                        ? group.FirstSelectedItem.Id
                                        : 0;

                var groupViewModel = new KitGroupViewModel
                {
                    Id          = group.Id,
                    Name        = group.Name,
                    Description = group.Description,
                    Summary     = group.Summary,
                    ImageUrl    = group.HasImage
                                                        ? group.ImagePath
                                                        : string.Empty,
                    KitGroupType   = group.SelectionControl,
                    Items          = kitItems,
                    SelectedItemId = selectedItemId,
                    IsRequired     = group.IsRequired,
                    IsReadOnly     = group.IsReadOnly
                };

                kitGroups.Add(groupViewModel);
            }

            var regularBasePrice   = kitData.Price;
            var basePrice          = kitData.BasePrice + kitData.ReadOnlyItemsSum;
            var customizedPrice    = kitData.CustomizedPrice;
            var customerLevelPrice = kitData.LevelPrice;

            PayPalAd payPalAd = null;

            // If this is a single variant product, setup the PayPal ad.
            if (AppLogic.GetNextVariant(product.ProductID, variant.VariantID) == variant.VariantID)
            {
                payPalAd = new PayPalAd(PayPalAd.TargetPage.Product);
            }

            // Values need for the Schema.Org tags
            var storeDefaultCultureInfo = CultureInfo.GetCultureInfo(Localization.GetDefaultLocale());
            var formattedSchemaPrice    = string.Format(storeDefaultCultureInfo, "{0:C}", kitData.BasePrice);
            var schemaRegionInfo        = new RegionInfo(storeDefaultCultureInfo.Name);

            // Build the view model
            return(new KitAddToCartViewModel(
                       isUnorderable: isUnorderable,
                       isCallToOrder: isCallToOrder,
                       regularBasePrice: FormatCurrencyDisplay(regularBasePrice, customer, variant.IsTaxable),
                       basePrice: FormatCurrencyDisplay(basePrice, customer, variant.IsTaxable),
                       customizedPrice: FormatCurrencyDisplay(customizedPrice, customer, variant.IsTaxable),
                       customerLevelPrice: FormatCurrencyDisplay(customerLevelPrice, customer, variant.IsTaxable),
                       showRegularBasePrice: kitData.IsDiscounted,
                       showBasePrice: !AppLogic.AppConfigBool("HideKitPrice"),
                       showCustomerLevelPrice: kitData.HasCustomerLevelPricing,
                       showQuantity: AppLogic.AppConfigBool("ShowQuantityOnProductPage") &&
                       !AppLogic.AppConfigBool("HideKitQuantity"),
                       showBuyButton: AppLogic.AppConfigBool("ShowBuyButtons") &&
                       product.ShowBuyButton &&
                       !AppLogic.HideForWholesaleSite(customer.CustomerLevelID),
                       showWishlistButton: AppLogic.AppConfigBool("ShowWishButtons"),
                       hidePriceUntilCart: product.HidePriceUntilCart,
                       restrictedQuantities: RestrictedQuantityProvider.BuildRestrictedQuantityList(variant.RestrictedQuantities),
                       payPalAd: payPalAd,
                       showSchemaOrgPrice: kitData.BasePrice > 0 && !AppLogic.AppConfigBool("HideKitPrice"),
                       schemaBasePrice: formattedSchemaPrice,
                       isoThreeLetterCurrency: schemaRegionInfo.ISOCurrencySymbol,
                       schemaProductUrl: string.Format("{0}://schema.org/Product", Request.Url.Scheme),
                       schemaOfferUrl: string.Format("{0}://schema.org/Offer", Request.Url.Scheme),
                       cartType: cartType)
            {
                ProductId = product.ProductID,
                VariantId = variant.VariantID,
                CartRecordId = cartRecordId,
                Quantity = quantity,
                KitGroups = kitGroups,

                UpsellProducts = null,
                IsWishlist = false,
                ReturnUrl = UrlHelper.MakeSafeReturnUrl(Request.RawUrl),
                TemporaryImageNameStub = Guid.NewGuid().ToString()
            });
        }
Beispiel #26
0
        string AcceptJsProcessCardOrECheck(
            int customerId,
            decimal orderTotal,
            bool useLiveTransactions,
            TransactionModeEnum transactionMode,
            out string avsResult,
            out string authorizationResult,
            out string authorizationCode,
            out string authorizationTransId,
            out string transactionCommandOut,
            out string transactionResponse)
        {
            authorizationCode     = string.Empty;
            authorizationResult   = string.Empty;
            authorizationTransId  = string.Empty;
            avsResult             = string.Empty;
            transactionCommandOut = string.Empty;
            transactionResponse   = string.Empty;

            orderTotal.ValidateNumberOfDigits(15);             // Accept.js limit

            //We don't display the address form in the lightbox, so use the billing address the customer entered onsite
            var customer = new AspDotNetStorefrontCore.Customer(customerId);
            var acceptJsBillingAddress = new customerAddressType
            {
                firstName = customer.FirstName
                            .ToAlphaNumeric()
                            .Truncate(50),             // Accept.js limit
                lastName = customer.LastName
                           .ToAlphaNumeric()
                           .Truncate(50),              // Accept.js limit
                address = customer.PrimaryBillingAddress.Address1
                          .ToAlphaNumeric().
                          Truncate(60),               // Accept.js limit
                city = customer.PrimaryBillingAddress.City
                       .ToAlphaNumeric()
                       .Truncate(40),                  // Accept.js limit
                state = customer.PrimaryBillingAddress.State
                        .ToAlphaNumeric()
                        .Truncate(40),                 // Accept.js limit, but really it's only ever going to be 2 characters
                zip = customer.PrimaryBillingAddress.Zip
                      .ToAlphaNumeric()
                      .Truncate(20)                   // Accept.js limit
            };

            //Add line items to the order info
            var cart      = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var lineItems = cart
                            .CartItems
                            .Take(30)      // Accept.js only accepts 30 line items.  Not very accepting of them.
                            .Select(cartItem => new lineItemType
            {
                itemId    = cartItem.ShoppingCartRecordID.ToString(),  // Accept.js limit of 31 which we can't get with an int
                name      = cartItem.ProductName.Truncate(31),         // Accept.js limit
                quantity  = cartItem.Quantity,                         // Accept.js limit of 4 decimal places which we can't get with an int
                unitPrice = Math.Round(cartItem.Price, 2)              // Accept.js limit
            })
                            .ToArray();

            //Add the customer's payment info from the Accept.js form
            var opaqueData = new opaqueDataType
            {
                dataDescriptor = customer.ThisCustomerSession[AppLogic.AcceptJsDataDescriptor],
                dataValue      = customer.ThisCustomerSession[AppLogic.AcceptJsDataValue]
            };

            var paymentType = new paymentType
            {
                Item = opaqueData
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionMode == TransactionModeEnum.auth
                                        ? transactionTypeEnum.authOnlyTransaction.ToString()
                                        : transactionTypeEnum.authCaptureTransaction.ToString(),
                amount          = orderTotal,
                amountSpecified = true,
                payment         = paymentType,
                billTo          = acceptJsBillingAddress,
                lineItems       = lineItems
            };

            if (useLiveTransactions)
            {
                transactionRequest.solution = new solutionType
                {
                    id = SolutionId
                }
            }
            ;

            var request = new createTransactionRequest
            {
                transactionRequest     = transactionRequest,
                merchantAuthentication = GetMerchantAuthentication(useLiveTransactions)
            };

            transactionCommandOut = JsonConvert.SerializeObject(request);

            var controller = new createTransactionController(request);

            controller.Execute(
                GetRunEnvironment(useLiveTransactions));

            var response = controller.GetApiResponse();

            if (response == null)
            {
                return("NO RESPONSE FROM GATEWAY!");
            }

            transactionResponse = JsonConvert.SerializeObject(response);

            if (response.messages.resultCode != messageTypeEnum.Ok)
            {
                return(response.transactionResponse?.errors?[0].errorText
                       ?? response.messages.message[0].text);
            }

            if (response.transactionResponse.messages == null)
            {
                return(response.transactionResponse.errors?[0].errorText
                       ?? "Unspecified Error");
            }

            authorizationCode    = response.transactionResponse.authCode;
            authorizationResult  = response.transactionResponse.messages[0].description;
            authorizationTransId = response.transactionResponse.transId;
            avsResult            = response.transactionResponse.avsResultCode;

            return(AppLogic.ro_OK);
        }
        OrderSummaryViewModel BuildOrderSummaryViewModel()
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            var subtotal = cart.SubTotal(
                includeDiscount: false,
                onlyIncludeTaxableItems: false,
                includeDownloadItems: true,
                includeFreeShippingItems: true,
                includeSystemItems: true,
                useCustomerCurrencySetting: true);

            var taxTotal = cart.TaxTotal();

            var shippingTotal = cart.ShippingTotal(
                includeDiscount: true,
                includeTax: true);

            // Calculate lineitem and order level coupon and promotional discounts.
            var discountTotal = cart.Total(
                includeDiscount: true,
                roundBeforeTotaling: false) - taxTotal - shippingTotal - subtotal;

            var orderTotal = cart.Total(includeDiscount: true);

            // Calculate the discount for gift card.
            var giftCardDiscount = Decimal.Zero;

            if (cart.Coupon.CouponType == CouponTypeEnum.GiftCard)
            {
                giftCardDiscount = decimal.Round(Currency.Convert(cart.Coupon.DiscountAmount, Localization.StoreCurrency(), customer.CurrencySetting), 2, MidpointRounding.AwayFromZero);
            }

            // Don't display the full GC balance if it exceeds the order total
            if (giftCardDiscount > orderTotal)
            {
                giftCardDiscount = orderTotal;
            }

            // Ensure gift card discounts do not create a negative order total.
            orderTotal -= giftCardDiscount;
            if (orderTotal < 0)
            {
                orderTotal = 0;
            }

            var vatEnabled         = AppLogic.AppConfigBool("VAT.Enabled");
            var shippingVatCaption = string.Empty;

            if (vatEnabled)
            {
                shippingVatCaption = AppLogic.GetString("setvatsetting.aspx.7");
                if (cart.VatIsInclusive)
                {
                    shippingVatCaption = AppLogic.GetString("setvatsetting.aspx.6");
                }
            }

            var currencySetting = customer.CurrencySetting;

            return(new OrderSummaryViewModel
            {
                SubTotal = Localization.CurrencyStringForDisplayWithExchangeRate(subtotal, currencySetting),
                DiscountTotal = Localization.CurrencyStringForDisplayWithExchangeRate(discountTotal, currencySetting),
                ShippingTotal = Localization.CurrencyStringForDisplayWithExchangeRate(shippingTotal, currencySetting),
                ShippingVatCaption = string.Format("({0})", shippingVatCaption),
                TaxTotal = Localization.CurrencyStringForDisplayWithExchangeRate(taxTotal, currencySetting),
                HasGiftCardDiscountTotal = giftCardDiscount != 0,
                GiftCardDiscountTotal = Localization.CurrencyStringForDisplayWithExchangeRate(-giftCardDiscount, currencySetting),
                Total = Localization.CurrencyStringForDisplayWithExchangeRate(orderTotal, currencySetting),
                HasDiscount = discountTotal != 0,
                ShowVatLabels = vatEnabled,
                ShowTax = !cart.VatIsInclusive
            });
        }
Beispiel #28
0
        public ActionResult Index(string errorMessage, string returnUrl, bool?showErrors)
        {
            PushErrorMessages(errorMessage);

            var defaultReturnUrl = "";

            if (string.IsNullOrEmpty(defaultReturnUrl))
            {
                defaultReturnUrl = Url.Action(ActionNames.Index, ControllerNames.Home);
            }

            var safeReturnUrl = Url.MakeSafeReturnUrl(returnUrl, defaultReturnUrl);

            // Get the current checkout state
            var customer = HttpContext.GetCustomer();

            // We need to validate that a (potentially previously) selected PM is still available and valid (as any number of site settings/configs/customerLevel values could have changed)
            if (!string.IsNullOrEmpty(customer.RequestedPaymentMethod) &&
                !PaymentOptionProvider.PaymentMethodSelectionIsValid(customer.RequestedPaymentMethod, customer))
            {
                customer.UpdateCustomer(requestedPaymentMethod: string.Empty);
            }

            var storeId = AppLogic.StoreID();
            var cart    = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

            // Make sure there's a GiftCard record for every gift card product in the cart
            CreateGiftCards(customer, cart);

            var checkoutConfiguration = CheckoutConfigurationProvider.GetCheckoutConfiguration();

            var selectedPaymentMethod = PaymentMethodInfoProvider
                                        .GetPaymentMethodInfo(
                paymentMethod: customer.RequestedPaymentMethod,
                gateway: AppLogic.ActivePaymentGatewayCleaned());

            var persistedCheckoutContext = PersistedCheckoutContextProvider
                                           .LoadCheckoutContext(customer);

            var cartContext = CartContextProvider
                              .LoadCartContext(
                customer: customer,
                configuration: checkoutConfiguration,
                persistedCheckoutContext: persistedCheckoutContext,
                selectedPaymentMethod: selectedPaymentMethod);

            var checkoutSelectionContext = CheckoutSelectionProvider
                                           .GetCheckoutSelection(
                customer: customer,
                persistedCheckoutContext: persistedCheckoutContext,
                selectedPaymentMethod: selectedPaymentMethod);

            var result = CheckoutEngine
                         .EvaluateCheckout(
                customer: customer,
                configuration: checkoutConfiguration,
                persistedCheckoutContext: persistedCheckoutContext,
                checkoutSelectionContext: checkoutSelectionContext,
                storeId: storeId,
                cartContext: cartContext);

            var updated = CheckoutSelectionProvider.ApplyCheckoutSelections(customer, result.Selections);

            var action = GetActionForState(result.State);

            // Perform the resulting action
            switch (action)
            {
            case CheckoutAction.Error:
                if (result.State == CheckoutState.CustomerIsNotOver13)
                {
                    break;
                }
                else if (result.State == CheckoutState.TermsAndConditionsRequired)
                {
                    break;
                }
                else if (result.State == CheckoutState.ShippingAddressDoesNotMatchBillingAddress)
                {
                    NoticeProvider.PushNotice("This store can only ship to the billing address", NoticeType.Failure);
                }
                else if (result.State == CheckoutState.MicroPayBalanceIsInsufficient)
                {
                    NoticeProvider.PushNotice(
                        string.Format("Your MicroPay balance is insufficient for purchasing this order. <br />(<b>Your MicroPay Balance is {0}</b>)",
                                      Localization.CurrencyStringForDisplayWithExchangeRate(updated.Customer.MicroPayBalance, updated.Customer.CurrencySetting)),
                        NoticeType.Failure);
                }
                else if (result.State == CheckoutState.SubtotalDoesNotMeetMinimumAmount)
                {
                    NoticeProvider.PushNotice(
                        string.Format("The minimum allowed order amount is {0} Please add additional items to your cart, or increase item quantities.",
                                      updated.Customer.CurrencyString(AppLogic.AppConfigNativeDecimal("CartMinOrderAmount"))),
                        NoticeType.Failure);
                }
                else if (result.State == CheckoutState.CartItemsLessThanMinimumItemCount)
                {
                    NoticeProvider.PushNotice(
                        string.Format("Please make sure you have ordered at least {0} items - any {1} items from our site - before checking out.",
                                      AppLogic.AppConfigNativeInt("MinCartItemsBeforeCheckout"),
                                      AppLogic.AppConfigNativeInt("MinCartItemsBeforeCheckout")),
                        NoticeType.Failure);
                }
                else if (result.State == CheckoutState.CartItemsGreaterThanMaximumItemCount)
                {
                    NoticeProvider.PushNotice(
                        string.Format("We allow a maximum of {0} items per order.  Please remove some products from your cart before beginning checkout.",
                                      AppLogic.AppConfigNativeInt("MaxCartItemsBeforeCheckout")),
                        NoticeType.Failure);
                }
                else if (result.State == CheckoutState.RecurringScheduleMismatchOnItems)
                {
                    NoticeProvider.PushNotice("Your cart has Auto-Ship items with conflicting shipment schedules. Only one Auto-Ship schedule is allowed per order.", NoticeType.Failure);
                }
                else
                {
                    NoticeProvider.PushNotice(result.State.ToString(), NoticeType.Failure);
                }
                break;

            case CheckoutAction.Empty:
                return(View("EmptyCart"));
            }

            return(RenderIndexView(
                       checkoutStageContext: result.CheckoutStageContext,
                       persistedCheckoutContext: updated.PersistedCheckoutContext,
                       selectedPaymentMethod: updated.SelectedPaymentMethod,
                       customer: updated.Customer,
                       termsAndConditionsAccepted: result.Selections.TermsAndConditionsAccepted,
                       returnUrl: safeReturnUrl,
                       showCheckoutStageErrors: showErrors ?? false));
        }
        public ActionResult CreditCard()
        {
            var customer = HttpContext.GetCustomer();

            if (!PaymentOptionProvider.PaymentMethodSelectionIsValid(AppLogic.ro_PMCreditCard, customer))
            {
                NoticeProvider.PushNotice(
                    message: AppLogic.GetString("checkout.paymentmethodnotallowed"),
                    type: NoticeType.Failure);
                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
            }

            //Decide which form to display
            if (AppLogic.ActivePaymentGatewayCleaned() == Gateway.ro_GWBRAINTREE)
            {
                var processor = GatewayLoader.GetProcessor(Gateway.ro_GWBRAINTREE);

                var clientToken = processor.ObtainBraintreeToken();

                if (string.IsNullOrEmpty(clientToken))
                {
                    NoticeProvider.PushNotice(AppLogic.GetString("braintree.creditcardunavailable"), NoticeType.Failure);
                    return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
                }

                var braintreeModel = new BraintreeViewModel(token: clientToken,
                                                            scriptUrl: AppLogic.AppConfig("Braintree.ScriptUrl"));

                return(View(ViewNames.BraintreeCreditCard, braintreeModel));
            }
            else if (AppLogic.ActivePaymentGatewayCleaned() == Gateway.ro_GWACCEPTJS)
            {
                var liveMode = AppLogic.AppConfigBool("UseLiveTransactions");
                var cart     = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());

                var acceptJsModel = new AcceptJsViewModel(
                    clientKey: liveMode
                                                ? AppLogic.AppConfig("AcceptJs.Live.ClientKey")
                                                : AppLogic.AppConfig("AcceptJs.Test.ClientKey"),
                    apiLoginId: liveMode
                                                ? AppLogic.AppConfig("AcceptJs.Live.ApiLoginId")
                                                : AppLogic.AppConfig("AcceptJs.Test.ApiLoginId"),
                    scriptUrlHostedForm: liveMode
                                                ? AppLogic.AppConfig("AcceptJs.Form.Hosted.Live.Url")
                                                : AppLogic.AppConfig("AcceptJs.Form.Hosted.Test.Url"),
                    scriptUrlOwnForm: liveMode
                                                ? AppLogic.AppConfig("AcceptJs.Form.Own.Live.Url")
                                                : AppLogic.AppConfig("AcceptJs.Form.Own.Test.Url"));


                return(View(ViewNames.AcceptJsCreditCard, acceptJsModel));
            }
            else if (AppLogic.ActivePaymentGatewayCleaned() == Gateway.ro_GWSAGEPAYPI)
            {
                var processor = (ISagePayPiGatewayProcessor)GatewayLoader.GetProcessor(Gateway.ro_GWSAGEPAYPI);

                var clientMerchantSessionKey = processor.ObtainSagePayPiMerchantSessionKey();

                if (string.IsNullOrEmpty(clientMerchantSessionKey))
                {
                    NoticeProvider.PushNotice(AppLogic.GetString("sagepaypi.creditcardunavailable"), NoticeType.Failure);
                    return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
                }

                var sagePayPiModel = new SagePayPiViewModel(merchantSessionKey: clientMerchantSessionKey,
                                                            scriptUrl: AppLogic.AppConfigBool("UseLiveTransactions")
                                                ? AppLogic.AppConfig("SagePayPi.LiveScriptUrl")
                                                : AppLogic.AppConfig("SagePayPi.TestScriptUrl"),
                                                            validateCreditCardNumber: AppLogic.AppConfigBool("ValidateCreditCardNumbers"));

                return(View(ViewNames.SagePayPiCreditCard, sagePayPiModel));
            }
            else
            {
                var ccModel = BuildCheckoutCreditCardViewModel(customer);
                return(View(ViewNames.CreditCard, ccModel));
            }
        }
Beispiel #30
0
        public CheckoutAccountStatus GetCheckoutAccountStatus(Customer customer, string email)
        {
            var guestCheckoutType = AppConfigProvider.GetAppConfigValue <GuestCheckoutType>("GuestCheckout");

            // If the customer is already logged in, we've got everything we need.
            // Just set the mode to "Registered" to indicate we have a "locked" registered customer.
            if (customer.IsRegistered)
            {
                return(new CheckoutAccountStatus(
                           email: customer.EMail,
                           state: CheckoutAccountState.Registered,
                           nextAction: CheckoutAccountAction.None,
                           requireRegisteredCustomer: false));
            }

            // If the customer is not logged in and hasn't given us an email, we don't have anything to work with yet.
            // Set the mode to "EnterEmail" to indicate we need that first.
            if (string.IsNullOrWhiteSpace(email))
            {
                return(new CheckoutAccountStatus(
                           email: string.Empty,
                           state: CheckoutAccountState.Unvalidated,
                           nextAction: CheckoutAccountAction.MustProvideEmail,
                           requireRegisteredCustomer: false));
            }

            // If we have an email address and we're forcing guest checkouts, then we will never need anything more.
            // Set the mode to "Guest" to indicate we have a "locked" guest customer.
            if (guestCheckoutType == GuestCheckoutType.PasswordNeverRequestedAtCheckout)
            {
                return(new CheckoutAccountStatus(
                           email: email,
                           state: CheckoutAccountState.Guest,
                           nextAction: CheckoutAccountAction.None,
                           requireRegisteredCustomer: false));
            }

            // If we got this far, it means we have an email that may or may not be registered. The remaining modes
            // depends on knowing which.
            var emailIsAlreadyRegistered = Customer.EmailInUse(
                email: email,
                customerId: customer.CustomerID,
                excludeUnregisteredUsers: true);

            // Finally, decide if we require a logged in user.
            var cart = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var requireRegisteredCustomer =
                cart.HasRecurringComponents() ||
                guestCheckoutType == GuestCheckoutType.Disabled ||
                (emailIsAlreadyRegistered && guestCheckoutType != GuestCheckoutType.AllowRegisteredCustomers);

            // Now we can return a status that indicates the following:
            //	- The email address is already registered and the user must login to continue using it
            //	- The email address is already registered, but the user may continue using it without logging in
            //	- The email address is unregistered, but must create an account to continue using it
            //	- The email address is unregistered and the user may continue using it without creating an account
            return(new CheckoutAccountStatus(
                       email: email,
                       state: requireRegisteredCustomer
                                        ? CheckoutAccountState.Unvalidated
                                        : CheckoutAccountState.Guest,
                       nextAction: emailIsAlreadyRegistered
                                        ? CheckoutAccountAction.CanLogin
                                        : CheckoutAccountAction.CanCreateAccount,
                       requireRegisteredCustomer: requireRegisteredCustomer));
        }