/// <summary>
        /// Initialize a payment request from an <see cref="OrderGroup"/> instance. Adds order number, amount, timestamp, buyer information etc.
        /// </summary>
        /// <param name="payment">The <see cref="VerifonePaymentRequest"/> instance to initialize</param>
        /// <param name="orderGroup"><see cref="OrderGroup"/></param>
        public virtual void InitializePaymentRequest(VerifonePaymentRequest payment, IOrderGroup orderGroup)
        {
            IOrderAddress billingAddress  = FindBillingAddress(payment, orderGroup);
            IOrderAddress shipmentAddress = FindShippingAddress(payment, orderGroup);

            payment.OrderTimestamp        = orderGroup.Created.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            payment.MerchantAgreementCode = GetMerchantAgreementCode(payment);
            payment.PaymentLocale         = GetPaymentLocale(ContentLanguage.PreferredCulture);
            payment.OrderNumber           = orderGroup.OrderLink.OrderGroupId.ToString(CultureInfo.InvariantCulture.NumberFormat);

            payment.OrderCurrencyCode = IsProduction(payment)
                ? Iso4217Lookup.LookupByCode(CurrentMarket.DefaultCurrency.CurrencyCode).Number.ToString()
                : "978";

            var totals = OrderGroupCalculator.GetOrderGroupTotals(orderGroup);

            payment.OrderGrossAmount = totals.Total.ToVerifoneAmountString();

            var netAmount = orderGroup.PricesIncludeTax ? totals.Total : totals.Total - totals.TaxTotal;

            payment.OrderNetAmount = netAmount.ToVerifoneAmountString();
            payment.OrderVatAmount = totals.TaxTotal.ToVerifoneAmountString();

            payment.BuyerFirstName       = billingAddress?.FirstName;
            payment.BuyerLastName        = billingAddress?.LastName;
            payment.OrderVatPercentage   = "0";
            payment.PaymentMethodCode    = "";
            payment.SavedPaymentMethodId = "";
            payment.RecurringPayment     = "0";
            payment.DeferredPayment      = "0";
            payment.SavePaymentMethod    = "0";
            payment.SkipConfirmationPage = "0";

            string phoneNumber = billingAddress?.DaytimePhoneNumber ?? billingAddress?.EveningPhoneNumber;

            if (string.IsNullOrWhiteSpace(phoneNumber) == false)
            {
                payment.BuyerPhoneNumber = phoneNumber;
            }

            payment.BuyerEmailAddress = billingAddress?.Email ?? orderGroup.Name ?? string.Empty;

            if (payment.BuyerEmailAddress.IndexOf('@') < 0)
            {
                payment.BuyerEmailAddress = null;
            }

            payment.DeliveryAddressLineOne = shipmentAddress?.Line1;

            if (shipmentAddress != null && string.IsNullOrWhiteSpace(shipmentAddress.Line2) == false)
            {
                payment.DeliveryAddressLineTwo = shipmentAddress.Line2;
            }

            payment.DeliveryAddressPostalCode  = shipmentAddress?.PostalCode;
            payment.DeliveryAddressCity        = shipmentAddress?.City;
            payment.DeliveryAddressCountryCode = "246";

            ApplyPaymentMethodConfiguration(payment);
        }
        public virtual LargeCartViewModel CreateSimpleLargeCartViewModel(ICart cart)
        {
            if (cart == null)
            {
                var zeroAmount = new Money(0, _currencyService.GetCurrentCurrency());
                return(new LargeCartViewModel()
                {
                    TotalDiscount = zeroAmount,
                    Total = zeroAmount,
                    TaxTotal = zeroAmount,
                    ShippingTotal = zeroAmount,
                    Subtotal = zeroAmount,
                });
            }

            var totals                = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var orderDiscountTotal    = _orderGroupCalculator.GetOrderDiscountTotal(cart);
            var shippingDiscountTotal = cart.GetShippingDiscountTotal();
            var discountTotal         = shippingDiscountTotal + orderDiscountTotal;

            var model = new LargeCartViewModel()
            {
                TotalDiscount = discountTotal,
                Total         = totals.Total,
                ShippingTotal = totals.ShippingTotal,
                Subtotal      = totals.SubTotal,
                TaxTotal      = totals.TaxTotal,
                ReferrerUrl   = GetReferrerUrl(),
            };

            return(model);
        }
Exemple #3
0
        private CheckoutOrderData GetCheckoutOrderData(
            ICart cart, IMarket market, PaymentMethodDto paymentMethodDto)
        {
            var totals        = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var shipment      = cart.GetFirstShipment();
            var marketCountry = CountryCodeHelper.GetTwoLetterCountryCode(market.Countries.FirstOrDefault());

            if (string.IsNullOrWhiteSpace(marketCountry))
            {
                throw new ConfigurationException($"Please select a country in CM for market {cart.MarketId}");
            }
            var checkoutConfiguration = GetCheckoutConfiguration(market);

            var orderData = new PatchedCheckoutOrderData
            {
                PurchaseCountry  = marketCountry,
                PurchaseCurrency = cart.Currency.CurrencyCode,
                Locale           = ContentLanguage.PreferredCulture.Name,
                // Non-negative, minor units. Total amount of the order, including tax and any discounts.
                OrderAmount = AmountHelper.GetAmount(totals.Total),
                // Non-negative, minor units. The total tax amount of the order.
                OrderTaxAmount = AmountHelper.GetAmount(totals.TaxTotal),
                MerchantUrls   = GetMerchantUrls(cart),
                OrderLines     = GetOrderLines(cart, totals, checkoutConfiguration.SendProductAndImageUrl)
            };

            if (checkoutConfiguration.SendShippingCountries)
            {
                orderData.ShippingCountries = GetCountries().ToList();
            }

            // KCO_6 Setting to let the user select shipping options in the iframe
            if (checkoutConfiguration.SendShippingOptionsPriorAddresses)
            {
                if (checkoutConfiguration.ShippingOptionsInIFrame)
                {
                    orderData.ShippingOptions = GetShippingOptions(cart, cart.Currency, ContentLanguage.PreferredCulture);
                }
                else
                {
                    if (shipment != null)
                    {
                        orderData.SelectedShippingOption = ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                                           ?.ShippingMethod?.FirstOrDefault()
                                                           ?.ToShippingOption();
                    }
                }
            }

            if (paymentMethodDto != null)
            {
                orderData.Options = GetOptions(cart.MarketId);
            }
            return(orderData);
        }
        protected virtual OmniumOrderTotals GetOrderFormTotals(
            IPurchaseOrder purchaseOrder, IMarket market, Currency currency, IEnumerable <OmniumShipment> shipments)
        {
            var orderGroupTotals = _orderGroupCalculator.GetOrderGroupTotals(purchaseOrder);

            var totalShipping         = new Money(shipments.Sum(s => s.ShippingSubTotal), currency);
            var totalShippingTax      = new Money(shipments.Sum(x => x.ShippingTax), currency);
            var totalLineItems        = new Money(shipments.Sum(s => s.LineItems.Sum(l => l.ExtendedPrice)), currency);
            var totalLineItemsExclTax = new Money(shipments.Sum(s => s.LineItems.Sum(l => l.ExtendedPriceExclTax)), currency);

            return(new OmniumOrderTotals(currency)
            {
                ShippingDiscounts = new Money(shipments.Sum(x => x.ShippingDiscountAmount), currency),
                OrderDiscounts = _orderGroupCalculator.GetOrderDiscountTotal(purchaseOrder),
                Handling = orderGroupTotals.HandlingTotal,
                // total shipping costs
                Shipping = totalShipping,
                // total shipping costs excl tax
                ShippingExclTax = totalShipping - totalShippingTax,
                // total line item prices (extended price)
                SubTotal = totalLineItems,
                // total line items prices exl tax (ExtendedPriceExclTax)
                SubTotalExclTax = totalLineItemsExclTax,
                // total taxes
                TaxTotal = orderGroupTotals.TaxTotal,
                // total incl taxes
                Total = orderGroupTotals.Total,
                // total excl taxes
                TotalExclTax = orderGroupTotals.Total - orderGroupTotals.TaxTotal // new Money(orderGroupTotals.Total - (totalShipmentTax + totalLineItemTax), currency) // total - (shipment tax + lineItems tax)
            });
        }
        public virtual OrderSummaryViewModel CreateOrderSummaryViewModel(ICart cart)
        {
            if (cart == null)
            {
                return(CreateEmptyOrderSummaryViewModel());
            }

            var totals = _orderGroupCalculator.GetOrderGroupTotals(cart);

            return(new OrderSummaryViewModel
            {
                SubTotal = totals.SubTotal,
                CartTotal = totals.Total,
                ShippingTotal = totals.ShippingTotal,
                ShippingSubtotal = cart.GetShippingSubTotal(_orderGroupCalculator),
                OrderDiscountTotal = cart.GetOrderDiscountTotal(_orderGroupCalculator),
                ShippingDiscountTotal = cart.GetShippingDiscountTotal(),
                ShippingTaxTotal = totals.ShippingTotal + totals.TaxTotal,
                TaxTotal = totals.TaxTotal,
                OrderDiscounts = cart.GetFirstForm().Promotions.Where(x => x.DiscountType == DiscountType.Order).Select(x => new OrderDiscountViewModel
                {
                    Discount = new Money(x.SavedAmount, new Currency(cart.Currency)),
                    DisplayName = x.Description
                })
            });
        }
Exemple #6
0
        private Session GetSessionRequest(ICart cart, PaymentsConfiguration config, Uri siteUrl, bool includePersonalInformation = false)
        {
            var market  = _marketService.GetMarket(cart.MarketId);
            var totals  = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var request = new Session
            {
                PurchaseCountry = CountryCodeHelper.GetTwoLetterCountryCode(market.Countries.FirstOrDefault()),
                OrderAmount     = AmountHelper.GetAmount(totals.Total),
                // Non-negative, minor units. The total tax amount of the order.
                OrderTaxAmount   = AmountHelper.GetAmount(totals.TaxTotal),
                PurchaseCurrency = cart.Currency.CurrencyCode,
                Locale           = _languageService.GetPreferredCulture().Name,
                OrderLines       = GetOrderLines(cart, totals, config.SendProductAndImageUrlField).ToArray()
            };

            var paymentMethod = PaymentManager.GetPaymentMethodBySystemName(
                Constants.KlarnaPaymentSystemKeyword, _languageService.GetPreferredCulture().Name, returnInactive: true);

            if (paymentMethod != null)
            {
                request.MerchantUrl = new MerchantUrl
                {
                    Confirmation = ToFullSiteUrl(siteUrl, config.ConfirmationUrl),
                    Notification = ToFullSiteUrl(siteUrl, config.NotificationUrl),
                };
                request.Options     = GetWidgetOptions(paymentMethod, cart.MarketId);
                request.AutoCapture = config.AutoCapture;
            }

            if (includePersonalInformation)
            {
                var shipment = cart.GetFirstShipment();
                var payment  = cart.GetFirstForm()?.Payments.FirstOrDefault();

                if (shipment?.ShippingAddress != null)
                {
                    request.ShippingAddress = shipment.ShippingAddress.ToAddress();
                }
                if (payment?.BillingAddress != null)
                {
                    request.BillingAddress = payment.BillingAddress.ToAddress();
                }
                else if (request.ShippingAddress != null)
                {
                    request.BillingAddress = new OrderManagementAddressInfo()
                    {
                        Email = request.ShippingAddress?.Email,
                        Phone = request.ShippingAddress?.Phone
                    };
                }
            }
            return(request);
        }
        protected OrderConfirmationViewModel <T> CreateViewModel(T currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <T> {
                    CurrentPage = currentPage
                });
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupTotalsCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <T>
            {
                Currency                = order.Currency,
                CurrentPage             = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = _customerContext.CurrentContactId,
                Payments                = order.GetFirstForm().Payments,
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total
            };

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
Exemple #8
0
        private OrderConfirmationViewModel <OrderConfirmationMailPage> CreateViewModel(OrderConfirmationMailPage currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <OrderConfirmationMailPage>(currentPage));
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <OrderConfirmationMailPage>(currentPage)
            {
                Currency                = order.Currency,
                CurrentContent          = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = _customerService.CurrentContactId,
                Payments                = order.GetFirstForm().Payments.Where(c => c.TransactionType == TransactionType.Authorization.ToString() || c.TransactionType == TransactionType.Sale.ToString()),
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total,
                SubTotal                = order.GetSubTotal()
            };

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
        public async Task <CartContentResponce> Handle(CartContentRequest request, CancellationToken cancellationToken)
        {
            var cart = _cartFactory.LoadOrCreateCart();

            var allLineItems  = cart.GetAllLineItems();
            var lineItemCodes = allLineItems.Select(x => x.Code).Distinct();
            var variants      = _contentLoader.GetItems(_referenceConverter.GetContentLinks(lineItemCodes).Select(x => x.Value), new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            }).OfType <MovieVariant>();
            var prices    = _customerPriceService.GetPrices(variants.Select(x => x.Code)).ToDictionary(x => x.CatalogKey.CatalogEntryCode, x => x);
            var discounts = _customerPriceService.GetDiscountPrices(variants.Select(x => x.ContentLink)).ToDictionary(x => x.EntryLink, x => x);
            var products  = variants.Select(
                x => new
            {
                variant = x.ContentLink,
                product = _contentLoader.GetItems(x.GetParentProducts(), new LoaderOptions {
                    LanguageLoaderOption.FallbackWithMaster()
                }).OfType <MovieProduct>()
            }).ToDictionary(x => x.variant, x => x.product.FirstOrDefault());

            var lineItems = cart.GetAllLineItems().Select(x => new LineItem()
            {
                Code             = x.Code,
                DisplayName      = x.DisplayName,
                Quantity         = Convert.ToInt32(x.Quantity),
                ImageUrl         = "",//products[variants.Where(y => y.Code == x.Code).Select(y => y.ContentLink).First()].PosterPath,
                Price            = prices[x.Code].UnitPrice.ToString(),
                DiscountPrice    = discounts[variants.First(y => y.Code == x.Code).ContentLink].DiscountPrices.Last().Price.ToString(),
                ProductReference = products[variants.Where(y => y.Code == x.Code).Select(y => y.ContentLink).First()].ContentLink
            });

            var total            = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var tax              = _orderGroupCalculator.GetTaxTotal(cart);
            var orderDiscount    = _orderGroupCalculator.GetOrderDiscountTotal(cart);
            var lineItemDiscount = new Money(cart.GetAllLineItems().Sum(x => x.GetEntryDiscount()), cart.Currency);
            var noDiscount       = new Money(allLineItems.Sum(x => prices[x.Code].UnitPrice.Amount * x.Quantity), cart.Currency);
            var model            = new CartContentResponce()
            {
                LineItems     = lineItems,
                Total         = total.Total.ToString(),
                ItemsDiscount = lineItemDiscount.ToString(),
                OrderDiscount = orderDiscount.ToString(),
                NoDiscount    = noDiscount.ToString()
            };

            return(await Task.FromResult(model));
        }
        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"));
        }
Exemple #11
0
        protected OrderConfirmationViewModel <T> CreateViewModel(T currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <T>(currentPage));
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <T>(currentPage)
            {
                Currency                = order.Currency,
                CurrentContent          = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = PrincipalInfo.CurrentPrincipal.GetContactId(),
                Payments                = order.GetFirstForm().Payments.Where(c => c.TransactionType == TransactionType.Authorization.ToString() || c.TransactionType == TransactionType.Sale.ToString()),
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total,
                SubTotal                = order.GetSubTotal(),
                FileUrls                = new List <Dictionary <string, string> >(),
                Keys = new List <Dictionary <string, string> >()
            };

            foreach (var lineItem in lineItems)
            {
                var entry   = lineItem.GetEntryContent <EntryContentBase>();
                var variant = entry as GenericVariant;
                if (entry == null || variant == null || variant.VirtualProductMode == null || variant.VirtualProductMode.Equals("None"))
                {
                    continue;
                }

                if (variant.VirtualProductMode.Equals("File"))
                {
                    var url = "";// _urlResolver.GetUrl(((FileVariant)lineItem.GetEntryContentBase()).File);
                    viewModel.FileUrls.Add(new Dictionary <string, string>()
                    {
                        { lineItem.DisplayName, url }
                    });
                }
                else if (variant.VirtualProductMode.Equals("Key"))
                {
                    var key = Guid.NewGuid().ToString();
                    viewModel.Keys.Add(new Dictionary <string, string>()
                    {
                        { lineItem.DisplayName, key }
                    });
                }
                else if (variant.VirtualProductMode.Equals("ElevatedRole"))
                {
                    viewModel.ElevatedRole = variant.VirtualProductRole;
                    var currentContact = _customerService.GetCurrentContact();
                    if (currentContact != null)
                    {
                        currentContact.ElevatedRole = ElevatedRoles.Reader.ToString();
                        currentContact.SaveChanges();
                    }
                }
            }

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
Exemple #12
0
        public virtual PaymentOrderUpdateRequest GetUpdateRequest(IOrderGroup orderGroup)
        {
            var totals = _orderGroupCalculator.GetOrderGroupTotals(orderGroup);

            return(new PaymentOrderUpdateRequest(Amount.FromDecimal(totals.Total.Amount), Amount.FromDecimal(totals.TaxTotal)));
        }
Exemple #13
0
        protected virtual CheckoutOrder GetCheckoutOrderData(
            ICart cart, IMarket market, PaymentMethodDto paymentMethodDto)
        {
            var totals        = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var shipment      = cart.GetFirstShipment();
            var marketCountry = CountryCodeHelper.GetTwoLetterCountryCode(market.Countries.FirstOrDefault());

            if (string.IsNullOrWhiteSpace(marketCountry))
            {
                throw new ConfigurationException($"Please select a country in CM for market {cart.MarketId}");
            }
            var checkoutConfiguration = GetCheckoutConfiguration(market);

            var orderData = new CheckoutOrder
            {
                PurchaseCountry  = marketCountry,
                PurchaseCurrency = cart.Currency.CurrencyCode,
                Locale           = _languageService.ConvertToLocale(Thread.CurrentThread.CurrentCulture.Name),
                // Non-negative, minor units. Total amount of the order, including tax and any discounts.
                OrderAmount = AmountHelper.GetAmount(totals.Total),
                // Non-negative, minor units. The total tax amount of the order.
                OrderTaxAmount = AmountHelper.GetAmount(totals.TaxTotal),
                MerchantUrls   = GetMerchantUrls(cart),
                OrderLines     = GetOrderLines(cart, totals, checkoutConfiguration.SendProductAndImageUrl)
            };

            if (checkoutConfiguration.SendShippingCountries)
            {
                orderData.ShippingCountries = GetCountries().ToList();
            }

            // KCO_6 Setting to let the user select shipping options in the iframe
            if (checkoutConfiguration.SendShippingOptionsPriorAddresses)
            {
                if (checkoutConfiguration.ShippingOptionsInIFrame)
                {
                    orderData.ShippingOptions = GetShippingOptions(cart, cart.Currency).ToList();
                }
                else
                {
                    if (shipment != null)
                    {
                        orderData.SelectedShippingOption = ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                                           ?.ShippingMethod?.FirstOrDefault()
                                                           ?.ToShippingOption();
                    }
                }
            }

            if (paymentMethodDto != null)
            {
                orderData.CheckoutOptions = GetOptions(cart.MarketId);
            }

            if (checkoutConfiguration.PrefillAddress)
            {
                // KCO_4: In case of signed in user the email address and default address details will be prepopulated by data from Merchant system.
                var customerContact = CustomerContext.Current.GetContactById(cart.CustomerId);
                if (customerContact?.PreferredBillingAddress != null)
                {
                    orderData.BillingCheckoutAddress = customerContact.PreferredBillingAddress.ToAddress();
                }

                if (orderData.CheckoutOptions.AllowSeparateShippingAddress)
                {
                    if (customerContact?.PreferredShippingAddress != null)
                    {
                        orderData.ShippingCheckoutAddress = customerContact.PreferredShippingAddress.ToAddress();
                    }

                    if (shipment?.ShippingAddress != null)
                    {
                        orderData.ShippingCheckoutAddress = shipment.ShippingAddress.ToCheckoutAddress();
                    }
                }
            }

            return(orderData);
        }