Example #1
0
        public IActionResult ConfirmSave()
        {
            if (!CanCheckout(out Cart cart))
            {
                return(R.Fail.With("error", T("An error occurred while checking out")).Result);
            }
            var shippingRequired = CartHelper.IsShippingRequired(cart);

            if (cart.BillingAddressId == 0 || cart.ShippingAddressId == 0 && shippingRequired)
            {
                return(R.Fail.With("error", T("The address details were not provided")).Result);
            }

            if (cart.ShippingMethodName.IsNullEmptyOrWhiteSpace() && shippingRequired)
            {
                return(R.Fail.With("error", T("The shipping details were not provided.")).Result);
            }

            if (CartHelper.IsPaymentRequired(cart) && cart.PaymentMethodName.IsNullEmptyOrWhiteSpace() && !cart.UseStoreCredits)
            {
                return(R.Fail.With("error", T("The payment method was not provided")).Result);
            }

            if (shippingRequired)
            {
                //validate shipping method
                var shippingHandler = PluginHelper.GetShipmentHandler(cart.ShippingMethodName);
                if (shippingHandler == null || !shippingHandler.IsMethodAvailable(cart))
                {
                    return(R.Fail.With("error", T("Shipping method unavailable")).Result);
                }
            }


            var currentUser = ApplicationEngine.CurrentUser;
            var order       = new Order()
            {
                PaymentMethodName         = cart.PaymentMethodName,
                PaymentMethodDisplayName  = cart.PaymentMethodDisplayName,
                ShippingMethodName        = cart.ShippingMethodName,
                ShippingMethodDisplayName = cart.ShippingMethodDisplayName,
                SelectedShippingOption    = cart.SelectedShippingOption,
                CreatedOn         = DateTime.UtcNow,
                DiscountId        = cart.DiscountCouponId,
                Guid              = Guid.NewGuid().ToString(),
                UserId            = cart.UserId,
                PaymentStatus     = PaymentStatus.Pending,
                OrderStatus       = OrderStatus.New,
                DiscountCoupon    = cart.DiscountCoupon?.CouponCode,
                Discount          = cart.Discount + cart.CartItems.Sum(x => x.Discount),
                PaymentMethodFee  = cart.PaymentMethodFee,
                ShippingMethodFee = cart.ShippingFee,
                Tax            = cart.CartItems.Sum(x => x.Tax),
                UserIpAddress  = WebHelper.GetClientIpAddress(),
                CurrencyCode   = ApplicationEngine.BaseCurrency.IsoCode,
                Subtotal       = cart.FinalAmount - cart.CartItems.Sum(x => x.Tax),
                ExchangeRate   = ApplicationEngine.BaseCurrency.ExchangeRate,
                DisableReturns = cart.CartItems.All(x => !x.Product.AllowReturns),
                User           = currentUser,
                IsSubscription = CartHelper.IsSubscriptionCart(cart),
                StoreId        = CurrentStore.Id
            };

            order.OrderTotal = order.Subtotal + order.Tax + (order.PaymentMethodFee ?? 0) + (order.ShippingMethodFee ?? 0) - order.Discount;
            //load the addresses
            var addressIds = new List <int>()
            {
                cart.BillingAddressId, cart.ShippingAddressId
            };
            var addresses       = _addressService.Get(x => addressIds.Contains(x.Id)).ToList();
            var billingAddress  = addresses.First(x => x.Id == cart.BillingAddressId);
            var shippingAddress = addresses.FirstOrDefault(x => x.Id == cart.ShippingAddressId);

            order.BillingAddressSerialized  = _dataSerializer.Serialize(billingAddress);
            order.ShippingAddressSerialized =
                shippingAddress == null ? null : _dataSerializer.Serialize(shippingAddress);

            //get all the products
            var distinctProductIds = cart.CartItems.Select(x => x.ProductId).ToList();
            var products           = _productService.Get(x => distinctProductIds.Contains(x.Id)).ToList();

            order.OrderItems = new List <OrderItem>();
            foreach (var cartItem in cart.CartItems)
            {
                var orderItem = new OrderItem()
                {
                    AttributeJson    = cartItem.AttributeJson,
                    OrderId          = order.Id,
                    Price            = cartItem.Price,
                    ProductId        = cartItem.ProductId,
                    Quantity         = cartItem.Quantity,
                    Tax              = cartItem.Tax,
                    TaxPercent       = cartItem.TaxPercent,
                    TaxName          = cartItem.TaxName,
                    ProductVariantId = cartItem.ProductVariantId,
                    IsDownloadable   = cartItem.IsDownloadable,
                    Product          = products.First(x => x.Id == cartItem.ProductId),
                };
                orderItem.SubscriptionCycle = orderItem.Product.SubscriptionCycle;
                orderItem.CycleCount        = orderItem.Product.CycleCount;
                orderItem.TrialDays         = orderItem.Product.TrialDays;
                order.OrderItems.Add(orderItem);
            }
            var creditAmount = 0m;

            if (cart.UseStoreCredits)
            {
                GetAvailableStoreCredits(out var credits, out creditAmount, ApplicationEngine.BaseCurrency, cart);
                if (credits > 0 && _affiliateSettings.MinimumStoreCreditsToAllowPurchases <= credits)
                {
                    order.UsedStoreCredits  = true;
                    order.StoreCredits      = credits;
                    order.StoreCreditAmount = creditAmount;
                }
            }

            //insert complete order
            _orderAccountant.InsertCompleteOrder(order);

            //process payment
            var paymentMethodData = cart.PaymentMethodData.IsNullEmptyOrWhiteSpace()
                ? null
                : _dataSerializer.DeserializeAs <Dictionary <string, object> >(
                _cryptographyService.Decrypt(cart.PaymentMethodData));

            CustomResponse response = null;

            if (cart.PaymentMethodName != ApplicationConfig.UnavailableMethodName && !ProcessPayment(order, creditAmount, paymentMethodData, out response))
            {
                return(response.With("orderGuid", order.Guid).Result);
            }

            //clear the user's cart
            _cartService.ClearCart(currentUser.Id);

            if (currentUser.IsVisitor())
            {
                //if current user is visitor, change the email to billing address and change it to registered user
                currentUser.Email = billingAddress.Email;
                _userService.Update(currentUser);

                var roleId = _roleService.Get(x => x.SystemName == SystemRoleNames.Registered).First().Id;
                //assign registered role to the user
                _roleService.SetUserRoles(currentUser.Id, new[] { roleId });

                ApplicationEngine.SignIn(currentUser.Email, null, false);
            }

            response = response ?? R.Success;
            return(response.With("orderGuid", order.Guid).Result);
        }