Exemplo n.º 1
0
        public ShippingOptionUpdateResponse UpdateShippingMethod(ICart cart, ShippingOptionUpdateRequest shippingOptionUpdateRequest)
        {
            var configuration = GetConfiguration(cart.Market);
            var shipment      = cart.GetFirstShipment();

            if (shipment != null && Guid.TryParse(shippingOptionUpdateRequest.SelectedShippingOption.Id, out Guid guid))
            {
                shipment.ShippingMethodId = guid;
                shipment.ShippingAddress  = shippingOptionUpdateRequest.ShippingAddress.ToOrderAddress(cart);
                _orderRepository.Save(cart);
            }

            var totals = _orderGroupTotalsCalculator.GetTotals(cart);
            var result = new ShippingOptionUpdateResponse
            {
                OrderAmount      = AmountHelper.GetAmount(totals.Total),
                OrderTaxAmount   = AmountHelper.GetAmount(totals.TaxTotal),
                OrderLines       = GetOrderLines(cart, totals, configuration.SendProductAndImageUrl),
                PurchaseCurrency = cart.Currency.CurrencyCode
            };

            if (ServiceLocator.Current.TryGetExistingInstance(out ICheckoutOrderDataBuilder checkoutOrderDataBuilder))
            {
                checkoutOrderDataBuilder.Build(result, cart, configuration);
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// When an order needs to be captured the cartridge needs to make an API Call
        /// POST /ordermanagement/v1/orders/{order_id}/captures for the amount which needs to be captured.
        ///     If it's a partial capture the API call will be the same just for the
        /// amount that should be captured. Many captures can be made up to the whole amount authorized.
        /// The shipment information can be added in this call or amended aftewards using the method
        /// "Add shipping info to a capture".
        ///     The amount captured never can be greater than the authorized.
        /// When an order is Partally Captured the status of the order in Klarna is PART_CAPTURED
        /// </summary>
        public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message)
        {
            if (payment.TransactionType == TransactionType.Capture.ToString())
            {
                var amount  = AmountHelper.GetAmount(payment.Amount);
                var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString();
                if (!string.IsNullOrEmpty(orderId))
                {
                    try
                    {
                        var captureData = KlarnaOrderService.CaptureOrder(orderId, amount, "Capture the payment", orderGroup, orderForm, payment, shipment);
                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Captured {payment.Amount}, id {captureData.CaptureId}");
                    }
                    catch (Exception ex) when(ex is ApiException || ex is WebException)
                    {
                        var exceptionMessage = GetExceptionMessage(ex);

                        payment.Status = PaymentStatus.Failed.ToString();
                        message        = exceptionMessage;
                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
                        Logger.Error(exceptionMessage, ex);
                        return(false);
                    }
                }
                return(true);
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message));
            }
            return(false);
        }
Exemplo n.º 3
0
        public AddressUpdateResponse UpdateAddress(ICart cart, AddressUpdateRequest addressUpdateRequest)
        {
            var configuration = GetConfiguration(cart.Market);
            var shipment      = cart.GetFirstShipment();

            if (shipment != null)
            {
                shipment.ShippingAddress = addressUpdateRequest.ShippingAddress.ToOrderAddress(cart);
                _orderRepository.Save(cart);
            }

            var totals = _orderGroupTotalsCalculator.GetTotals(cart);
            var result = new AddressUpdateResponse
            {
                OrderAmount      = AmountHelper.GetAmount(totals.Total),
                OrderTaxAmount   = AmountHelper.GetAmount(totals.TaxTotal),
                OrderLines       = GetOrderLines(cart, totals, configuration.SendProductAndImageUrl),
                PurchaseCurrency = cart.Currency.CurrencyCode,
                ShippingOptions  = configuration.ShippingOptionsInIFrame ? GetShippingOptions(cart, cart.Currency, ContentLanguage.PreferredCulture) : Enumerable.Empty <ShippingOption>()
            };

            if (ServiceLocator.Current.TryGetExistingInstance(out ICheckoutOrderDataBuilder checkoutOrderDataBuilder))
            {
                checkoutOrderDataBuilder.Build(result, cart, configuration);
            }
            return(result);
        }
Exemplo n.º 4
0
 public static OrderLine GetOrderLine(this ILineItem lineItem, bool includeProductAndImageUrl = false)
 {
     return(GetOrderLine(
                lineItem,
                includeProductAndImageUrl,
                AmountHelper.GetAmount(lineItem.PlacedPrice),
                AmountHelper.GetAmount(lineItem.PlacedPrice * lineItem.Quantity),
                0, 0, 0));
 }
Exemplo n.º 5
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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 7
0
        private List <OrderLine> GetOrderLinesWithTax(ICart cart, OrderGroupTotals orderGroupTotals, bool sendProductAndImageUrl)
        {
            var shipment   = cart.GetFirstShipment();
            var orderLines = new List <OrderLine>();
            var market     = _marketService.GetMarket(cart.MarketId);

            // Line items
            foreach (var lineItem in cart.GetAllLineItems())
            {
                var orderLine = lineItem.GetOrderLineWithTax(market, cart.GetFirstShipment(), cart.Currency, sendProductAndImageUrl);
                orderLines.Add(orderLine);
            }

            // Shipment
            if (shipment != null && orderGroupTotals.ShippingTotal.Amount > 0)
            {
                var shipmentOrderLine = shipment.GetOrderLine(cart, orderGroupTotals, true);
                orderLines.Add(shipmentOrderLine);
            }

            // Without tax
            var orderLevelDiscount = AmountHelper.GetAmount(cart.GetOrderDiscountTotal());

            if (orderLevelDiscount > 0)
            {
                // Order level discounts with tax
                var totalOrderAmountWithoutDiscount =
                    orderLines
                    .Sum(x => x.TotalAmount);
                var totalOrderAmountWithDiscount   = AmountHelper.GetAmount(orderGroupTotals.Total.Amount);
                var orderLevelDiscountIncludingTax = totalOrderAmountWithoutDiscount - totalOrderAmountWithDiscount;

                // Tax
                var totalTaxAmountWithoutDiscount =
                    orderLines
                    .Sum(x => x.TotalTaxAmount);
                var totalTaxAmountWithDiscount = AmountHelper.GetAmount(orderGroupTotals.TaxTotal);
                var discountTax = totalTaxAmountWithoutDiscount - totalTaxAmountWithDiscount;
                var taxRate     = discountTax * 100 / (orderLevelDiscountIncludingTax - discountTax);

                orderLines.Add(new OrderLine()
                {
                    Type           = OrderLineType.discount,
                    Name           = "Discount",
                    Quantity       = 1,
                    TotalAmount    = orderLevelDiscountIncludingTax * -1,
                    UnitPrice      = orderLevelDiscountIncludingTax * -1,
                    TotalTaxAmount = discountTax * -1,
                    TaxRate        = AmountHelper.GetAmount(taxRate)
                });
            }
            return(orderLines);
        }
Exemplo n.º 8
0
 public static ShippingOption ToShippingOption(this ShippingMethodDto.ShippingMethodRow method)
 {
     return(new ShippingOption
     {
         Id = method.ShippingMethodId.ToString(),
         Name = method.DisplayName,
         Price = AmountHelper.GetAmount(method.BasePrice),
         PreSelected = method.IsDefault,
         TaxAmount = 0,
         TaxRate = 0,
         Description = method.Description
     });
 }
Exemplo n.º 9
0
        private List <OrderLine> GetOrderLinesWithoutTax(ICart cart, OrderGroupTotals orderGroupTotals, bool sendProductAndImageUrl)
        {
            var shipment   = cart.GetFirstShipment();
            var orderLines = new List <OrderLine>();

            // Line items
            foreach (var lineItem in cart.GetAllLineItems())
            {
                var orderLine = lineItem.GetOrderLine(sendProductAndImageUrl);
                orderLines.Add(orderLine);
            }

            // Shipment
            if (shipment != null && orderGroupTotals.ShippingTotal.Amount > 0)
            {
                var shipmentOrderLine = shipment.GetOrderLine(cart, orderGroupTotals, false);
                orderLines.Add(shipmentOrderLine);
            }

            // Sales tax
            orderLines.Add(new PatchedOrderLine()
            {
                Type           = "sales_tax",
                Name           = "Sales Tax",
                Quantity       = 1,
                TotalAmount    = AmountHelper.GetAmount(orderGroupTotals.TaxTotal),
                UnitPrice      = AmountHelper.GetAmount(orderGroupTotals.TaxTotal),
                TotalTaxAmount = 0,
                TaxRate        = 0
            });

            // Order level discounts
            var orderDiscount      = cart.GetOrderDiscountTotal(cart.Currency);
            var entryLevelDiscount = cart.GetAllLineItems().Sum(x => x.GetEntryDiscount());
            var totalDiscount      = orderDiscount.Amount + entryLevelDiscount;

            if (totalDiscount > 0)
            {
                orderLines.Add(new PatchedOrderLine()
                {
                    Type           = "discount",
                    Name           = "Discount",
                    Quantity       = 1,
                    TotalAmount    = -AmountHelper.GetAmount(totalDiscount),
                    UnitPrice      = -AmountHelper.GetAmount(totalDiscount),
                    TotalTaxAmount = 0,
                    TaxRate        = 0
                });
            }
            return(orderLines);
        }
Exemplo n.º 10
0
        public static Prices GetPrices(ILineItem lineItem, IMarket market, IShipment shipment, Currency currency)
        {
            /*
             * unit_price integer required
             *  Minor units. Includes tax, excludes discount. (max value: 100000000)
             * tax_rate integer required
             *  Non-negative. In percent, two implicit decimals. I.e 2500 = 25%.
             * total_amount integer required
             *  Includes tax and discount. Must match (quantity * unit_price) - total_discount_amount within �quantity. (max value: 100000000)
             * total_tax_amount integer required
             *  Must be within �1 of total_amount - total_amount * 10000 / (10000 + tax_rate). Negative when type is discount.
             * total_discount_amount integer
             *  Non - negative minor units. Includes tax.
             */
            var taxType = TaxType.SalesTax;

            // All excluding tax
            var unitPrice = lineItem.PlacedPrice;
            var totalPriceWithoutDiscount = lineItem.PlacedPrice * lineItem.Quantity;
            var extendedPrice             = lineItem.GetDiscountedPrice(currency);
            var discountAmount            = (totalPriceWithoutDiscount - extendedPrice);

            // Tax value
            var taxValues     = _lineItemTaxCalculator.Service.GetTaxValuesForLineItem(lineItem, market, shipment);
            var taxPercentage = taxValues
                                .Where(x => x.TaxType == taxType)
                                .Sum(x => (decimal)x.Percentage);

            // Using ITaxCalculator instead of ILineItemCalculator because ILineItemCalculator
            // calculates tax from the price which includes order discount amount and line item discount amount
            // but should use only line item discount amount
            var salesTax =
                _taxCalculator.Service.GetSalesTax(lineItem, market, shipment.ShippingAddress, extendedPrice);

            // Includes tax, excludes discount. (max value: 100000000)
            var unitPriceIncludingTax = AmountHelper.GetAmount(
                _lineItemTaxCalculator.Service.PriceIncludingTaxPercent(unitPrice, taxPercentage, market));
            // Non - negative minor units. Includes tax
            var totalDiscountAmount = AmountHelper.GetAmount(
                _lineItemTaxCalculator.Service.PriceIncludingTaxPercent(discountAmount, taxPercentage, market));
            // Includes tax and discount. Must match (quantity * unit_price) - total_discount_amount within quantity. (max value: 100000000)
            var totalAmount = AmountHelper.GetAmount(
                _lineItemTaxCalculator.Service.PriceIncludingTaxAmount(extendedPrice, salesTax.Amount, market));
            // Non-negative. In percent, two implicit decimals. I.e 2500 = 25%.
            var taxRate = AmountHelper.GetAmount(taxPercentage);
            // Must be within 1 of total_amount - total_amount * 10000 / (10000 + tax_rate). Negative when type is discount.
            var totalTaxAmount = AmountHelper.GetAmount(salesTax.Amount);

            return(new Prices(unitPriceIncludingTax, taxRate, totalDiscountAmount, totalAmount, totalTaxAmount));
        }
Exemplo n.º 11
0
#pragma warning restore 649

        public static OrderLine GetOrderLine(this IShipment shipment, ICart cart, OrderGroupTotals totals, bool includeTaxes)
        {
            var total          = AmountHelper.GetAmount(totals.ShippingTotal);
            var totalTaxAmount = 0;
            var taxRate        = 0;

            if (includeTaxes)
            {
                var market           = _marketService.Service.GetMarket(cart.MarketId);
                var shippingTaxTotal = _shippingCalculator.Service.GetShippingTax(shipment, market, cart.Currency);

                if (shippingTaxTotal.Amount > 0)
                {
                    totalTaxAmount = AmountHelper.GetAmount(shippingTaxTotal.Amount);

                    var shippingTotalExcludingTax = market.PricesIncludeTax
                        ? totals.ShippingTotal.Amount - shippingTaxTotal.Amount
                        : totals.ShippingTotal.Amount;
                    taxRate = AmountHelper.GetAmount(shippingTaxTotal.Amount * 100 / shippingTotalExcludingTax);

                    if (!market.PricesIncludeTax)
                    {
                        total = total + totalTaxAmount;
                    }
                }
            }

            var shipmentOrderLine = new OrderLine
            {
                Name           = shipment.ShippingMethodName,
                Quantity       = 1,
                UnitPrice      = total,
                TotalAmount    = total,
                TaxRate        = taxRate,
                TotalTaxAmount = totalTaxAmount,
                Type           = OrderLineType.shipping_fee
            };

            if (string.IsNullOrEmpty(shipmentOrderLine.Name))
            {
                var shipmentMethod = Mediachase.Commerce.Orders.Managers.ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                     .ShippingMethod.FirstOrDefault();
                if (shipmentMethod != null)
                {
                    shipmentOrderLine.Name = shipmentMethod.DisplayName;
                }
            }
            return(shipmentOrderLine);
        }
        public void GetAmount_Should_ReturnDynamicRewardForFriendMention()
        {
            _statServiceMock.Setup(x => x.GetPreviousDayStat()).Returns(new Stat
            {
                Id = 1,
                TotalWithdrawals = 333,
                NewUsers         = 190,
                WithdrawalAmount = 2233.5m
            });

            var amountHelper = new AmountHelper(_appSettings, _statServiceMock.Object);
            var reward       = amountHelper.GetAmount(RewardType.FriendMention);

            Assert.True(reward < _appSettings.BotSettings.AmountForTweetWithFriendMention);
        }
        public void GetAmount_Should_ReturnFixedRewardForTag()
        {
            _statServiceMock.Setup(x => x.GetPreviousDayStat()).Returns(new Stat
            {
                Id = 1,
                TotalWithdrawals = 1,
                NewUsers         = 190,
                WithdrawalAmount = 12.5m
            });

            var amountHelper = new AmountHelper(_appSettings, _statServiceMock.Object);
            var reward       = amountHelper.GetAmount(RewardType.Tag);

            Assert.True(reward == _appSettings.BotSettings.AmountForTweetWithTag);
        }
Exemplo n.º 14
0
        public static (int unitPrice, int taxRate, int totalDiscountAmount, int totalAmount, int totalTaxAmount) GetPrices(ILineItem lineItem, IMarket market, IShipment shipment, Currency currency)
        {
            /*
             * unit_price integer required
             *  Minor units. Includes tax, excludes discount. (max value: 100000000)
             * tax_rate integer required
             *  Non-negative. In percent, two implicit decimals. I.e 2500 = 25%.
             * total_amount integer required
             *  Includes tax and discount. Must match (quantity * unit_price) - total_discount_amount within �quantity. (max value: 100000000)
             * total_tax_amount integer required
             *  Must be within �1 of total_amount - total_amount * 10000 / (10000 + tax_rate). Negative when type is discount.
             * total_discount_amount integer
             *  Non - negative minor units. Includes tax.
             */
            var taxType = TaxType.SalesTax;

            // All excluding tax
            var unitPrice = lineItem.PlacedPrice;
            var totalPriceWithoutDiscount = lineItem.PlacedPrice * lineItem.Quantity;
            var extendedPrice             = lineItem.GetDiscountedPrice(currency).Amount;
            var discountAmount            = (totalPriceWithoutDiscount - extendedPrice);

            // Tax value
            var taxValues     = _lineItemTaxCalculator.Service.GetTaxValuesForLineItem(lineItem, market, shipment);
            var taxPercentage = taxValues
                                .Where(x => x.TaxType == taxType)
                                .Sum(x => (decimal)x.Percentage);

            // Includes tax, excludes discount. (max value: 100000000)
            var unitPriceIncludingTax = AmountHelper.GetAmount(_lineItemTaxCalculator.Service.PriceIncludingTax(unitPrice, taxValues, taxType));
            // Non - negative minor units. Includes tax
            int totalDiscountAmount = AmountHelper.GetAmount(_lineItemTaxCalculator.Service.PriceIncludingTax(discountAmount, taxValues, taxType));
            // Includes tax and discount. Must match (quantity * unit_price) - total_discount_amount within quantity. (max value: 100000000)
            var totalAmount = AmountHelper.GetAmount(_lineItemTaxCalculator.Service.PriceIncludingTax(extendedPrice, taxValues, taxType));
            // Non-negative. In percent, two implicit decimals. I.e 2500 = 25%.
            var taxRate = AmountHelper.GetAmount(taxPercentage);
            // Must be within 1 of total_amount - total_amount * 10000 / (10000 + tax_rate). Negative when type is discount.
            var totalTaxAmount = AmountHelper.GetAmount(_lineItemTaxCalculator.Service.GetTaxes(extendedPrice, taxValues, taxType));

            return(unitPriceIncludingTax, taxRate, totalDiscountAmount, totalAmount, totalTaxAmount);
        }
Exemplo n.º 15
0
#pragma warning restore 649

        public static PatchedOrderLine GetOrderLine(this IShipment shipment, ICart cart, OrderGroupTotals totals, bool includeTaxes)
        {
            var total          = AmountHelper.GetAmount(totals.ShippingTotal);
            var totalTaxAmount = 0;
            var taxRate        = 0;

            if (includeTaxes)
            {
                var shippingTaxTotal = _taxCalculator.Service.GetShippingTaxTotal(shipment, cart.Market, cart.Currency);

                if (shippingTaxTotal.Amount > 0)
                {
                    totalTaxAmount = AmountHelper.GetAmount(shippingTaxTotal.Amount);
                    taxRate        = AmountHelper.GetAmount((shippingTaxTotal.Amount / totals.ShippingTotal.Amount) * 100);

                    total = total + totalTaxAmount;
                }
            }

            var shipmentOrderLine = new PatchedOrderLine
            {
                Name           = shipment.ShippingMethodName,
                Quantity       = 1,
                UnitPrice      = total,
                TotalAmount    = total,
                TaxRate        = taxRate,
                TotalTaxAmount = totalTaxAmount,
                Type           = "shipping_fee"
            };

            if (string.IsNullOrEmpty(shipmentOrderLine.Name))
            {
                var shipmentMethod = Mediachase.Commerce.Orders.Managers.ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                     .ShippingMethod.FirstOrDefault();
                if (shipmentMethod != null)
                {
                    shipmentOrderLine.Name = shipmentMethod.DisplayName;
                }
            }
            return(shipmentOrderLine);
        }
Exemplo n.º 16
0
        public virtual ShippingOptionUpdateResponse UpdateShippingMethod(ICart cart, ShippingOptionUpdateRequest shippingOptionUpdateRequest)
        {
            var configuration      = GetConfiguration(cart.MarketId);
            var shipment           = cart.GetFirstShipment();
            var validationIssues   = new Dictionary <ILineItem, List <ValidationIssue> >();
            var rewardDescriptions = Enumerable.Empty <RewardDescription>();

            if (shipment != null && Guid.TryParse(shippingOptionUpdateRequest.SelectedShippingOption.Id, out Guid guid))
            {
                shipment.ShippingAddress  = shippingOptionUpdateRequest.ShippingCheckoutAddress.ToOrderAddress(cart);
                shipment.ShippingMethodId = guid;
                validationIssues          = _klarnaCartValidator.ValidateCart(cart);
                rewardDescriptions        = _klarnaCartValidator.ApplyDiscounts(cart);
                _orderRepository.Save(cart);
            }

            var totals = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var result = new ShippingOptionUpdateResponse
            {
                OrderAmount      = AmountHelper.GetAmount(totals.Total),
                OrderTaxAmount   = AmountHelper.GetAmount(totals.TaxTotal),
                OrderLines       = GetOrderLines(cart, totals, configuration.SendProductAndImageUrl),
                PurchaseCurrency = cart.Currency.CurrencyCode,
                ShippingOptions  = configuration.ShippingOptionsInIFrame
                    ? GetShippingOptions(cart, cart.Currency)
                    : Enumerable.Empty <ShippingOption>(),
                ValidationIssues   = validationIssues,
                RewardDescriptions = rewardDescriptions
            };

            if (ServiceLocator.Current.TryGetExistingInstance(out ICheckoutOrderDataBuilder checkoutOrderDataBuilder))
            {
                checkoutOrderDataBuilder.Build(result, cart, configuration);
            }

            return(result);
        }
Exemplo n.º 17
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);
        }