Пример #1
0
        public virtual CheckoutViewModel CreateCheckoutViewModel(ICart cart, CheckoutPage currentPage, IPaymentMethod paymentOption = null)
        {
            if (cart == null)
            {
                return(CreateEmptyCheckoutViewModel(currentPage));
            }

            var currentShippingAddressId = cart.GetFirstShipment()?.ShippingAddress?.Id;
            var currentBillingAdressId   = cart.GetFirstForm().Payments.FirstOrDefault()?.BillingAddress?.Id;

            var shipments = _shipmentViewModelFactory.CreateShipmentsViewModel(cart).ToList();
            var useShippingAddressForBilling = shipments.Count == 1;

            var viewModel = new CheckoutViewModel(currentPage)
            {
                Shipments      = shipments,
                BillingAddress = CreateBillingAddressModel(currentBillingAdressId),
                UseShippingingAddressForBilling = useShippingAddressForBilling,
                AppliedCouponCodes = cart.GetFirstForm().CouponCodes.Distinct(),
                AvailableAddresses = new List <AddressModel>(),
                ReferrerUrl        = GetReferrerUrl(),
                Currency           = cart.Currency,
                CurrentCustomer    = _customerService.GetCurrentContactViewModel(),
                IsOnHoldBudget     = CheckForOnHoldBudgets(),
                Payment            = paymentOption,
                PaymentPlanSetting = new PaymentPlanSetting()
                {
                    CycleMode = Mediachase.Commerce.Orders.PaymentPlanCycle.None,
                    IsActive  = false,
                    StartDate = DateTime.UtcNow
                },
            };

            UpdatePayments(viewModel, cart);

            var availableAddresses = GetAvailableAddresses();

            if (availableAddresses.Any())
            {
                //viewModel.AvailableAddresses.Add(new AddressModel { Name = _localizationService.GetString("/Checkout/MultiShipment/SelectAddress"), AddressId = "" });

                foreach (var address in availableAddresses)
                {
                    viewModel.AvailableAddresses.Add(address);
                }
            }
            else
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/NoAddressFound"), AddressId = ""
                });
            }

            SetDefaultShipmentAddress(viewModel, currentShippingAddressId);

            _addressBookService.LoadAddress(viewModel.BillingAddress);
            PopulateCountryAndRegions(viewModel);

            return(viewModel);
        }
Пример #2
0
        public virtual CheckoutViewModel CreateCheckoutViewModel(ICart cart, CheckoutPage currentPage, IPaymentMethod paymentMethod = null)
        {
            if (cart == null)
            {
                return(CreateEmptyCheckoutViewModel(currentPage));
            }

            var currentShippingAddressId = cart.GetFirstShipment()?.ShippingAddress?.Id;
            var currentBillingAdressId   = cart.GetFirstForm().Payments.FirstOrDefault()?.BillingAddress?.Id;

            var shipments = _shipmentViewModelFactory.CreateShipmentsViewModel(cart).ToList();
            var useBillingAddressForShipment = shipments.Count == 1 && currentBillingAdressId == currentShippingAddressId && _addressBookService.UseBillingAddressForShipment();

            var payments = _paymentMethodViewModelFactory.CreatePaymentMethodSelectionViewModel(paymentMethod);

            paymentMethod = payments.SelectedPaymentMethod.PaymentMethod;

            var viewModel = new CheckoutViewModel
            {
                CurrentPage    = currentPage,
                Shipments      = shipments,
                BillingAddress = CreateBillingAddressModel(),
                UseBillingAddressForShipment = useBillingAddressForShipment,
                StartPage          = _contentLoader.Get <StartPage>(ContentReference.StartPage),
                AppliedCouponCodes = cart.GetFirstForm().CouponCodes.Distinct(),
                AvailableAddresses = new List <AddressModel>(),
                ReferrerUrl        = GetReferrerUrl(),
                Payment            = paymentMethod,
            };

            var availableAddresses = GetAvailableAddresses();

            if (availableAddresses.Any())
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/SelectAddress")
                });

                foreach (var address in availableAddresses)
                {
                    viewModel.AvailableAddresses.Add(address);
                }
            }
            else
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/NoAddressFound")
                });
            }

            SetDefaultShipmentAddress(viewModel, currentShippingAddressId);

            _addressBookService.LoadAddress(viewModel.BillingAddress);
            PopulateCountryAndRegions(viewModel);

            viewModel.KlarnaCheckoutPaymentMethodSelected = viewModel.Payment?.SystemKeyword == Constants.KlarnaCheckoutSystemKeyword;

            return(viewModel);
        }
        public virtual MiniCartViewModel CreateMiniCartViewModel(ICart cart, bool isSharedCart = false)
        {
            var labelSettings = _settingsService.GetSiteSettings<LabelSettings>();
            var pageSettings = _settingsService.GetSiteSettings<ReferencePageSettings>();
            if (cart == null)
            {
                return new MiniCartViewModel
                {
                    ItemCount = 0,
                    CheckoutPage = pageSettings?.CheckoutPage,
                    CartPage = isSharedCart ? pageSettings?.SharedCartPage : pageSettings?.CartPage,
                    Label = isSharedCart ? labelSettings?.SharedCartLabel : labelSettings?.CartLabel,
                    Shipments = Enumerable.Empty<ShipmentViewModel>(),
                    Total = new Money(0, _currencyService.GetCurrentCurrency()),
                    IsSharedCart = isSharedCart
                };
            }

            return new MiniCartViewModel
            {
                ItemCount = GetLineItemsTotalQuantity(cart),
                CheckoutPage = pageSettings?.CheckoutPage,
                CartPage = isSharedCart ? pageSettings?.SharedCartPage : pageSettings?.CartPage,
                Label = isSharedCart ? labelSettings?.SharedCartLabel : labelSettings?.CartLabel,
                Shipments = _shipmentViewModelFactory.CreateShipmentsViewModel(cart),
                Total = _orderGroupCalculator.GetSubTotal(cart),
                IsSharedCart = isSharedCart
            };
        }
Пример #4
0
        public virtual CheckoutViewModel CreateCheckoutViewModel(ICart cart, CheckoutPage currentPage, IPaymentMethodViewModel <PaymentMethodBase> paymentViewModel = null)
        {
            if (cart == null)
            {
                return(CreateEmptyCheckoutViewModel(currentPage));
            }

            var shipments = _shipmentViewModelFactory.CreateShipmentsViewModel(cart).ToList();

            var viewModel = new CheckoutViewModel
            {
                CurrentPage    = currentPage,
                Shipments      = shipments,
                BillingAddress = CreateBillingAddressModel(),
                UseBillingAddressForShipment = shipments.Count == 1 && _addressBookService.UseBillingAddressForShipment(),
                StartPage          = _contentLoader.Get <StartPage>(ContentReference.StartPage),
                AppliedCouponCodes = cart.GetFirstForm().CouponCodes.Distinct(),
                AvailableAddresses = new List <AddressModel>(),
                ReferrerUrl        = GetReferrerUrl(),
                Payment            = paymentViewModel,
                CurrentCustomer    = _customerService.GetCurrentContact(),
                IsOnHoldBudget     = CheckForOnHoldBudgets()
            };

            UpdatePayment(viewModel);

            var availableAddresses = GetAvailableAddresses();

            if (availableAddresses.Any())
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/SelectAddress")
                });

                foreach (var address in availableAddresses)
                {
                    viewModel.AvailableAddresses.Add(address);
                }
            }
            else
            {
                viewModel.AvailableAddresses.Add(new AddressModel {
                    Name = _localizationService.GetString("/Checkout/MultiShipment/NoAddressFound")
                });
            }

            SetDefaultShipmentAddress(viewModel);

            _addressBookService.LoadAddress(viewModel.BillingAddress);
            PopulateCountryAndRegions(viewModel);

            return(viewModel);
        }
        public async Task <ActionResult> BuyNow(RequestParamsToCart param)
        {
            var warningMessage = string.Empty;

            ModelState.Clear();

            if (CartWithValidationIssues.Cart == null)
            {
                _cart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultCartName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var result = _cartService.AddToCart(CartWithValidationIssues.Cart, param.Code, param.Quantity, param.Store, param.SelectedStore);

            if (!result.EntriesAddedToCart)
            {
                return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
            }
            var contact = PrincipalInfo.CurrentPrincipal.GetCustomerContact();

            if (contact == null)
            {
                return(RedirectToCart("The contact is invalid"));
            }

            var creditCard = contact.ContactCreditCards.FirstOrDefault();

            if (creditCard == null)
            {
                return(RedirectToCart("There is not any credit card"));
            }

            var shipment = CartWithValidationIssues.Cart.GetFirstShipment();

            if (shipment == null)
            {
                return(RedirectToCart("The shopping cart is not exist"));
            }

            var shippingAddress = (contact.PreferredShippingAddress ?? contact.ContactAddresses.FirstOrDefault())?.ConvertToOrderAddress(CartWithValidationIssues.Cart);

            if (shippingAddress == null)
            {
                return(RedirectToCart("The shipping address is not exist"));
            }

            shipment.ShippingAddress = shippingAddress;

            var shippingMethodViewModels = _shipmentViewModelFactory.CreateShipmentsViewModel(CartWithValidationIssues.Cart).SelectMany(x => x.ShippingMethods);
            var shippingMethodViewModel  = shippingMethodViewModels.Where(x => x.Price != 0)
                                           .OrderBy(x => x.Price)
                                           .FirstOrDefault();

            //If product is virtual set shipping method is Free
            if (shipment.LineItems.FirstOrDefault().IsVirtualVariant())
            {
                shippingMethodViewModel = shippingMethodViewModels.Where(x => x.Price == 0).FirstOrDefault();
            }

            if (shippingMethodViewModel == null)
            {
                return(RedirectToCart("The shipping method is invalid"));
            }

            shipment.ShippingMethodId = shippingMethodViewModel.Id;

            var paymentAddress = (contact.PreferredBillingAddress ?? contact.ContactAddresses.FirstOrDefault())?.ConvertToOrderAddress(CartWithValidationIssues.Cart);

            if (paymentAddress == null)
            {
                return(RedirectToCart("The billing address is not exist"));
            }

            var totals = _orderGroupCalculator.GetOrderGroupTotals(CartWithValidationIssues.Cart);

            var payment = CartWithValidationIssues.Cart.CreateCardPayment();

            payment.BillingAddress         = paymentAddress;
            payment.CardType               = "Credit card";
            payment.PaymentMethodId        = new Guid("B1DA37A6-CF19-40D5-915B-B863D74D8799");
            payment.PaymentMethodName      = "GenericCreditCard";
            payment.Amount                 = CartWithValidationIssues.Cart.GetTotal().Amount;
            payment.CreditCardNumber       = creditCard.CreditCardNumber;
            payment.CreditCardSecurityCode = creditCard.SecurityCode;
            payment.ExpirationMonth        = creditCard.ExpirationMonth ?? 1;
            payment.ExpirationYear         = creditCard.ExpirationYear ?? DateTime.Now.Year;
            payment.Status                 = PaymentStatus.Pending.ToString();
            payment.CustomerName           = contact.FullName;
            payment.TransactionType        = TransactionType.Authorization.ToString();
            CartWithValidationIssues.Cart.GetFirstForm().Payments.Add(payment);

            var issues = _cartService.ValidateCart(CartWithValidationIssues.Cart);

            if (issues.Keys.Any(x => issues.HasItemBeenRemoved(x)))
            {
                return(RedirectToCart("The product is invalid"));
            }
            var order = _checkoutService.PlaceOrder(CartWithValidationIssues.Cart, new ModelStateDictionary(), new CheckoutViewModel());

            //await _checkoutService.CreateOrUpdateBoughtProductsProfileStore(CartWithValidationIssues.Cart);
            //await _checkoutService.CreateBoughtProductsSegments(CartWithValidationIssues.Cart);
            await _recommendationService.TrackOrder(HttpContext, order);

            var homePage = _contentLoader.Get <PageData>(ContentReference.StartPage) as CommerceHomePage;

            if (homePage?.OrderConfirmationPage != null)
            {
                var orderConfirmationPage = _contentLoader.Get <OrderConfirmationPage>(homePage.OrderConfirmationPage);
                var queryCollection       = new NameValueCollection
                {
                    { "contactId", contact.PrimaryKeyId?.ToString() },
                    { "orderNumber", order.OrderLink.OrderGroupId.ToString() }
                };
                var urlRedirect = new UrlBuilder(orderConfirmationPage.StaticLinkURL)
                {
                    QueryCollection = queryCollection
                };
                return(Json(new { Redirect = urlRedirect.ToString() }));
            }

            return(RedirectToCart("Something went wrong"));
        }
Пример #6
0
        public ActionResult Index(CheckoutPage currentPage, int?isGuest)
        {
            if (CartIsNullOrEmpty())
            {
                return(View("EmptyCart", new CheckoutMethodViewModel(currentPage)));
            }

            if (!Request.IsAuthenticated && (!isGuest.HasValue || isGuest.Value != 1))
            {
                return(RedirectToAction("CheckoutMethod", new { node = currentPage.ContentLink }));
            }

            if (CartWithValidationIssues.Cart.GetFirstShipment().ShippingMethodId == Guid.Empty)
            {
                _checkoutService.UpdateShippingMethods(CartWithValidationIssues.Cart, _shipmentViewModelFactory.CreateShipmentsViewModel(CartWithValidationIssues.Cart).ToList());
                _orderRepository.Save(CartWithValidationIssues.Cart);
            }

            var viewModel = CreateCheckoutViewModel(currentPage);

            viewModel.OrderSummary   = _orderSummaryViewModelFactory.CreateOrderSummaryViewModel(CartWithValidationIssues.Cart);
            viewModel.BillingAddress = _addressBookService.ConvertToModel(CartWithValidationIssues.Cart.GetFirstForm()?.Payments.FirstOrDefault()?.BillingAddress);
            _addressBookService.LoadAddress(viewModel.BillingAddress);

            if (viewModel.Shipments.Count == 1)
            {
                viewModel.BillingAddressType = 2;
            }
            else if (Request.IsAuthenticated)
            {
                viewModel.BillingAddressType = 1;
            }
            else
            {
                viewModel.BillingAddressType = 0;
            }

            var shippingAddressType = Request.IsAuthenticated ? 1 : 0;

            for (var i = 0; i < viewModel.Shipments.Count; i++)
            {
                if (string.IsNullOrEmpty(viewModel.Shipments[i].Address.AddressId))
                {
                    viewModel.Shipments[i].ShippingAddressType = shippingAddressType;
                }
                else
                {
                    viewModel.Shipments[i].ShippingAddressType = 1;
                }
            }

            if (TempData[Constant.ErrorMessages] != null)
            {
                ViewBag.ErrorMessages = (string)TempData[Constant.ErrorMessages];
            }

            return(View("Checkout", viewModel));
        }
Пример #7
0
        public virtual MultiShipmentViewModel CreateMultiShipmentViewModel(ICart cart, bool isAuthenticated)
        {
            var viewModel = new MultiShipmentViewModel
            {
                StartPage                                     = _contentLoader.Get <StartPage>(ContentReference.StartPage),
                AvailableAddresses                            = GetAvailableShippingAddresses(),
                CartItems                                     = cart != null?FlattenCartItems(_shipmentViewModelFactory.CreateShipmentsViewModel(cart).SelectMany(x => x.CartItems)) : new CartItemViewModel[0],
                                                  ReferrerUrl = GetReferrerUrl()
            };

            if (!isAuthenticated)
            {
                UpdateShippingAddressesForAnonymous(viewModel);
            }

            return(viewModel);
        }
        //public virtual MultiShipmentViewModel CreateMultiShipmentViewModel(ICart cart, MultiShipmentPage multiShipmentPage, bool isAuthenticated)
        //{
        //    var viewModel = new MultiShipmentViewModel(multiShipmentPage)
        //    {
        //        AvailableAddresses = GetAvailableShippingAddresses(cart),
        //        CartItems = cart != null ? FlattenCartItems(_shipmentViewModelFactory.CreateShipmentsViewModel(cart).SelectMany(x => x.CartItems)) : new CartItemViewModel[0],
        //        ReferrerUrl = GetReferrerUrl()
        //    };

        //    if (!isAuthenticated)
        //    {
        //        UpdateShippingAddressesForAnonymous(viewModel);
        //    }

        //    return viewModel;
        //}

        public virtual MultiAddressViewModel CreateMultiShipmentViewModel(ICart cart, CheckoutPage checkoutPage, bool isAuthenticated)
        {
            var viewModel = new MultiAddressViewModel(checkoutPage)
            {
                AvailableAddresses                            = GetAvailableShippingAddresses(cart),
                CartItems                                     = cart != null?FlattenCartItems(_shipmentViewModelFactory.CreateShipmentsViewModel(cart).SelectMany(x => x.CartItems)) : Array.Empty <CartItemViewModel>(),
                                                  ReferrerUrl = GetReferrerUrl(),
            };

            if (!isAuthenticated && !viewModel.AvailableAddresses.Any())
            {
                UpdateShippingAddressesForAnonymous(viewModel);
            }

            return(viewModel);
        }
Пример #9
0
        //[OutputCache(Duration = 0, NoStore = true)]
        public IActionResult Index(CheckoutPage currentPage, int?isGuest)
        {
            if (CartIsNullOrEmpty())
            {
                return(View("EmptyCart", new CheckoutMethodViewModel(currentPage)));
            }

            if (!HttpContext.User.Identity.IsAuthenticated && (!isGuest.HasValue || isGuest.Value != 1))
            {
                return(RedirectToAction("CheckoutMethod", new { node = currentPage.ContentLink }));
            }

            if (CartWithValidationIssues.Cart.GetFirstShipment().ShippingMethodId == Guid.Empty)
            {
                _checkoutService.UpdateShippingMethods(CartWithValidationIssues.Cart, _shipmentViewModelFactory.CreateShipmentsViewModel(CartWithValidationIssues.Cart).ToList());
                _orderRepository.Save(CartWithValidationIssues.Cart);
            }

            var viewModel = CreateCheckoutViewModel(currentPage);

            viewModel.OrderSummary   = _orderSummaryViewModelFactory.CreateOrderSummaryViewModel(CartWithValidationIssues.Cart);
            viewModel.BillingAddress = _addressBookService.ConvertToModel(CartWithValidationIssues.Cart.GetFirstForm()?.Payments.FirstOrDefault()?.BillingAddress);
            _addressBookService.LoadAddress(viewModel.BillingAddress);

            var shipmentBillingTypes = TempData["ShipmentBillingTypes"] as List <KeyValuePair <string, int> >;

            if (shipmentBillingTypes != null && shipmentBillingTypes.Any(x => x.Key == "Billing"))
            {
                viewModel.BillingAddressType = 0;
            }
            else
            {
                if (viewModel.Shipments.Count == 1)
                {
                    viewModel.BillingAddressType = 2;
                }
                else if (HttpContext.User.Identity.IsAuthenticated)
                {
                    viewModel.BillingAddressType = 1;
                }
                else
                {
                    viewModel.BillingAddressType = 0;
                }
            }

            var shippingAddressType = HttpContext.User.Identity.IsAuthenticated ? 1 : 0;

            for (var i = 0; i < viewModel.Shipments.Count; i++)
            {
                if (shipmentBillingTypes != null && shipmentBillingTypes.Where(x => x.Key == "Shipment").Any(x => x.Value == i))
                {
                    viewModel.Shipments[i].ShippingAddressType = 0;
                }
                else
                {
                    if (string.IsNullOrEmpty(viewModel.Shipments[i].Address.AddressId))
                    {
                        viewModel.Shipments[i].ShippingAddressType = shippingAddressType;
                    }
                    else
                    {
                        viewModel.Shipments[i].ShippingAddressType = 1;
                    }
                }
            }

            if (TempData[Constant.ErrorMessages] != null)
            {
                ViewBag.ErrorMessages = (string)TempData[Constant.ErrorMessages];
            }

            var tempDataState = TempData["ModelState"] as List <KeyValuePair <string, string> >;

            if (tempDataState != null)
            {
                foreach (var e in tempDataState)
                {
                    ViewData.ModelState.AddModelError(e.Key, e.Value);
                }
            }

            return(View("Checkout", viewModel));
        }