need help to upgrade page to 2.6

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
11 years ago
hi
this code for 2.5 checkout one page with out 6 step it's very good code
but i need help to change to 2.6
if its cost i can pay 20$

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Shipping;
using Nop.Services.Tax;
using Nop.Web.Extensions;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Security;
using Nop.Web.Models.Checkout;
using Nop.Web.Models.Common;

namespace Nop.Web.Controllers
{
    [NopHttpsRequirement(SslRequirement.Yes)]
    public class OnePageCheckoutV25Controller : BaseNopController
    {
        #region Fields

        private readonly IWorkContext _workContext;
        private readonly IShoppingCartService _shoppingCartService;
        private readonly ILocalizationService _localizationService;
        private readonly ITaxService _taxService;
        private readonly ICurrencyService _currencyService;
        private readonly IPriceFormatter _priceFormatter;
        private readonly IOrderProcessingService _orderProcessingService;
        private readonly ICustomerService _customerService;
        private readonly ICountryService _countryService;
        private readonly IStateProvinceService _stateProvinceService;
        private readonly IShippingService _shippingService;
        private readonly IPaymentService _paymentService;
        private readonly IOrderTotalCalculationService _orderTotalCalculationService;
        private readonly ILogger _logger;
        private readonly IOrderService _orderService;
        private readonly IWebHelper _webHelper;
        private readonly HttpContextBase _httpContext;
        private readonly IMobileDeviceHelper _mobileDeviceHelper;


        private readonly OrderSettings _orderSettings;
        private readonly RewardPointsSettings _rewardPointsSettings;
        private readonly PaymentSettings _paymentSettings;

        #endregion

        #region Constructors

        public OnePageCheckoutV25Controller(IWorkContext workContext,
            IShoppingCartService shoppingCartService, ILocalizationService localizationService,
            ITaxService taxService, ICurrencyService currencyService,
            IPriceFormatter priceFormatter, IOrderProcessingService orderProcessingService,
            ICustomerService customerService, ICountryService countryService,
            IStateProvinceService stateProvinceService, IShippingService shippingService,
            IPaymentService paymentService, IOrderTotalCalculationService orderTotalCalculationService,
            ILogger logger, IOrderService orderService, IWebHelper webHelper,
            HttpContextBase httpContext, IMobileDeviceHelper mobileDeviceHelper,
            OrderSettings orderSettings, RewardPointsSettings rewardPointsSettings,
            PaymentSettings paymentSettings)
        {
            this._workContext = workContext;
            this._shoppingCartService = shoppingCartService;
            this._localizationService = localizationService;
            this._taxService = taxService;
            this._currencyService = currencyService;
            this._priceFormatter = priceFormatter;
            this._orderProcessingService = orderProcessingService;
            this._customerService = customerService;
            this._countryService = countryService;
            this._stateProvinceService = stateProvinceService;
            this._shippingService = shippingService;
            this._paymentService = paymentService;
            this._orderTotalCalculationService = orderTotalCalculationService;
            this._logger = logger;
            this._orderService = orderService;
            this._webHelper = webHelper;
            this._httpContext = httpContext;
            this._mobileDeviceHelper = mobileDeviceHelper;

            this._orderSettings = orderSettings;
            this._rewardPointsSettings = rewardPointsSettings;
            this._paymentSettings = paymentSettings;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected bool IsPaymentWorkflowRequired(IList<ShoppingCartItem> cart, bool ignoreRewardPoints = false)
        {
            bool result = true;

            //check whether order total equals zero
            decimal? shoppingCartTotalBase = _orderTotalCalculationService.GetShoppingCartTotal(cart, ignoreRewardPoints);
            if (shoppingCartTotalBase.HasValue && shoppingCartTotalBase.Value == decimal.Zero)
                result = false;
            return result;
        }

        [NonAction]
        protected OnePageCheckoutV25Model PrepareBillingAddressModel(OnePageCheckoutV25Model model, int? selectedCountryId = null)
        {
            //existing addresses
            var addresses = _workContext.CurrentCustomer.Addresses.Where(a => a.Country == null || a.Country.AllowsBilling).ToList();
            foreach (var address in addresses)
                model.ExistingBillingAddresses.Add(address.ToModel());

            //new address model
            model.NewBillingAddress = new AddressModel();
            model.NewBillingAddress.Address2Disabled = true;
            model.NewBillingAddress.CompanyDisabled = true;
            model.NewBillingAddress.CountryDisabled = true;
            model.NewBillingAddress.FaxNumberDisabled = true;
            model.NewBillingAddress.StateProvinceDisabled = true;
          
            //countries
            model.NewBillingAddress.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountriesForBilling())
                model.NewBillingAddress.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (selectedCountryId.HasValue && c.Id == selectedCountryId.Value) });
            //states
            var states = selectedCountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(selectedCountryId.Value).ToList() : new List<StateProvince>();
            if (states.Count > 0)
            {
                foreach (var s in states)
                    model.NewBillingAddress.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString() });
            }
            else
                model.NewBillingAddress.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });

            return model;
        }

        [NonAction]
        protected OnePageCheckoutV25Model PrepareShippingAddressModel(OnePageCheckoutV25Model model, int? selectedCountryId = null)
        {

            //existing addresses
            var addresses = _workContext.CurrentCustomer.Addresses.Where(a => a.Country == null || a.Country.AllowsShipping).ToList();
            foreach (var address in addresses)
                model.ExistingShippingAddresses.Add(address.ToModel());

            //new address model
            model.NewShippingAddress = new AddressModel();
            model.NewShippingAddress.Address2Disabled = true;
            model.NewShippingAddress.CompanyDisabled = true;
            model.NewShippingAddress.CountryDisabled = true;
            model.NewShippingAddress.FaxNumberDisabled = true;
            model.NewShippingAddress.StateProvinceDisabled = true;
            //countries
            model.NewShippingAddress.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountriesForShipping())
                model.NewShippingAddress.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (selectedCountryId.HasValue && c.Id == selectedCountryId.Value) });
            //states
            var states = selectedCountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(selectedCountryId.Value).ToList() : new List<StateProvince>();
            if (states.Count > 0)
            {
                foreach (var s in states)
                    model.NewShippingAddress.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString() });
            }
            else
                model.NewShippingAddress.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });

            return model;
        }

        [NonAction]
        protected OnePageCheckoutV25Model PrepareShippingMethodModel(OnePageCheckoutV25Model model, IList<ShoppingCartItem> cart)
        {
            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress);
            if (getShippingOptionResponse.Success)
            {
                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new OnePageCheckoutV25Model.ShippingMethodModel()
                    {
                        Name = shippingOption.Name,
                        Description = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                    };

                    //adjust rate
                    Discount appliedDiscount = null;
                    var shippingTotal = _orderTotalCalculationService.AdjustShippingRate(
                        shippingOption.Rate, cart, out appliedDiscount);

                    decimal rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer);
                    decimal rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                    soModel.Fee = _priceFormatter.FormatShippingPrice(rate, true);

                    model.ShippingMethods.Add(soModel);
                }
            }
            else
                foreach (var error in getShippingOptionResponse.Errors)
                    model.ShippingMethodWarnings.Add(error);

            return model;
        }

        [NonAction]
        protected OnePageCheckoutV25Model PreparePaymentMethodModel(OnePageCheckoutV25Model model, IList<ShoppingCartItem> cart)
        {
            //reward points
            if (_rewardPointsSettings.Enabled && !cart.IsRecurring())
            {
                int rewardPointsBalance = _workContext.CurrentCustomer.GetRewardPointsBalance();
                decimal rewardPointsAmountBase = _orderTotalCalculationService.ConvertRewardPointsToAmount(rewardPointsBalance);
                decimal rewardPointsAmount = _currencyService.ConvertFromPrimaryStoreCurrency(rewardPointsAmountBase, _workContext.WorkingCurrency);
                if (rewardPointsAmount > decimal.Zero)
                {
                    model.DisplayRewardPoints = true;
                    model.RewardPointsAmount = _priceFormatter.FormatPrice(rewardPointsAmount, true, false);
                    model.RewardPointsBalance = rewardPointsBalance;
                }
            }

            var boundPaymentMethods = _paymentService
                .LoadActivePaymentMethods(_workContext.CurrentCustomer.Id)
                .Where(pm => pm.PaymentMethodType == PaymentMethodType.Standard || pm.PaymentMethodType == PaymentMethodType.Redirection)
                .ToList();
            foreach (var pm in boundPaymentMethods)
            {
                if (cart.IsRecurring() && pm.RecurringPaymentType == RecurringPaymentType.NotSupported)
                    continue;

                var pmModel = new OnePageCheckoutV25Model.PaymentMethodModel()
                {
                    Name = pm.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id),
                    PaymentMethodSystemName = pm.PluginDescriptor.SystemName,
                };
                //payment method additional fee
                decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(pm.PluginDescriptor.SystemName);
                decimal rateBase = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, _workContext.CurrentCustomer);
                decimal rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                if (rate > decimal.Zero)
                    pmModel.Fee = _priceFormatter.FormatPaymentMethodAdditionalFee(rate, true);

                model.PaymentMethods.Add(pmModel);
            }
            return model;
        }

        [NonAction]
        protected OnePageCheckoutV25Model PreparePaymentInfoModel(OnePageCheckoutV25Model model, IPaymentMethod paymentMethod)
        {
            string actionName;
            string controllerName;
            RouteValueDictionary routeValues;
            paymentMethod.GetPaymentInfoRoute(out actionName, out controllerName, out routeValues);
            model.PaymentInfoActionName = actionName;
            model.PaymentInfoControllerName = controllerName;
            model.PaymentInfoRouteValues = routeValues;
            model.DisplayOrderTotals = _orderSettings.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab;
            return model;
        }



        [NonAction]
        protected CheckoutPaymentInfoModel PreparePaymentInfoModel(IPaymentMethod paymentMethod)
        {
            string actionName;
            string controllerName;
            RouteValueDictionary routeValues;
            paymentMethod.GetPaymentInfoRoute(out actionName, out controllerName, out routeValues);

            var model = new CheckoutPaymentInfoModel();
            model.PaymentInfoActionName = actionName;
            model.PaymentInfoControllerName = controllerName;
            model.PaymentInfoRouteValues = routeValues;
            model.DisplayOrderTotals = _orderSettings.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab;
            return model;
        }


        [NonAction]
        protected OnePageCheckoutV25Model PrepareConfirmOrderModel(OnePageCheckoutV25Model model, IList<ShoppingCartItem> cart)
        {
            //min order amount validation
            bool minOrderTotalAmountOk = _orderProcessingService.ValidateMinOrderTotalAmount(cart);
            if (!minOrderTotalAmountOk)
            {
                decimal minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency);
                model.MinOrderTotalWarning = string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"), _priceFormatter.FormatPrice(minOrderTotalAmount, true, false));
            }
            return model;
        }

        [NonAction]
        protected bool UseOnePageCheckout()
        {
            bool useMobileDevice = _mobileDeviceHelper.IsMobileDevice(_httpContext)
                && _mobileDeviceHelper.MobileDevicesSupported()
                && !_mobileDeviceHelper.CustomerDontUseMobileVersion();

            //mobile version doesn't support one-page checkout
            if (useMobileDevice)
                return false;

            //check the appropriate setting
            return _orderSettings.OnePageCheckoutEnabled;
        }

        [NonAction]
        protected bool IsMinimumOrderPlacementIntervalValid(Customer customer)
        {
            //prevent 2 orders being placed within an X seconds time frame
            if (_orderSettings.MinimumOrderPlacementInterval == 0)
                return true;

            var lastOrderPlaced = _orderService.GetOrdersByCustomerId(_workContext.CurrentCustomer.Id)
                .FirstOrDefault();
            if (lastOrderPlaced == null)
                return true;

            var interval = DateTime.UtcNow - lastOrderPlaced.CreatedOnUtc;
            return interval.TotalSeconds > _orderSettings.MinimumOrderPlacementInterval;
        }

        #endregion

        #region Methods

        //mobile version doesn't support one-page checkout
        public ActionResult Index()
        {
            if (!UseOnePageCheckout())
                return RedirectToRoute("Checkout");

            var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            //reset checkout data
            _customerService.ResetCheckoutData(_workContext.CurrentCustomer, false);

            //validation (cart)
            var scWarnings = _shoppingCartService.GetShoppingCartWarnings(cart, _workContext.CurrentCustomer.CheckoutAttributes, true);
            if (scWarnings.Count > 0)
                return RedirectToRoute("ShoppingCart");
            //validation (each shopping cart item)
            foreach (ShoppingCartItem sci in cart)
            {
                var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(_workContext.CurrentCustomer,
                    sci.ShoppingCartType,
                    sci.ProductVariant,
                    sci.AttributesXml,
                    sci.CustomerEnteredPrice,
                    sci.Quantity,
                    false);
                if (sciWarnings.Count > 0)
                    return RedirectToRoute("ShoppingCart");
            }

            var model = new OnePageCheckoutV25Model();
            model.ShippingRequired = cart.RequiresShipping();
            //Set Default Payment Method
            IList<IPaymentMethod> activePaymentMethods = _paymentService.LoadActivePaymentMethods();
            IPaymentMethod defaultPaymentMethod = activePaymentMethods.FirstOrDefault();
            _workContext.CurrentCustomer.SelectedPaymentMethodSystemName = defaultPaymentMethod.PluginDescriptor.SystemName;
            _customerService.UpdateCustomer(_workContext.CurrentCustomer);
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(_workContext.CurrentCustomer.SelectedPaymentMethodSystemName);

            //Payment Method Plugin
            string actionName;
            string controllerName;
            RouteValueDictionary routeValues;
            paymentMethod.GetPaymentInfoRoute(out actionName, out controllerName, out routeValues);
            model.PaymentInfoActionName = actionName;
            model.PaymentInfoControllerName = controllerName;
            model.PaymentInfoRouteValues = routeValues;
            model.DisplayOrderTotals = _orderSettings.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab;
            //Shipping option

            //Prepare model
            model = PrepareBillingAddressModel(model);
            model = PrepareShippingAddressModel(model);
            model = PrepareShippingMethodModel(model, cart);
            model = PreparePaymentMethodModel(model, cart);
            model = PreparePaymentInfoModel(model, paymentMethod);
            model = PrepareConfirmOrderModel(model, cart);

            return View(model);
        }

        [AcceptVerbs("POST")]
        [ActionName("Index")]
        public ActionResult SaveAll(OnePageCheckoutV25Model model, FormCollection form)
        {
            //validation
            var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            if (!UseOnePageCheckout())
                return RedirectToRoute("Checkout");

            int billingAddressId = 0;
            int.TryParse(form["billing_address_id"], out billingAddressId);

            bool billingSucceeded = false;

            if (billingAddressId == 0)
            {
                model.NewBillingAddressPreselected = true;
                billingSucceeded = NewBillingAddress(model);
            }
            else
            {
                model.SelectedBillingAddressID = billingAddressId;
                billingSucceeded = SaveBillingAddress(billingAddressId);
            }

            int shippingAddressId = 0;

            int.TryParse(form["shipping_address_id"], out shippingAddressId);
            bool shippingSucceeded = false;
            if (shippingAddressId == 0)
            {
                model.NewShippingAddressPreselected = true;
                shippingSucceeded = NewShippingAddress(model);
            }
            else
            {
                model.SelectedShippingAddressID = shippingAddressId;
                shippingSucceeded = SaveShippingAddress(shippingAddressId);
            }

            //string paymentMethod = form["paymentmethod"];
            //model.SelectedPaymentMethod = paymentMethod;
            //bool paymentMethodSucceeded = SavePaymentMethod(model);
            var paymentMethod = _workContext.CurrentCustomer.SelectedPaymentMethodSystemName;
            var paymentMethodInst = _paymentService.LoadPaymentMethodBySystemName(paymentMethod);
            model.SelectedPaymentMethod = paymentMethod;

            string shippingMethod = form["shippingmethod"];
            model.SelectedShippingMethod = shippingMethod;
            bool shippingMethodSucceeded = SaveShippingMethod(model);

            bool paymentinfosucceeded = false;
            bool paymentsucceeded = false;
            paymentinfosucceeded = SavePaymentInfo(form);
            if (!ModelState.IsValid)
            {
                //Prepare model
                model = PrepareBillingAddressModel(model);
                model = PrepareShippingAddressModel(model);
                model = PrepareShippingMethodModel(model, cart);
                model = PreparePaymentMethodModel(model, cart);
                model = PreparePaymentInfoModel(model, paymentMethodInst);
                model = PrepareConfirmOrderModel(model, cart);

                return View(model);
            }

            if (paymentinfosucceeded)
            {
                paymentsucceeded = ConfirmOrder(model);
                if (paymentsucceeded == true)
                    return RedirectToRoute("CheckoutCompleted");
            }

            return View(model);
        }

        public bool SaveBillingAddress(int addressId)
        {
            var address = _workContext.CurrentCustomer.Addresses.Where(a => a.Id == addressId).FirstOrDefault();
            if (address == null)
                return false;

            _workContext.CurrentCustomer.SetBillingAddress(address);
            _customerService.UpdateCustomer(_workContext.CurrentCustomer);
            return true;
        }

        public bool NewBillingAddress(OnePageCheckoutV25Model model)
        {
            if (ModelState.IsValid)
            {
                var address = model.NewBillingAddress.ToEntity();
                address.CreatedOnUtc = DateTime.UtcNow;
                //some validation
                if (address.CountryId == 0)
                    address.CountryId = null;
                if (address.StateProvinceId == 0)
                    address.StateProvinceId = null;
                _workContext.CurrentCustomer.AddAddress(address);
                _workContext.CurrentCustomer.SetBillingAddress(address);
                _customerService.UpdateCustomer(_workContext.CurrentCustomer);

                return true;
            }

            ////If we got this far, something failed, redisplay form
            model = PrepareBillingAddressModel(model, model.NewBillingAddress.CountryId);
            return false;
        }

  
11 years ago
Hi, I know a little late to answer, but had this issue few days ago,
all you need just replace some code from original Checkout Controller, for example:

//_workContext.CurrentCustomer.AddAddress(address);
//_workContext.CurrentCustomer.SetBillingAddress(address);
_workContext.CurrentCustomer.Addresses.Add(address);
_workContext.CurrentCustomer.BillingAddress = address;


Yaro
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.