/// <summary>
        /// Handle admin tabstrip created event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public async void HandleEvent(AdminTabStripCreated eventMessage)
        {
            if (eventMessage?.Helper == null)
            {
                return;
            }

            //we need customer details page
            var tabsElementId = "customer-edit";

            if (!eventMessage.TabStripName.Equals(tabsElementId))
            {
                return;
            }

            //check whether the payment plugin is installed and is active
            var worldpayPaymentMethod = _paymentService.LoadPaymentMethodBySystemName(WorldpayPaymentDefaults.SystemName);

            if (!(worldpayPaymentMethod?.PluginDescriptor?.Installed ?? false) || !_paymentService.IsPaymentMethodActive(worldpayPaymentMethod))
            {
                return;
            }

            //get the view model
            if (!(eventMessage.Helper.ViewData.Model is CustomerModel customerModel))
            {
                return;
            }

            //check whether a customer exists and isn't guest
            var customer = _customerService.GetCustomerById(customerModel.Id);

            if (customer == null || customer.IsGuest())
            {
                return;
            }

            //try to get stored in Vault customer
            var vaultCustomer = _worldpayPaymentManager.GetCustomer(_genericAttributeService.GetAttribute <string>(customer, WorldpayPaymentDefaults.CustomerIdAttribute));

            //prepare model
            var model = new WorldpayCustomerModel
            {
                Id                 = customerModel.Id,
                CustomerExists     = vaultCustomer != null,
                WorldpayCustomerId = vaultCustomer?.CustomerId
            };

            //compose script to create a new tab
            var worldpayCustomerTabElementId = "tab-worldpay";
            var worldpayCustomerTab          = new HtmlString($@"
                <script>
                    $(document).ready(function() {{
                        $(`
                            <li>
                                <a data-tab-name='{worldpayCustomerTabElementId}' data-toggle='tab' href='#{worldpayCustomerTabElementId}'>
                                    {_localizationService.GetResource("Plugins.Payments.Worldpay.WorldpayCustomer")}
                                </a>
                            </li>
                        `).appendTo('#{tabsElementId} .nav-tabs:first');
                        $(`
                            <div class='tab-pane' id='{worldpayCustomerTabElementId}'>
                                {
                                    (await eventMessage.Helper.PartialAsync("~/Plugins/Payments.Worldpay/Views/Customer/_CreateOrUpdate.Worldpay.cshtml", model)).RenderHtmlContent()
                                        .Replace("</script>", "<\\/script>") //we need escape a closing script tag to prevent terminating the script block early
                                }
                            </div>
                        `).appendTo('#{tabsElementId} .tab-content:first');
                    }});
                </script>");

            //add this tab as a block to render on the customer details page
            eventMessage.BlocksToRender.Add(worldpayCustomerTab);
        }
        /// <summary>
        /// Prepare the profile info model
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <returns>Profile info model</returns>
        public virtual ProfileInfoModel PrepareProfileInfoModel(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //avatar
            var avatarUrl = "";

            if (_customerSettings.AllowCustomersToUploadAvatars)
            {
                avatarUrl = _pictureService.GetPictureUrl(
                    _genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute),
                    _mediaSettings.AvatarPictureSize,
                    _customerSettings.DefaultAvatarEnabled,
                    defaultPictureType: PictureType.Avatar);
            }

            //location
            var locationEnabled = false;
            var location        = string.Empty;

            if (_customerSettings.ShowCustomersLocation)
            {
                locationEnabled = true;

                var countryId = _genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.CountryIdAttribute);
                var country   = _countryService.GetCountryById(countryId);
                if (country != null)
                {
                    location = _localizationService.GetLocalized(country, x => x.Name);
                }
                else
                {
                    locationEnabled = false;
                }
            }

            //private message
            var pmEnabled = _forumSettings.AllowPrivateMessages && !customer.IsGuest();

            //total forum posts
            var totalPostsEnabled = false;
            var totalPosts        = 0;

            if (_forumSettings.ForumsEnabled && _forumSettings.ShowCustomersPostCount)
            {
                totalPostsEnabled = true;
                totalPosts        = _genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.ForumPostCountAttribute);
            }

            //registration date
            var joinDateEnabled = false;
            var joinDate        = string.Empty;

            if (_customerSettings.ShowCustomersJoinDate)
            {
                joinDateEnabled = true;
                joinDate        = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc).ToString("f");
            }

            //birth date
            var dateOfBirthEnabled = false;
            var dateOfBirth        = string.Empty;

            if (_customerSettings.DateOfBirthEnabled)
            {
                var dob = _genericAttributeService.GetAttribute <DateTime?>(customer, NopCustomerDefaults.DateOfBirthAttribute);
                if (dob.HasValue)
                {
                    dateOfBirthEnabled = true;
                    dateOfBirth        = dob.Value.ToString("D");
                }
            }

            var model = new ProfileInfoModel
            {
                CustomerProfileId  = customer.Id,
                AvatarUrl          = avatarUrl,
                LocationEnabled    = locationEnabled,
                Location           = location,
                PMEnabled          = pmEnabled,
                TotalPostsEnabled  = totalPostsEnabled,
                TotalPosts         = totalPosts.ToString(),
                JoinDateEnabled    = joinDateEnabled,
                JoinDate           = joinDate,
                DateOfBirthEnabled = dateOfBirthEnabled,
                DateOfBirth        = dateOfBirth,
            };

            return(model);
        }
Exemple #3
0
        public IActionResult PDTHandler()
        {
            var tx = _webHelper.QueryString <string>("tx");

            if (!(_paymentPluginManager.LoadPluginBySystemName("Payments.PayPalStandard") is PayPalStandardPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new QNetException("PayPal Standard module cannot be loaded");
            }

            if (processor.GetPdtDetails(tx, out var values, out var response))
            {
                values.TryGetValue("custom", out var orderNumber);
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch
                {
                    // ignored
                }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);

                if (order == null)
                {
                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                var mcGross = decimal.Zero;

                try
                {
                    mcGross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch (Exception exc)
                {
                    _logger.Error("PayPal PDT. Error getting mc_gross", exc);
                }

                values.TryGetValue("payer_status", out var payerStatus);
                values.TryGetValue("payment_status", out var paymentStatus);
                values.TryGetValue("pending_reason", out var pendingReason);
                values.TryGetValue("mc_currency", out var mcCurrency);
                values.TryGetValue("txn_id", out var txnId);
                values.TryGetValue("payment_type", out var paymentType);
                values.TryGetValue("payer_id", out var payerId);
                values.TryGetValue("receiver_id", out var receiverId);
                values.TryGetValue("invoice", out var invoice);
                values.TryGetValue("payment_fee", out var paymentFee);

                var sb = new StringBuilder();
                sb.AppendLine("PayPal PDT:");
                sb.AppendLine("mc_gross: " + mcGross);
                sb.AppendLine("Payer status: " + payerStatus);
                sb.AppendLine("Payment status: " + paymentStatus);
                sb.AppendLine("Pending reason: " + pendingReason);
                sb.AppendLine("mc_currency: " + mcCurrency);
                sb.AppendLine("txn_id: " + txnId);
                sb.AppendLine("payment_type: " + paymentType);
                sb.AppendLine("payer_id: " + payerId);
                sb.AppendLine("receiver_id: " + receiverId);
                sb.AppendLine("invoice: " + invoice);
                sb.AppendLine("payment_fee: " + paymentFee);

                var newPaymentStatus = PayPalHelper.GetPaymentStatus(paymentStatus, string.Empty);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                //order note
                order.OrderNotes.Add(new OrderNote
                {
                    Note = sb.ToString(),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);

                //validate order total
                var orderTotalSentToPayPal = _genericAttributeService.GetAttribute <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal);
                if (orderTotalSentToPayPal.HasValue && mcGross != orderTotalSentToPayPal.Value)
                {
                    var errorStr = $"PayPal PDT. Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                    //log
                    _logger.Error(errorStr);
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = errorStr,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                //clear attribute
                if (orderTotalSentToPayPal.HasValue)
                {
                    _genericAttributeService.SaveAttribute <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal, null);
                }

                if (newPaymentStatus != PaymentStatus.Paid)
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                if (!_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                //mark order as paid
                order.AuthorizationTransactionId = txnId;
                _orderService.UpdateOrder(order);
                _orderProcessingService.MarkOrderAsPaid(order);

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
Exemple #4
0
 string GetCustomerAvatarUrl(Customer customer)
 {
     return(_pictureService.GetPictureUrl(
                _genericAttributeService.GetAttribute <int>(customer, GSCustomerDefaults.AvatarPictureIdAttribute),
                _mediaSettings.AvatarPictureSize, defaultPictureType: PictureType.Avatar));
 }
        /// <summary>
        /// Prepare the forum topic page model
        /// </summary>
        /// <param name="forumTopic">Forum topic</param>
        /// <param name="page">Number of forum posts page</param>
        /// <returns>Forum topic page model</returns>
        public virtual ForumTopicPageModel PrepareForumTopicPageModel(ForumTopic forumTopic, int page)
        {
            if (forumTopic == null)
            {
                throw new ArgumentNullException(nameof(forumTopic));
            }

            //load posts
            var posts = _forumService.GetAllPosts(forumTopic.Id, 0, string.Empty,
                                                  page - 1, _forumSettings.PostsPageSize);

            //prepare model
            var model = new ForumTopicPageModel
            {
                Id      = forumTopic.Id,
                Subject = forumTopic.Subject,
                SeName  = _forumService.GetTopicSeName(forumTopic),

                IsCustomerAllowedToEditTopic   = _forumService.IsCustomerAllowedToEditTopic(_workContext.CurrentCustomer, forumTopic),
                IsCustomerAllowedToDeleteTopic = _forumService.IsCustomerAllowedToDeleteTopic(_workContext.CurrentCustomer, forumTopic),
                IsCustomerAllowedToMoveTopic   = _forumService.IsCustomerAllowedToMoveTopic(_workContext.CurrentCustomer, forumTopic),
                IsCustomerAllowedToSubscribe   = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer)
            };

            if (model.IsCustomerAllowedToSubscribe)
            {
                model.WatchTopicText = _localizationService.GetResource("Forum.WatchTopic");

                var forumTopicSubscription = _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id, 0, forumTopic.Id, 0, 1).FirstOrDefault();
                if (forumTopicSubscription != null)
                {
                    model.WatchTopicText = _localizationService.GetResource("Forum.UnwatchTopic");
                }
            }
            model.PostsPageIndex    = posts.PageIndex;
            model.PostsPageSize     = posts.PageSize;
            model.PostsTotalRecords = posts.TotalCount;
            foreach (var post in posts)
            {
                var forumPostModel = new ForumPostModel
                {
                    Id               = post.Id,
                    ForumTopicId     = post.TopicId,
                    ForumTopicSeName = _forumService.GetTopicSeName(forumTopic),
                    FormattedText    = _forumService.FormatPostText(post),
                    IsCurrentCustomerAllowedToEditPost   = _forumService.IsCustomerAllowedToEditPost(_workContext.CurrentCustomer, post),
                    IsCurrentCustomerAllowedToDeletePost = _forumService.IsCustomerAllowedToDeletePost(_workContext.CurrentCustomer, post),
                    CustomerId               = post.CustomerId,
                    AllowViewingProfiles     = _customerSettings.AllowViewingProfiles && !post.Customer.IsGuest(),
                    CustomerName             = _customerService.FormatUserName(post.Customer),
                    IsCustomerForumModerator = post.Customer.IsForumModerator(),
                    ShowCustomersPostCount   = _forumSettings.ShowCustomersPostCount,
                    ForumPostCount           = _genericAttributeService.GetAttribute <int>(post.Customer, NopCustomerDefaults.ForumPostCountAttribute),
                    ShowCustomersJoinDate    = _customerSettings.ShowCustomersJoinDate && !post.Customer.IsGuest(),
                    CustomerJoinDate         = post.Customer.CreatedOnUtc,
                    AllowPrivateMessages     = _forumSettings.AllowPrivateMessages && !post.Customer.IsGuest(),
                    SignaturesEnabled        = _forumSettings.SignaturesEnabled,
                    FormattedSignature       = _forumService.FormatForumSignatureText(_genericAttributeService.GetAttribute <string>(post.Customer, NopCustomerDefaults.SignatureAttribute)),
                };
                //created on string
                if (_forumSettings.RelativeDateTimeFormattingEnabled)
                {
                    forumPostModel.PostCreatedOnStr = post.CreatedOnUtc.RelativeFormat(true, "f");
                }
                else
                {
                    forumPostModel.PostCreatedOnStr =
                        _dateTimeHelper.ConvertToUserTime(post.CreatedOnUtc, DateTimeKind.Utc).ToString("f");
                }
                //avatar
                if (_customerSettings.AllowCustomersToUploadAvatars)
                {
                    forumPostModel.CustomerAvatarUrl = _pictureService.GetPictureUrl(
                        _genericAttributeService.GetAttribute <int>(post.Customer, NopCustomerDefaults.AvatarPictureIdAttribute),
                        _mediaSettings.AvatarPictureSize,
                        _customerSettings.DefaultAvatarEnabled,
                        defaultPictureType: PictureType.Avatar);
                }
                //location
                forumPostModel.ShowCustomersLocation = _customerSettings.ShowCustomersLocation && !post.Customer.IsGuest();
                if (_customerSettings.ShowCustomersLocation)
                {
                    var countryId = _genericAttributeService.GetAttribute <int>(post.Customer, NopCustomerDefaults.CountryIdAttribute);
                    var country   = _countryService.GetCountryById(countryId);
                    forumPostModel.CustomerLocation = country != null?_localizationService.GetLocalized(country, x => x.Name) : string.Empty;
                }

                //votes
                if (_forumSettings.AllowPostVoting)
                {
                    forumPostModel.AllowPostVoting = true;
                    forumPostModel.VoteCount       = post.VoteCount;
                    var postVote = _forumService.GetPostVote(post.Id, _workContext.CurrentCustomer);
                    if (postVote != null)
                    {
                        forumPostModel.VoteIsUp = postVote.IsUp;
                    }
                }

                // page number is needed for creating post link in _ForumPost partial view
                forumPostModel.CurrentTopicPage = page;
                model.ForumPostModels.Add(forumPostModel);
            }

            return(model);
        }
        public IActionResult ParatikaPaymentInfo(PaymentInfoModel model)
        {
            Dictionary <String, String> requestParameters = new Dictionary <String, String>();
            var processPaymentRequest = new ProcessPaymentRequest();
            var processGuid           = Guid.NewGuid().ToString();

            if (_orderSettings.CheckoutDisabled)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_storeContext.CurrentStore.Id)
                       .ToList();

            if (!cart.Any())
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if (_orderSettings.OnePageCheckoutEnabled)
            {
                return(RedirectToRoute("CheckoutOnePage"));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
            {
                return(Challenge());
            }

            //Check whether payment workflow is required
            var isPaymentWorkflowRequired = _orderProcessingService.IsPaymentWorkflowRequired(cart);

            if (!isPaymentWorkflowRequired)
            {
                return(RedirectToRoute("CheckoutConfirm"));
            }

            //load payment method
            var paymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer,
                                                                                         NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id);
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSystemName);

            if (paymentMethod == null)
            {
                return(RedirectToRoute("CheckoutPaymentMethod"));
            }

            string sessionTokenValue = _session.Get <string>("SESSIONTOKEN_" + _workContext.CurrentCustomer.Id);

            //if prataka is not active, you get payment with HP Interface.
            if (_paratikaOrderPaymentSettings.PaymentHPMethod)
            {
                //used main url set value only with hp method
                var orderGuid = _session.Get <string>("MERCHANTPAYMENTID_" + _workContext.CurrentCustomer.Id);
                processPaymentRequest.OrderGuid = Guid.Parse(orderGuid);
                HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
                model.PaymentHPMethodURL = _paratikaOrderPaymentSettings.PaymentHPMethodURL + sessionTokenValue;
                return(Json(model));
            }

            if (!string.IsNullOrWhiteSpace(sessionTokenValue))
            {
                model.SessionToken = sessionTokenValue;
                return(View("~/Plugins/Payments.Paratika/Views/PaymentInfo.cshtml", model));
            }
            else
            {
                _logger.Information(" > SESSIONTOKEN operation is FAILED, please check the error codes.");
                model.Error = _localizationService.GetResource("Plugins.Payments.Paratika.Fields.Error");
                return(View("~/Plugins/Payments.Paratika/Views/PaymentInfo.cshtml", model));
            }
        }
Exemple #7
0
        /// <summary>
        /// Invoke the widget view component
        /// </summary>
        /// <param name="widgetZone">Widget zone</param>
        /// <param name="additionalData">Additional parameters</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            //ensure that model is passed
            if (!(additionalData is BaseNopEntityModel entityModel))
            {
                return(Content(string.Empty));
            }

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(Content(string.Empty));
            }

            //ensure that Avalara tax provider is active
            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName))
            {
                return(Content(string.Empty));
            }

            //ensure that it's a proper widget zone
            if (!widgetZone.Equals(AdminWidgetZones.CustomerDetailsBlock) &&
                !widgetZone.Equals(AdminWidgetZones.CustomerRoleDetailsTop) &&
                !widgetZone.Equals(AdminWidgetZones.ProductDetailsBlock) &&
                !widgetZone.Equals(AdminWidgetZones.CheckoutAttributeDetailsBlock))
            {
                return(Content(string.Empty));
            }

            //get Avalara pre-defined entity use codes
            var cachedEntityUseCodes = _cacheManager.Get(AvalaraTaxDefaults.EntityUseCodesCacheKey, () => _avalaraTaxManager.GetEntityUseCodes());
            var entityUseCodes       = cachedEntityUseCodes?.Select(useCode => new SelectListItem
            {
                Value = useCode.code,
                Text  = $"{useCode.name} ({useCode.validCountries.Aggregate(string.Empty, (list, country) => $"{list}{country},").TrimEnd(',')})"
            }).ToList() ?? new List <SelectListItem>();

            //add the special item for 'undefined' with empty guid value
            var defaultValue = Guid.Empty.ToString();

            entityUseCodes.Insert(0, new SelectListItem
            {
                Value = defaultValue,
                Text  = _localizationService.GetResource("Plugins.Tax.Avalara.Fields.EntityUseCode.None")
            });

            //prepare model
            var model = new EntityUseCodeModel
            {
                Id             = entityModel.Id,
                EntityUseCodes = entityUseCodes
            };

            //get entity by the model identifier
            BaseEntity entity = null;

            if (widgetZone.Equals(AdminWidgetZones.CustomerDetailsBlock))
            {
                model.PrecedingElementId = nameof(CustomerModel.IsTaxExempt);
                entity = _customerService.GetCustomerById(entityModel.Id);
            }

            if (widgetZone.Equals(AdminWidgetZones.CustomerRoleDetailsTop))
            {
                model.PrecedingElementId = nameof(CustomerRoleModel.TaxExempt);
                entity = _customerService.GetCustomerRoleById(entityModel.Id);
            }

            if (widgetZone.Equals(AdminWidgetZones.ProductDetailsBlock))
            {
                model.PrecedingElementId = nameof(ProductModel.IsTaxExempt);
                entity = _productService.GetProductById(entityModel.Id);
            }

            if (widgetZone.Equals(AdminWidgetZones.CheckoutAttributeDetailsBlock))
            {
                model.PrecedingElementId = nameof(CheckoutAttributeModel.IsTaxExempt);
                entity = _checkoutAttributeService.GetCheckoutAttributeById(entityModel.Id);
            }

            //try to get previously saved entity use code
            model.AvalaraEntityUseCode = entity == null ? defaultValue :
                                         _genericAttributeService.GetAttribute <string>(entity, AvalaraTaxDefaults.EntityUseCodeAttribute);

            return(View("~/Plugins/Tax.Avalara/Views/EntityUseCode/EntityUseCode.cshtml", model));
        }
        public virtual IActionResult PaidCallback(IpayDoubleEightResponseModel model)
        {
            if (string.IsNullOrEmpty(model.RefNo))
            {
                return(RedirectToRoute("HomePage"));
            }

            var orderNumber = model.RefNo;

            if (model.RefNo.Contains("_"))
            {
                orderNumber = orderNumber.Substring(0, model.RefNo.IndexOf('_'));
            }

            var order = _orderService.GetOrderByCustomOrderNumber(orderNumber);

            if (order == null)
            {
                return(RedirectToRoute("HomePage"));
            }

            _orderService.InsertOrderNote(new OrderNote
            {
                OrderId           = order.Id,
                Note              = ParseMessageToNote(model),
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });

            //check total
            var orderTotalSentTo =
                _genericAttributeService.GetAttribute <decimal?>(order, IpayDoubleEightHelper.OrderTotalSentToIpayDoubleEight);

            if (orderTotalSentTo.HasValue && model.Amount != orderTotalSentTo.Value)
            {
                var errorStr =
                    $"iPay88. Returned order total {model.Amount} doesn't equal order total {order.OrderTotal}." +
                    $"Order #{order.CustomOrderNumber}.";
                //log
                _logger.Error(errorStr);
                //order note
                _orderService.InsertOrderNote(new OrderNote
                {
                    OrderId           = order.Id,
                    Note              = errorStr,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                return(RedirectToRoute("HomePage"));
            }

            //clear attribute
            if (orderTotalSentTo.HasValue)
            {
                _genericAttributeService.SaveAttribute <decimal?>(order, IpayDoubleEightHelper.OrderTotalSentToIpayDoubleEight, null);
            }

            if (model.Status == "1" && _orderProcessingService.CanMarkOrderAsPaid(order))
            {
                order.AuthorizationTransactionId     = model.TransId;
                order.AuthorizationTransactionCode   = model.AuthCode;
                order.AuthorizationTransactionResult = model.Status;

                _orderService.UpdateOrder(order);

                _orderProcessingService.MarkOrderAsPaid(order);

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
            else
            {
                _orderService.InsertOrderNote(new OrderNote
                {
                    OrderId           = order.Id,
                    Note              = model.ErrDesc,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
            }
        }
        public PaymentDetailsType[] GetPaymentDetails(IList <ShoppingCartItem> cart)
        {
            var currencyCode = _payPalCurrencyCodeParser.GetCurrencyCodeType(_workContext.WorkingCurrency);

            var orderTotalWithDiscount = _payPalCartItemService.GetCartTotal(cart, out var orderTotalDiscountAmount,
                                                                             out _,
                                                                             out _,
                                                                             out _,
                                                                             out var appliedGiftCards);

            var itemTotalWithDiscount = _payPalCartItemService.GetCartItemTotal(cart,
                                                                                out var subTotalDiscountAmount,
                                                                                out _,
                                                                                out _,
                                                                                out _);

            var giftCardsAmount = appliedGiftCards.Sum(x => x.AmountCanBeUsed);

            itemTotalWithDiscount = itemTotalWithDiscount - orderTotalDiscountAmount - giftCardsAmount;

            var taxTotal      = _payPalCartItemService.GetTax(cart);
            var shippingTotal = _payPalCartItemService.GetShippingTotal(cart);
            var items         = GetPaymentDetailsItems(cart);

            // checkout attributes
            var customer = _workContext.CurrentCustomer;

            if (customer != null)
            {
                var checkoutAttributesXml = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CheckoutAttributes, _storeContext.CurrentStore.Id);
                var caValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(checkoutAttributesXml);
                if (caValues != null)
                {
                    foreach (var caValue in caValues)
                    {
                        if (caValue.PriceAdjustment <= 0)
                        {
                            continue;
                        }

                        var checkoutAttrItem = new PaymentDetailsItemType
                        {
                            Name     = caValue.Name,
                            Amount   = caValue.PriceAdjustment.GetBasicAmountType(currencyCode),
                            Quantity = "1"
                        };

                        items.Add(checkoutAttrItem);
                    }
                }
            }

            if (orderTotalDiscountAmount > 0 || subTotalDiscountAmount > 0)
            {
                var discountItem = new PaymentDetailsItemType
                {
                    Name     = "Discount",
                    Amount   = (-orderTotalDiscountAmount + -subTotalDiscountAmount).GetBasicAmountType(currencyCode),
                    Quantity = "1"
                };

                items.Add(discountItem);
            }

            foreach (var appliedGiftCard in appliedGiftCards)
            {
                var giftCardItem = new PaymentDetailsItemType
                {
                    Name     = $"Gift Card ({appliedGiftCard.GiftCard.GiftCardCouponCode})",
                    Amount   = (-appliedGiftCard.AmountCanBeUsed).GetBasicAmountType(currencyCode),
                    Quantity = "1"
                };

                items.Add(giftCardItem);
            }

            return(new[]
            {
                new PaymentDetailsType
                {
                    OrderTotal = orderTotalWithDiscount.GetBasicAmountType(currencyCode),
                    ItemTotal = itemTotalWithDiscount.GetBasicAmountType(currencyCode),
                    TaxTotal = taxTotal.GetBasicAmountType(currencyCode),
                    ShippingTotal = shippingTotal.GetBasicAmountType(currencyCode),
                    PaymentDetailsItem = items.ToArray(),
                    PaymentAction = _payPalExpressCheckoutPaymentSettings.PaymentAction,
                    PaymentActionSpecified = true,
                    ButtonSource = PayPalHelper.BnCode
                }
            });
        }
        /// <summary>
        /// Handle shopping cart changed event
        /// </summary>
        /// <param name="cartItem">Shopping cart item</param>
        public void HandleShoppingCartChangedEvent(ShoppingCartItem cartItem)
        {
            //whether marketing automation is enabled
            if (!_sendinBlueSettings.UseMarketingAutomation)
            {
                return;
            }

            try
            {
                //create API client
                var client = CreateMarketingAutomationClient();

                //first, try to identify current customer
                client.Identify(new Identify(cartItem.Customer.Email));

                //get shopping cart GUID
                var shoppingCartGuid = _genericAttributeService
                                       .GetAttribute <Guid?>(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute);

                //create track event object
                var trackEvent = new TrackEvent(cartItem.Customer.Email, string.Empty);

                //get current customer's shopping cart
                var cart = _shoppingCartService
                           .GetShoppingCart(cartItem.Customer, ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

                if (cart.Any())
                {
                    //get URL helper
                    var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                    //get shopping cart amounts
                    var shippingRateComputationMethods = _shippingPluginManager
                                                         .LoadActivePlugins(cartItem.Customer, _storeContext.CurrentStore.Id);
                    _orderTotalCalculationService.GetShoppingCartSubTotal(cart,
                                                                          _workContext.TaxDisplayType == TaxDisplayType.IncludingTax,
                                                                          out var cartDiscount, out _, out var cartSubtotal, out _);
                    var cartTax      = _orderTotalCalculationService.GetTaxTotal(cart, shippingRateComputationMethods, false);
                    var cartShipping = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart, shippingRateComputationMethods);
                    var cartTotal    = _orderTotalCalculationService.GetShoppingCartTotal(cart, false, false);

                    //get products data by shopping cart items
                    var itemsData = cart.Where(item => item.Product != null).Select(item =>
                    {
                        //try to get product attribute combination
                        var combination = _productAttributeParser.FindProductAttributeCombination(item.Product, item.AttributesXml);

                        //get default product picture
                        var picture = _pictureService.GetProductPicture(item.Product, item.AttributesXml);

                        //get product SEO slug name
                        var seName = _urlRecordService.GetSeName(item.Product);

                        //create product data
                        return(new
                        {
                            id = item.Product.Id,
                            name = item.Product.Name,
                            variant_id = combination?.Id ?? item.Product.Id,
                            variant_name = combination?.Sku ?? item.Product.Name,
                            sku = combination?.Sku ?? item.Product.Sku,
                            category = item.Product.ProductCategories.Aggregate(",", (all, category) =>
                            {
                                var res = category.Category.Name;
                                res = all == "," ? res : all + ", " + res;
                                return res;
                            }),
                            url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.CurrentRequestProtocol),
                            image = _pictureService.GetPictureUrl(picture),
                            quantity = item.Quantity,
                            price = _priceCalculationService.GetSubTotal(item)
                        });
                    }).ToArray();

                    //prepare cart data
                    var cartData = new
                    {
                        affiliation      = _storeContext.CurrentStore.Name,
                        subtotal         = cartSubtotal,
                        shipping         = cartShipping ?? decimal.Zero,
                        total_before_tax = cartSubtotal + cartShipping ?? decimal.Zero,
                        tax      = cartTax,
                        discount = cartDiscount,
                        revenue  = cartTotal ?? decimal.Zero,
                        url      = urlHelper.RouteUrl("ShoppingCart", null, _webHelper.CurrentRequestProtocol),
                        currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode,
                        //gift_wrapping = string.Empty, //currently we can't get this value
                        items = itemsData
                    };

                    //if there is a single item in the cart, so the cart is just created
                    if (cart.Count == 1)
                    {
                        shoppingCartGuid = Guid.NewGuid();
                    }
                    else
                    {
                        //otherwise cart is updated
                        shoppingCartGuid = shoppingCartGuid ?? Guid.NewGuid();
                    }
                    trackEvent.EventName = SendinBlueDefaults.CartUpdatedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}", data = cartData };
                }
                else
                {
                    //there are no items in the cart, so the cart is deleted
                    shoppingCartGuid     = shoppingCartGuid ?? Guid.NewGuid();
                    trackEvent.EventName = SendinBlueDefaults.CartDeletedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}" };
                }

                //track event
                client.TrackEvent(trackEvent);

                //update GUID for the current customer's shopping cart
                _genericAttributeService.SaveAttribute(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute, shoppingCartGuid);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"SendinBlue Marketing Automation error: {exception.Message}.", exception, cartItem.Customer);
            }
        }
Exemple #11
0
        /// <summary>
        /// Prepare tax details by Avalara tax service
        /// </summary>
        /// <param name="cart">Shopping cart</param>
        private void PrepareTaxDetails(IList <ShoppingCartItem> cart)
        {
            //ensure that Avalara tax provider is active
            if (!(_taxService.LoadActiveTaxProvider(_workContext.CurrentCustomer) is AvalaraTaxProvider taxProvider))
            {
                return;
            }

            //create dummy order for the tax request
            var order = new Order {
                Customer = _workContext.CurrentCustomer
            };

            //addresses
            order.BillingAddress  = _workContext.CurrentCustomer.BillingAddress;
            order.ShippingAddress = _workContext.CurrentCustomer.ShippingAddress;
            if (_shippingSettings.AllowPickUpInStore)
            {
                var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(_workContext.CurrentCustomer,
                                                                                      NopCustomerDefaults.SelectedPickupPointAttribute, _storeContext.CurrentStore.Id);
                if (pickupPoint != null)
                {
                    var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode);
                    order.PickupAddress = new Address
                    {
                        Address1      = pickupPoint.Address,
                        City          = pickupPoint.City,
                        Country       = country,
                        StateProvince = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id),
                        ZipPostalCode = pickupPoint.ZipPostalCode,
                        CreatedOnUtc  = DateTime.UtcNow,
                    };
                }
            }

            //checkout attributes
            order.CheckoutAttributesXml = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer,
                                                                                         NopCustomerDefaults.CheckoutAttributes, _storeContext.CurrentStore.Id);

            //shipping method
            order.OrderShippingExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart, false) ?? 0;
            order.ShippingMethod       = _genericAttributeService.GetAttribute <ShippingOption>(_workContext.CurrentCustomer,
                                                                                                NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id)?.Name;

            //payment method
            var paymentMethod = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer,
                                                                               NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id);
            var paymentFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethod);

            order.PaymentMethodAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentFee, false, _workContext.CurrentCustomer);
            order.PaymentMethodSystemName           = paymentMethod;

            //add discount amount
            _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false, out var orderSubTotalDiscountExclTax, out _, out _, out _);
            order.OrderSubTotalDiscountExclTax = orderSubTotalDiscountExclTax;

            //create dummy order items
            foreach (var cartItem in cart)
            {
                var orderItem = new OrderItem
                {
                    AttributesXml = cartItem.AttributesXml,
                    Product       = cartItem.Product,
                    Quantity      = cartItem.Quantity
                };

                var itemSubtotal = _priceCalculationService.GetSubTotal(cartItem, true, out _, out _, out _);
                orderItem.PriceExclTax = _taxService.GetProductPrice(cartItem.Product, itemSubtotal, false, _workContext.CurrentCustomer, out _);

                order.OrderItems.Add(orderItem);
            }

            //get tax details
            var taxTransaction = taxProvider.CreateOrderTaxTransaction(order, false);

            if (taxTransaction == null)
            {
                return;
            }

            //and save it for the further usage
            var taxDetails = new TaxDetails {
                TaxTotal = taxTransaction.totalTax
            };

            foreach (var item in taxTransaction.summary)
            {
                if (!item.rate.HasValue || !item.tax.HasValue)
                {
                    continue;
                }

                var taxRate  = item.rate.Value * 100;
                var taxValue = item.tax.Value;

                if (!taxDetails.TaxRates.ContainsKey(taxRate))
                {
                    taxDetails.TaxRates.Add(taxRate, taxValue);
                }
                else
                {
                    taxDetails.TaxRates[taxRate] = taxDetails.TaxRates[taxRate] + taxValue;
                }
            }
            _httpContextAccessor.HttpContext.Session.Set(AvalaraTaxDefaults.TaxDetailsSessionValue, taxDetails);
        }
Exemple #12
0
        /// <summary>
        /// Prepare FeedGoogleShoppingModel
        /// </summary>
        /// <param name="model">Model</param>
        private void PrepareModel(FeedGoogleShoppingModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return;
            }

            //load settings for a chosen store scope
            var storeScope             = _storeContext.ActiveStoreScopeConfiguration;
            var googleShoppingSettings = _settingService.LoadSetting <GoogleShoppingSettings>(storeScope);

            model.ProductPictureSize         = googleShoppingSettings.ProductPictureSize;
            model.PassShippingInfoWeight     = googleShoppingSettings.PassShippingInfoWeight;
            model.PassShippingInfoDimensions = googleShoppingSettings.PassShippingInfoDimensions;
            model.PricesConsiderPromotions   = googleShoppingSettings.PricesConsiderPromotions;

            //currencies
            model.CurrencyId = googleShoppingSettings.CurrencyId;
            foreach (var c in _currencyService.GetAllCurrencies())
            {
                model.AvailableCurrencies.Add(new SelectListItem {
                    Text = c.Name, Value = c.Id.ToString()
                });
            }
            //Google categories
            model.DefaultGoogleCategory = googleShoppingSettings.DefaultGoogleCategory;
            model.AvailableGoogleCategories.Add(new SelectListItem {
                Text = "Select a category", Value = ""
            });
            foreach (var gc in _googleService.GetTaxonomyList())
            {
                model.AvailableGoogleCategories.Add(new SelectListItem {
                    Text = gc, Value = gc
                });
            }

            model.HideGeneralBlock         = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, GoogleShoppingDefaults.HideGeneralBlock);
            model.HideProductSettingsBlock = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, GoogleShoppingDefaults.HideProductSettingsBlock);

            //prepare nested search models
            model.GoogleProductSearchModel.SetGridPageSize();

            //file paths
            foreach (var store in _storeService.GetAllStores())
            {
                var localFilePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "files\\exportimport", store.Id + "-" + googleShoppingSettings.StaticFileName);
                if (System.IO.File.Exists(localFilePath))
                {
                    model.GeneratedFiles.Add(new GeneratedFileModel
                    {
                        StoreName = store.Name,
                        FileUrl   = $"{_webHelper.GetStoreLocation(false)}files/exportimport/{store.Id}-{googleShoppingSettings.StaticFileName}"
                    });
                }
            }

            model.ActiveStoreScopeConfiguration = storeScope;
            if (storeScope > 0)
            {
                model.CurrencyId_OverrideForStore                 = _settingService.SettingExists(googleShoppingSettings, x => x.CurrencyId, storeScope);
                model.DefaultGoogleCategory_OverrideForStore      = _settingService.SettingExists(googleShoppingSettings, x => x.DefaultGoogleCategory, storeScope);
                model.PassShippingInfoDimensions_OverrideForStore = _settingService.SettingExists(googleShoppingSettings, x => x.PassShippingInfoDimensions, storeScope);
                model.PassShippingInfoWeight_OverrideForStore     = _settingService.SettingExists(googleShoppingSettings, x => x.PassShippingInfoWeight, storeScope);
                model.PricesConsiderPromotions_OverrideForStore   = _settingService.SettingExists(googleShoppingSettings, x => x.PricesConsiderPromotions, storeScope);
                model.ProductPictureSize_OverrideForStore         = _settingService.SettingExists(googleShoppingSettings, x => x.ProductPictureSize, storeScope);
            }
        }
        private string GetEcommerceScript(Order order)
        {
            var analyticsTrackingScript = _googleAnalyticsSettings.TrackingScript + "\n";

            analyticsTrackingScript = analyticsTrackingScript.Replace("{GOOGLEID}", _googleAnalyticsSettings.GoogleId);
            //remove {ECOMMERCE} (used in previous versions of the plugin)
            analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE}", "");
            //remove {CustomerID} (used in previous versions of the plugin)
            analyticsTrackingScript = analyticsTrackingScript.Replace("{CustomerID}", "");

            //whether to include customer identifier
            var customerIdCode = string.Empty;

            if (_googleAnalyticsSettings.IncludeCustomerId && !_workContext.CurrentCustomer.IsGuest())
            {
                customerIdCode = $"gtag('set', {{'user_id': '{_workContext.CurrentCustomer.Id}'}});{Environment.NewLine}";
            }
            analyticsTrackingScript = analyticsTrackingScript.Replace("{CUSTOMER_TRACKING}", customerIdCode);

            //ecommerce info
            var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(_storeContext.CurrentStore.Id);

            //ensure that ecommerce tracking code is renderred only once (avoid duplicated data in Google Analytics)
            if (order != null && !_genericAttributeService.GetAttribute <bool>(order, ORDER_ALREADY_PROCESSED_ATTRIBUTE_NAME))
            {
                var usCulture = new CultureInfo("en-US");

                var analyticsEcommerceScript = @"gtag('event', 'purchase', {
                    'transaction_id': '{ORDERID}',
                    'affiliation': '{SITE}',
                    'value': {TOTAL},
                    'currency': '{CURRENCY}',
                    'tax': {TAX},
                    'shipping': {SHIP},
                    'items': [
                    {DETAILS}
                    ]
                });";
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{ORDERID}", FixIllegalJavaScriptChars(order.CustomOrderNumber));
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{SITE}", FixIllegalJavaScriptChars(_storeContext.CurrentStore.Name));
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TOTAL}", order.OrderTotal.ToString("0.00", usCulture));
                var currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{CURRENCY}", currencyCode);
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{TAX}", order.OrderTax.ToString("0.00", usCulture));
                var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax;
                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{SHIP}", orderShipping.ToString("0.00", usCulture));

                var sb = new StringBuilder();
                int listingPosition = 1;
                foreach (var item in order.OrderItems)
                {
                    if (!String.IsNullOrEmpty(sb.ToString()))
                    {
                        sb.AppendLine(",");
                    }

                    string analyticsEcommerceDetailScript = @"{
                    'id': '{PRODUCTSKU}',
                    'name': '{PRODUCTNAME}',
                    'category': '{CATEGORYNAME}',
                    'list_position': {LISTPOSITION},
                    'quantity': {QUANTITY},
                    'price': '{UNITPRICE}'
                    }
                    ";
                    var    sku = _productService.FormatSku(item.Product, item.AttributesXml);
                    if (String.IsNullOrEmpty(sku))
                    {
                        sku = item.Product.Id.ToString();
                    }
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTSKU}", FixIllegalJavaScriptChars(sku));
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{PRODUCTNAME}", FixIllegalJavaScriptChars(item.Product.Name));
                    string category = _categoryService.GetProductCategoriesByProductId(item.ProductId).FirstOrDefault()?.Category.Name;
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{CATEGORYNAME}", FixIllegalJavaScriptChars(category));
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{LISTPOSITION}", listingPosition.ToString());
                    var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax;
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{QUANTITY}", item.Quantity.ToString());
                    analyticsEcommerceDetailScript = analyticsEcommerceDetailScript.Replace("{UNITPRICE}", unitPrice.ToString("0.00", usCulture));
                    sb.AppendLine(analyticsEcommerceDetailScript);

                    listingPosition++;
                }

                analyticsEcommerceScript = analyticsEcommerceScript.Replace("{DETAILS}", sb.ToString());

                analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE_TRACKING}", analyticsEcommerceScript);

                _genericAttributeService.SaveAttribute(order, ORDER_ALREADY_PROCESSED_ATTRIBUTE_NAME, true);
            }
            else
            {
                analyticsTrackingScript = analyticsTrackingScript.Replace("{ECOMMERCE_TRACKING}", "");
            }

            return(analyticsTrackingScript);
        }
        /// <summary>
        /// Gets tax total
        /// </summary>
        /// <param name="taxTotalRequest">Tax total request</param>
        /// <returns>Tax total</returns>
        public TaxTotalResult GetTaxTotal(TaxTotalRequest taxTotalRequest)
        {
            if (!(_httpContextAccessor.HttpContext.Items.TryGetValue("nop.TaxTotal", out var result) && result is TaxTotalResult taxTotalResult))
            {
                var taxRates = new SortedDictionary <decimal, decimal>();

                //order sub total (items + checkout attributes)
                _orderTotalCalculationService
                .GetShoppingCartSubTotal(taxTotalRequest.ShoppingCart, false, out _, out _, out _, out _, out var orderSubTotalTaxRates);
                var subTotalTaxTotal = decimal.Zero;
                foreach (var kvp in orderSubTotalTaxRates)
                {
                    var taxRate  = kvp.Key;
                    var taxValue = kvp.Value;
                    subTotalTaxTotal += taxValue;

                    if (taxRate > decimal.Zero && taxValue > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(taxRate))
                        {
                            taxRates.Add(taxRate, taxValue);
                        }
                        else
                        {
                            taxRates[taxRate] = taxRates[taxRate] + taxValue;
                        }
                    }
                }

                //shipping
                var shippingTax = decimal.Zero;
                if (_taxSettings.ShippingIsTaxable)
                {
                    var shippingExclTax = _orderTotalCalculationService
                                          .GetShoppingCartShippingTotal(taxTotalRequest.ShoppingCart, false, out _);
                    var shippingInclTax = _orderTotalCalculationService
                                          .GetShoppingCartShippingTotal(taxTotalRequest.ShoppingCart, true, out var taxRate);
                    if (shippingExclTax.HasValue && shippingInclTax.HasValue)
                    {
                        shippingTax = shippingInclTax.Value - shippingExclTax.Value;
                        if (shippingTax < decimal.Zero)
                        {
                            shippingTax = decimal.Zero;
                        }

                        if (taxRate > decimal.Zero && shippingTax > decimal.Zero)
                        {
                            if (!taxRates.ContainsKey(taxRate))
                            {
                                taxRates.Add(taxRate, shippingTax);
                            }
                            else
                            {
                                taxRates[taxRate] = taxRates[taxRate] + shippingTax;
                            }
                        }
                    }
                }

                //add at least one tax rate (0%)
                if (!taxRates.Any())
                {
                    taxRates.Add(decimal.Zero, decimal.Zero);
                }

                var taxTotal = subTotalTaxTotal + shippingTax;

                if (taxTotal < decimal.Zero)
                {
                    taxTotal = decimal.Zero;
                }

                taxTotalResult = new TaxTotalResult {
                    TaxTotal = taxTotal, TaxRates = taxRates
                };
                _httpContextAccessor.HttpContext.Items.TryAdd("nop.TaxTotal", taxTotalResult);
            }

            //payment method additional fee
            if (taxTotalRequest.UsePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                var paymentMethodSystemName = taxTotalRequest.Customer != null
                    ? _genericAttributeService.GetAttribute <string>(taxTotalRequest.Customer,
                                                                     NopCustomerDefaults.SelectedPaymentMethodAttribute, taxTotalRequest.StoreId)
                    : string.Empty;

                var paymentMethodAdditionalFee        = _paymentService.GetAdditionalHandlingFee(taxTotalRequest.ShoppingCart, paymentMethodSystemName);
                var paymentMethodAdditionalFeeExclTax = _taxService
                                                        .GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, taxTotalRequest.Customer, out _);
                var paymentMethodAdditionalFeeInclTax = _taxService
                                                        .GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, taxTotalRequest.Customer, out var taxRate);
                var paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;

                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                {
                    paymentMethodAdditionalFeeTax = decimal.Zero;
                }

                taxTotalResult.TaxTotal += paymentMethodAdditionalFeeTax;

                if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                {
                    if (!taxTotalResult.TaxRates.ContainsKey(taxRate))
                    {
                        taxTotalResult.TaxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
                    }
                    else
                    {
                        taxTotalResult.TaxRates[taxRate] = taxTotalResult.TaxRates[taxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }

            return(taxTotalResult);
        }
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Address model</param>
        /// <param name="address">Address entity</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="loadCountries">Countries loading function; pass null if countries do not need to load</param>
        /// <param name="prePopulateWithCustomerFields">Whether to populate model properties with the customer fields (used with the customer entity)</param>
        /// <param name="customer">Customer entity; required if prePopulateWithCustomerFields is true</param>
        /// <param name="overrideAttributesXml">Overridden address attributes in XML format; pass null to use CustomAttributes of the address entity</param>
        public virtual void PrepareAddressModel(AddressModel model,
                                                Address address, bool excludeProperties,
                                                AddressSettings addressSettings,
                                                Func <IList <Country> > loadCountries = null,
                                                bool prePopulateWithCustomerFields    = false,
                                                Customer customer            = null,
                                                string overrideAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException(nameof(addressSettings));
            }

            if (!excludeProperties && address != null)
            {
                model.Id          = address.Id;
                model.FirstName   = address.FirstName;
                model.LastName    = address.LastName;
                model.Email       = address.Email;
                model.Company     = address.Company;
                model.CountryId   = address.CountryId;
                model.CountryName = address.Country != null?_localizationService.GetLocalized(address.Country, x => x.Name) : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null?_localizationService.GetLocalized(address.StateProvince, x => x.Name) : null;

                model.County        = address.County;
                model.City          = address.City;
                model.Address1      = address.Address1;
                model.Address2      = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber   = address.PhoneNumber;
                model.FaxNumber     = address.FaxNumber;
            }

            if (address == null && prePopulateWithCustomerFields)
            {
                if (customer == null)
                {
                    throw new Exception("Customer cannot be null when prepopulating an address");
                }
                model.Email         = customer.Email;
                model.FirstName     = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
                model.LastName      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);
                model.Company       = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute);
                model.Address1      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddressAttribute);
                model.Address2      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddress2Attribute);
                model.ZipPostalCode = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);
                model.City          = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CityAttribute);
                model.County        = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CountyAttribute);
                //ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute);
                model.FaxNumber   = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FaxAttribute);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                var countries = loadCountries();

                if (_addressSettings.PreselectCountryIfOnlyOne && countries.Count == 1)
                {
                    model.CountryId = countries[0].Id;
                }
                else
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                    });
                }

                foreach (var c in countries)
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = _localizationService.GetLocalized(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = EngineContext.Current.Resolve <IWorkContext>().WorkingLanguage.Id;
                    var states     = _stateProvinceService
                                     .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0, languageId)
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = _localizationService.GetLocalized(s, x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }

            //form fields
            model.CompanyEnabled         = addressSettings.CompanyEnabled;
            model.CompanyRequired        = addressSettings.CompanyRequired;
            model.StreetAddressEnabled   = addressSettings.StreetAddressEnabled;
            model.StreetAddressRequired  = addressSettings.StreetAddressRequired;
            model.StreetAddress2Enabled  = addressSettings.StreetAddress2Enabled;
            model.StreetAddress2Required = addressSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled   = addressSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired  = addressSettings.ZipPostalCodeRequired;
            model.CityEnabled            = addressSettings.CityEnabled;
            model.CityRequired           = addressSettings.CityRequired;
            model.CountyEnabled          = addressSettings.CountyEnabled;
            model.CountyRequired         = addressSettings.CountyRequired;
            model.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;

            //customer attribute services
            if (_addressAttributeService != null && _addressAttributeParser != null)
            {
                PrepareCustomAddressAttributes(model, address, overrideAttributesXml);
            }
            if (_addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
Exemple #16
0
        /// <summary>
        /// Prepare the custom user attribute models
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="overrideAttributesXml">Overridden user attributes in XML format; pass null to use CustomUserAttributes of user</param>
        /// <returns>List of the user attribute model</returns>
        public virtual IList <UserAttributeModel> PrepareCustomUserAttributes(User user, string overrideAttributesXml = "")
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var result = new List <UserAttributeModel>();

            var userAttributes = _userAttributeService.GetAllUserAttributes();

            foreach (var attribute in userAttributes)
            {
                var attributeModel = new UserAttributeModel
                {
                    Id         = attribute.Id,
                    Name       = _localizationService.GetLocalized(attribute, x => x.Name),
                    IsRequired = attribute.IsRequired,
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _userAttributeService.GetUserAttributeValues(attribute.Id);
                    foreach (var attributeValue in attributeValues)
                    {
                        var valueModel = new UserAttributeValueModel
                        {
                            Id            = attributeValue.Id,
                            Name          = _localizationService.GetLocalized(attributeValue, x => x.Name),
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(valueModel);
                    }
                }

                //set already selected attributes
                var selectedAttributesXml = !string.IsNullOrEmpty(overrideAttributesXml) ?
                                            overrideAttributesXml :
                                            _genericAttributeService.GetAttribute <string>(user, NopUserDefaults.CustomUserAttributes);

                result.Add(attributeModel);
            }

            return(result);
        }
Exemple #17
0
        /// <summary>
        /// Prepare SendinBlueModel
        /// </summary>
        /// <param name="model">Model</param>
        private void PrepareModel(ConfigurationModel model)
        {
            //load settings for active store scope
            var storeId            = _storeContext.ActiveStoreScopeConfiguration;
            var sendinBlueSettings = _settingService.LoadSetting <SendinBlueSettings>(storeId);

            //whether plugin is configured
            if (string.IsNullOrEmpty(sendinBlueSettings.ApiKey))
            {
                return;
            }

            //prepare common properties
            model.ActiveStoreScopeConfiguration = storeId;
            model.ApiKey                 = sendinBlueSettings.ApiKey;
            model.ListId                 = sendinBlueSettings.ListId;
            model.SmtpKey                = sendinBlueSettings.SmtpKey;
            model.SenderId               = sendinBlueSettings.SenderId;
            model.UseSmsNotifications    = sendinBlueSettings.UseSmsNotifications;
            model.SmsSenderName          = sendinBlueSettings.SmsSenderName;
            model.StoreOwnerPhoneNumber  = sendinBlueSettings.StoreOwnerPhoneNumber;
            model.UseMarketingAutomation = sendinBlueSettings.UseMarketingAutomation;
            model.TrackingScript         = sendinBlueSettings.TrackingScript;

            model.HideGeneralBlock             = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, SendinBlueDefaults.HideGeneralBlock);
            model.HideSynchronizationBlock     = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, SendinBlueDefaults.HideSynchronizationBlock);
            model.HideTransactionalBlock       = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, SendinBlueDefaults.HideTransactionalBlock);
            model.HideSmsBlock                 = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, SendinBlueDefaults.HideSmsBlock);
            model.HideMarketingAutomationBlock = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, SendinBlueDefaults.HideMarketingAutomationBlock);

            //prepare nested search models
            model.MessageTemplateSearchModel.SetGridPageSize();
            model.SmsSearchModel.SetGridPageSize();

            //prepare add SMS model
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(_localizationService.GetResource("Plugins.Misc.SendinBlue.MyPhone"), "0"));
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(_localizationService.GetResource("Plugins.Misc.SendinBlue.CustomerPhone"), "1"));
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(_localizationService.GetResource("Plugins.Misc.SendinBlue.BillingAddressPhone"), "2"));
            model.AddSms.DefaultSelectedPhoneTypeId = model.AddSms.AvailablePhoneTypes.First().Value;

            model.AddSms.AvailableMessages = _messageTemplateService.GetAllMessageTemplates(storeId).Select(messageTemplate =>
            {
                var name = messageTemplate.Name;
                if (storeId == 0 && messageTemplate.LimitedToStores)
                {
                    var storeIds   = _storeMappingService.GetStoresIdsWithAccess(messageTemplate);
                    var storeNames = _storeService.GetAllStores().Where(store => storeIds.Contains(store.Id)).Select(store => store.Name);
                    name           = $"{name} ({string.Join(',', storeNames)})";
                }

                return(new SelectListItem(name, messageTemplate.Id.ToString()));
            }).ToList();
            var defaultSelectedMessage = model.AddSms.AvailableMessages.FirstOrDefault();

            model.AddSms.DefaultSelectedMessageId = defaultSelectedMessage?.Value ?? "0";

            //check whether email account exists
            if (sendinBlueSettings.UseSmtp && _emailAccountService.GetEmailAccountById(sendinBlueSettings.EmailAccountId) != null)
            {
                model.UseSmtp = sendinBlueSettings.UseSmtp;
            }

            //get account info
            var(accountInfo, marketingAutomationEnabled, maKey, accountErrors) = _sendinBlueEmailManager.GetAccountInfo();
            model.AccountInfo                 = accountInfo;
            model.MarketingAutomationKey      = maKey;
            model.MarketingAutomationDisabled = !marketingAutomationEnabled;
            if (!string.IsNullOrEmpty(accountErrors))
            {
                _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {accountErrors}");
            }

            //prepare overridable settings
            if (storeId > 0)
            {
                model.ListId_OverrideForStore                 = _settingService.SettingExists(sendinBlueSettings, settings => settings.ListId, storeId);
                model.UseSmtp_OverrideForStore                = _settingService.SettingExists(sendinBlueSettings, settings => settings.UseSmtp, storeId);
                model.SenderId_OverrideForStore               = _settingService.SettingExists(sendinBlueSettings, settings => settings.SenderId, storeId);
                model.UseSmsNotifications_OverrideForStore    = _settingService.SettingExists(sendinBlueSettings, settings => settings.UseSmsNotifications, storeId);
                model.SmsSenderName_OverrideForStore          = _settingService.SettingExists(sendinBlueSettings, settings => settings.SmsSenderName, storeId);
                model.UseMarketingAutomation_OverrideForStore = _settingService.SettingExists(sendinBlueSettings, settings => settings.UseMarketingAutomation, storeId);
            }

            //check SMTP status
            var(smtpEnabled, smtpErrors) = _sendinBlueEmailManager.SmtpIsEnabled();
            if (!string.IsNullOrEmpty(smtpErrors))
            {
                _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {smtpErrors}");
            }

            //get available contact lists to synchronize
            var(lists, listsErrors) = _sendinBlueEmailManager.GetLists();
            model.AvailableLists    = lists.Select(list => new SelectListItem(list.Name, list.Id)).ToList();
            model.AvailableLists.Insert(0, new SelectListItem("Select list", "0"));
            if (!string.IsNullOrEmpty(listsErrors))
            {
                _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {listsErrors}");
            }

            //get available senders of emails from account
            var(senders, sendersErrors) = _sendinBlueEmailManager.GetSenders();
            model.AvailableSenders      = senders.Select(list => new SelectListItem(list.Name, list.Id)).ToList();
            model.AvailableSenders.Insert(0, new SelectListItem("Select sender", "0"));
            if (!string.IsNullOrEmpty(sendersErrors))
            {
                _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {sendersErrors}");
            }

            //get allowed tokens
            model.AllowedTokens = string.Join(", ", _messageTokenProvider.GetListOfAllowedTokens());

            //create attributes in account
            var attributesErrors = _sendinBlueEmailManager.PrepareAttributes();

            if (!string.IsNullOrEmpty(attributesErrors))
            {
                _notificationService.ErrorNotification($"{SendinBlueDefaults.NotificationMessage} {attributesErrors}");
            }

            //try to set account partner
            if (!sendinBlueSettings.PartnerValueSet)
            {
                var partnerSet = _sendinBlueEmailManager.SetPartner();
                if (partnerSet)
                {
                    sendinBlueSettings.PartnerValueSet = true;
                    _settingService.SaveSetting(sendinBlueSettings, settings => settings.PartnerValueSet, clearCache: false);
                    _settingService.ClearCache();
                }
            }
        }
        public virtual IActionResult Edit(ProductReviewModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProductReviews))
            {
                return(AccessDeniedView());
            }

            //try to get a product review with the specified id
            var productReview = _productService.GetProductReviewById(model.Id);

            if (productReview == null)
            {
                return(RedirectToAction("List"));
            }

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null && _productService.GetProductById(productReview.ProductId).VendorId != _workContext.CurrentVendor.Id)
            {
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                var previousIsApproved = productReview.IsApproved;

                //vendor can edit "Reply text" only
                var isLoggedInAsVendor = _workContext.CurrentVendor != null;
                if (!isLoggedInAsVendor)
                {
                    productReview.Title      = model.Title;
                    productReview.ReviewText = model.ReviewText;
                    productReview.IsApproved = model.IsApproved;
                }

                productReview.ReplyText = model.ReplyText;

                //notify customer about reply
                if (productReview.IsApproved && !string.IsNullOrEmpty(productReview.ReplyText) &&
                    _catalogSettings.NotifyCustomerAboutProductReviewReply && !productReview.CustomerNotifiedOfReply)
                {
                    var customerLanguageId = _genericAttributeService.GetAttribute <Customer, int>(productReview.CustomerId,
                                                                                                   NopCustomerDefaults.LanguageIdAttribute, productReview.StoreId);

                    var queuedEmailIds = _workflowMessageService.SendProductReviewReplyCustomerNotificationMessage(productReview, customerLanguageId);
                    if (queuedEmailIds.Any())
                    {
                        productReview.CustomerNotifiedOfReply = true;
                    }
                }

                _productService.UpdateProductReview(productReview);

                //activity log
                _customerActivityService.InsertActivity("EditProductReview",
                                                        string.Format(_localizationService.GetResource("ActivityLog.EditProductReview"), productReview.Id), productReview);

                //vendor can edit "Reply text" only
                if (!isLoggedInAsVendor)
                {
                    var product = _productService.GetProductById(productReview.ProductId);
                    //update product totals
                    _productService.UpdateProductReviewTotals(product);

                    //raise event (only if it wasn't approved before and is approved now)
                    if (!previousIsApproved && productReview.IsApproved)
                    {
                        _eventPublisher.Publish(new ProductReviewApprovedEvent(productReview));
                    }
                }

                _notificationService.SuccessNotification(_localizationService.GetResource("Admin.Catalog.ProductReviews.Updated"));

                return(continueEditing ? RedirectToAction("Edit", new { id = productReview.Id }) : RedirectToAction("List"));
            }

            //prepare model
            model = _productReviewModelFactory.PrepareProductReviewModel(model, productReview, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
Exemple #19
0
        /// <summary>
        /// Prepare shipping method model
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <returns>Shipping method model</returns>
        public virtual CheckoutShippingMethodModel PrepareShippingMethodModel(IList <ShoppingCartItem> cart, Address shippingAddress)
        {
            var model = new CheckoutShippingMethodModel();

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, shippingAddress, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                //performance optimization. cache returned shipping options.
                //we'll use them later (after a customer has selected an option).
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                       NopCustomerDefaults.OfferedShippingOptionsAttribute,
                                                       getShippingOptionResponse.ShippingOptions,
                                                       _storeContext.CurrentStore.Id);

                //ADDED FOR FREE SHIPPING
                var allshippingMethods = _shippingService.GetAllShippingMethods();

                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new CheckoutShippingMethodModel.ShippingMethodModel
                    {
                        Name        = shippingOption.Name,
                        Description = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                        ShippingOption = shippingOption,
                    };

                    //adjust rate
                    var shippingTotal = _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, cart, out List <DiscountForCaching> _);

                    var rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer);

                    //ADDED FOR FREE SHIPPING
                    if (allshippingMethods.Where(s => s.Name == shippingOption.Name).Any())
                    {
                        var  shippingMethod      = allshippingMethods.Where(s => s.Name == shippingOption.Name).FirstOrDefault();
                        bool isFreeShipping      = _settingService.GetSettingByKey <bool>(string.Format("ShippingRateComputationMethod.FixedByWeightByTotal.FreeShipping.ShippingMethodId{0}", shippingMethod.Id));
                        var  shipppingMethodRate = _settingService.GetSettingByKey <decimal>(string.Format("ShippingRateComputationMethod.FixedByWeightByTotal.Rate.ShippingMethodId{0}", shippingMethod.Id));

                        if (!isFreeShipping)
                        {
                            rateBase = shipppingMethodRate;
                        }
                    }

                    var rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                    soModel.Fee = _priceFormatter.FormatShippingPrice(rate, true);

                    model.ShippingMethods.Add(soModel);
                }

                //find a selected (previously) shipping method
                var selectedShippingOption = _genericAttributeService.GetAttribute <ShippingOption>(_workContext.CurrentCustomer,
                                                                                                    NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id);
                if (selectedShippingOption != null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.ToList()
                                                 .Find(so =>
                                                       !string.IsNullOrEmpty(so.Name) &&
                                                       so.Name.Equals(selectedShippingOption.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                       !string.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName) &&
                                                       so.ShippingRateComputationMethodSystemName.Equals(selectedShippingOption.ShippingRateComputationMethodSystemName, StringComparison.InvariantCultureIgnoreCase));
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
                //if no option has been selected, let's do it for the first one
                if (model.ShippingMethods.FirstOrDefault(so => so.Selected) == null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.FirstOrDefault();
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }

                //notify about shipping from multiple locations
                if (_shippingSettings.NotifyCustomerAboutShippingFromMultipleLocations)
                {
                    model.NotifyCustomerAboutShippingFromMultipleLocations = getShippingOptionResponse.ShippingFromMultipleLocations;
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            return(model);
        }
        /// <summary>
        /// Prepare vendor attribute models
        /// </summary>
        /// <param name="models">List of vendor attribute models</param>
        /// <param name="vendor">Vendor</param>
        protected virtual void PrepareVendorAttributeModels(IList <VendorModel.VendorAttributeModel> models, Vendor vendor)
        {
            if (models == null)
            {
                throw new ArgumentNullException(nameof(models));
            }

            //get available vendor attributes
            var vendorAttributes = _vendorAttributeService.GetAllVendorAttributes();

            foreach (var attribute in vendorAttributes)
            {
                var attributeModel = new VendorModel.VendorAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = attribute.Name,
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _vendorAttributeService.GetVendorAttributeValues(attribute.Id);
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new VendorModel.VendorAttributeValueModel
                        {
                            Id            = attributeValue.Id,
                            Name          = attributeValue.Name,
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(attributeValueModel);
                    }
                }

                //set already selected attributes
                if (vendor != null)
                {
                    var selectedVendorAttributes = _genericAttributeService.GetAttribute <string>(vendor, NopVendorDefaults.VendorAttributes);
                    switch (attribute.AttributeControlType)
                    {
                    case AttributeControlType.DropdownList:
                    case AttributeControlType.RadioList:
                    case AttributeControlType.Checkboxes:
                    {
                        if (!string.IsNullOrEmpty(selectedVendorAttributes))
                        {
                            //clear default selection
                            foreach (var item in attributeModel.Values)
                            {
                                item.IsPreSelected = false;
                            }

                            //select new values
                            var selectedValues = _vendorAttributeParser.ParseVendorAttributeValues(selectedVendorAttributes);
                            foreach (var attributeValue in selectedValues)
                            {
                                foreach (var item in attributeModel.Values)
                                {
                                    if (attributeValue.Id == item.Id)
                                    {
                                        item.IsPreSelected = true;
                                    }
                                }
                            }
                        }
                    }
                    break;

                    case AttributeControlType.ReadonlyCheckboxes:
                    {
                        //do nothing
                        //values are already pre-set
                    }
                    break;

                    case AttributeControlType.TextBox:
                    case AttributeControlType.MultilineTextbox:
                    {
                        if (!string.IsNullOrEmpty(selectedVendorAttributes))
                        {
                            var enteredText = _vendorAttributeParser.ParseValues(selectedVendorAttributes, attribute.Id);
                            if (enteredText.Any())
                            {
                                attributeModel.DefaultValue = enteredText[0];
                            }
                        }
                    }
                    break;

                    case AttributeControlType.Datepicker:
                    case AttributeControlType.ColorSquares:
                    case AttributeControlType.ImageSquares:
                    case AttributeControlType.FileUpload:
                    default:
                        //not supported attribute control types
                        break;
                    }
                }

                models.Add(attributeModel);
            }
        }
        /// <summary>
        /// Gets shopping cart total
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="appliedGiftCards">Applied gift cards</param>
        /// <param name="discountAmount">Applied discount amount</param>
        /// <param name="appliedDiscounts">Applied discounts</param>
        /// <param name="redeemedRewardPoints">Reward points to redeem</param>
        /// <param name="redeemedRewardPointsAmount">Reward points amount in primary store currency to redeem</param>
        /// <param name="useRewardPoints">A value indicating reward points should be used; null to detect current choice of the customer</param>
        /// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param>
        /// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns>
        public override decimal?GetShoppingCartTotal(IList <ShoppingCartItem> cart,
                                                     out decimal discountAmount, out List <DiscountForCaching> appliedDiscounts,
                                                     out List <AppliedGiftCard> appliedGiftCards,
                                                     out int redeemedRewardPoints, out decimal redeemedRewardPointsAmount,
                                                     bool?useRewardPoints = null, bool usePaymentMethodAdditionalFee = true)
        {
            redeemedRewardPoints       = 0;
            redeemedRewardPointsAmount = decimal.Zero;

            var customer = cart.FirstOrDefault(item => item.Customer != null)?.Customer;
            var paymentMethodSystemName = string.Empty;

            if (customer != null)
            {
                paymentMethodSystemName = _genericAttributeService.GetAttribute <string>(customer,
                                                                                         NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id);
            }

            //subtotal without tax
            GetShoppingCartSubTotal(cart, false, out _, out _, out _, out var subTotalWithDiscountBase);
            //subtotal with discount
            var subtotalBase = subTotalWithDiscountBase;

            //LoadAllShippingRateComputationMethods
            var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id);

            //shipping without tax
            var shoppingCartShipping = GetShoppingCartShippingTotal(cart, false, shippingRateComputationMethods);

            //payment method additional fee without tax
            var paymentMethodAdditionalFeeWithoutTax = decimal.Zero;

            if (usePaymentMethodAdditionalFee && !string.IsNullOrEmpty(paymentMethodSystemName))
            {
                var paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart,
                                                                                          paymentMethodSystemName);
                paymentMethodAdditionalFeeWithoutTax =
                    _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee,
                                                              false, customer);
            }

            //tax
            var shoppingCartTax = GetTaxTotal(cart, shippingRateComputationMethods, usePaymentMethodAdditionalFee);

            //Avalara plugin changes
            //adjust tax total according to received value from the Avalara
            shoppingCartTax = _httpContextAccessor.HttpContext.Session
                              .Get <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue)?.TaxTotal ?? shoppingCartTax;
            //Avalara plugin changes

            //order total
            var resultTemp = decimal.Zero;

            resultTemp += subtotalBase;
            if (shoppingCartShipping.HasValue)
            {
                resultTemp += shoppingCartShipping.Value;
            }

            resultTemp += paymentMethodAdditionalFeeWithoutTax;
            resultTemp += shoppingCartTax;
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                resultTemp = _priceCalculationService.RoundPrice(resultTemp);
            }

            //order total discount
            discountAmount = GetOrderTotalDiscount(customer, resultTemp, out appliedDiscounts);

            //sub totals with discount
            if (resultTemp < discountAmount)
            {
                discountAmount = resultTemp;
            }

            //reduce subtotal
            resultTemp -= discountAmount;

            if (resultTemp < decimal.Zero)
            {
                resultTemp = decimal.Zero;
            }
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                resultTemp = _priceCalculationService.RoundPrice(resultTemp);
            }

            //let's apply gift cards now (gift cards that can be used)
            appliedGiftCards = new List <AppliedGiftCard>();
            AppliedGiftCards(cart, appliedGiftCards, customer, ref resultTemp);

            if (resultTemp < decimal.Zero)
            {
                resultTemp = decimal.Zero;
            }
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                resultTemp = _priceCalculationService.RoundPrice(resultTemp);
            }

            if (!shoppingCartShipping.HasValue)
            {
                //we have errors
                return(null);
            }

            var orderTotal = resultTemp;

            //reward points
            SetRewardPoints(ref redeemedRewardPoints, ref redeemedRewardPointsAmount, useRewardPoints, customer, orderTotal);

            orderTotal = orderTotal - redeemedRewardPointsAmount;
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                orderTotal = _priceCalculationService.RoundPrice(orderTotal);
            }
            return(orderTotal);
        }
Exemple #22
0
        public IActionResult CreateUpdateCustomer(int customerId, string worldpayCustomerId)
        {
            //whether user has the authority
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
            {
                return(AccessDeniedView());
            }

            //check whether customer exists
            var customer = _customerService.GetCustomerById(customerId);

            if (customer == null)
            {
                throw new ArgumentException("No customer found with the specified id", nameof(customerId));
            }

            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            //ensure that customer identifier not exceed 25 characters
            if ((worldpayCustomerId?.Length ?? 0) > 25)
            {
                throw new NopException("Worldpay Vault error: Customer ID must not exceed 25 characters");
            }

            //create request parameters to store a customer in Vault
            var createCustomerRequest = new CreateCustomerRequest
            {
                CustomerId = worldpayCustomerId,
                CustomerDuplicateCheckType = CustomerDuplicateCheckType.Error,
                EmailReceiptEnabled        = !string.IsNullOrEmpty(customer.Email),
                Email          = customer.Email,
                FirstName      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute),
                LastName       = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute),
                Company        = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute),
                Phone          = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute),
                BillingAddress = new Address
                {
                    Line1   = customer.BillingAddress?.Address1,
                    City    = customer.BillingAddress?.City,
                    State   = customer.BillingAddress?.StateProvince?.Abbreviation,
                    Country = customer.BillingAddress?.Country?.TwoLetterIsoCode,
                    Zip     = customer.BillingAddress?.ZipPostalCode,
                    Company = customer.BillingAddress?.Company,
                    Phone   = customer.BillingAddress?.PhoneNumber
                }
            };

            //check whether customer is already stored in the Vault and try to store, if it is not so
            var vaultCustomer = _worldpayPaymentManager.GetCustomer(_genericAttributeService.GetAttribute <string>(customer, WorldpayPaymentDefaults.CustomerIdAttribute))
                                ?? _worldpayPaymentManager.CreateCustomer(createCustomerRequest);

            if (vaultCustomer == null)
            {
                throw new NopException("Worldpay Vault error: Failed to create customer. Error details in the log");
            }

            //save Vault customer identifier as a generic attribute
            _genericAttributeService.SaveAttribute(customer, WorldpayPaymentDefaults.CustomerIdAttribute, vaultCustomer.CustomerId);

            //selected tab
            SaveSelectedTabName();

            return(Json(new { Result = true }));
        }
        /// <summary>
        /// Prepare the custom customer attribute models
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="overrideAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
        /// <returns>List of the customer attribute model</returns>
        public virtual IList <CustomerAttributeModel> PrepareCustomCustomerAttributes(Customer customer, string overrideAttributesXml = "")
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var result = new List <CustomerAttributeModel>();

            var customerAttributes = _customerAttributeService.GetAllCustomerAttributes();

            foreach (var attribute in customerAttributes)
            {
                var attributeModel = new CustomerAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = _localizationService.GetLocalized(attribute, x => x.Name),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType,
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _customerAttributeService.GetCustomerAttributeValues(attribute.Id);
                    foreach (var attributeValue in attributeValues)
                    {
                        var valueModel = new CustomerAttributeValueModel
                        {
                            Id            = attributeValue.Id,
                            Name          = _localizationService.GetLocalized(attributeValue, x => x.Name),
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(valueModel);
                    }
                }

                //set already selected attributes
                var selectedAttributesXml = !string.IsNullOrEmpty(overrideAttributesXml) ?
                                            overrideAttributesXml :
                                            _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CustomCustomerAttributes);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Checkboxes:
                {
                    if (!string.IsNullOrEmpty(selectedAttributesXml))
                    {
                        //clear default selection
                        foreach (var item in attributeModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        //select new values
                        var selectedValues = _customerAttributeParser.ParseCustomerAttributeValues(selectedAttributesXml);
                        foreach (var attributeValue in selectedValues)
                        {
                            foreach (var item in attributeModel.Values)
                            {
                                if (attributeValue.Id == item.Id)
                                {
                                    item.IsPreSelected = true;
                                }
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //do nothing
                    //values are already pre-set
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    if (!string.IsNullOrEmpty(selectedAttributesXml))
                    {
                        var enteredText = _customerAttributeParser.ParseValues(selectedAttributesXml, attribute.Id);
                        if (enteredText.Any())
                        {
                            attributeModel.DefaultValue = enteredText[0];
                        }
                    }
                }
                break;

                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                case AttributeControlType.Datepicker:
                case AttributeControlType.FileUpload:
                default:
                    //not supported attribute control types
                    break;
                }

                result.Add(attributeModel);
            }

            return(result);
        }
Exemple #24
0
        public IActionResult Configure()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            //prepare common properties
            var model = new ConfigurationModel
            {
                IsConfigured       = IsConfigured(),
                AccountId          = _avalaraTaxSettings.AccountId,
                LicenseKey         = _avalaraTaxSettings.LicenseKey,
                CompanyCode        = _avalaraTaxSettings.CompanyCode,
                UseSandbox         = _avalaraTaxSettings.UseSandbox,
                CommitTransactions = _avalaraTaxSettings.CommitTransactions,
                ValidateAddress    = _avalaraTaxSettings.ValidateAddress
            };

            //prepare address model
            PrepareAddress(model.TestAddress);

            //prepare tax transaction log model
            PrepareLogModel(model.TaxTransactionLogSearchModel);

            model.HideGeneralBlock = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, AvalaraTaxDefaults.HideGeneralBlock);
            model.HideLogBlock     = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, AvalaraTaxDefaults.HideLogBlock);

            //get account company list (only active)
            var activeCompanies = _avalaraTaxManager.GetAccountCompanies(true);

            if (activeCompanies?.Any() ?? false)
            {
                model.Companies = activeCompanies.OrderBy(company => company.isDefault ?? false ? 0 : 1).Select(company => new SelectListItem
                {
                    Text  = company.isTest ?? false ? $"{company.name} (Test)" : company.name,
                    Value = company.companyCode
                }).ToList();
            }

            var defaultCompanyCode = _avalaraTaxSettings.CompanyCode;

            if (!model.Companies.Any())
            {
                //add the special item for 'there are no companies' with empty guid value
                var noCompaniesText = _localizationService.GetResource("Plugins.Tax.Avalara.Fields.Company.NotExist");
                model.Companies.Add(new SelectListItem {
                    Text = noCompaniesText, Value = Guid.Empty.ToString()
                });
                defaultCompanyCode = Guid.Empty.ToString();
            }
            else if (string.IsNullOrEmpty(_avalaraTaxSettings.CompanyCode) || _avalaraTaxSettings.CompanyCode.Equals(Guid.Empty.ToString()))
            {
                defaultCompanyCode = model.Companies.FirstOrDefault()?.Value;
            }

            //set the default company
            model.CompanyCode = defaultCompanyCode;
            _avalaraTaxSettings.CompanyCode = defaultCompanyCode;
            _settingService.SaveSetting(_avalaraTaxSettings);

            //display warning in case of company currency differ from the primary store currency
            var primaryCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
            var selectedCompany = activeCompanies?.FirstOrDefault(company => company.companyCode.Equals(defaultCompanyCode));

            if (!selectedCompany?.baseCurrencyCode?.Equals(primaryCurrency?.CurrencyCode, StringComparison.InvariantCultureIgnoreCase) ?? false)
            {
                _notificationService.WarningNotification(_localizationService.GetResource("Plugins.Tax.Avalara.Fields.Company.Currency.Warning"));
            }

            return(View("~/Plugins/Tax.Avalara/Views/Configuration/Configure.cshtml", model));
        }
Exemple #25
0
        /// <summary>
        /// Prepare shipping method model
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <returns>Shipping method model</returns>
        public virtual CheckoutShippingMethodModel PrepareShippingMethodModel(IList <ShoppingCartItem> cart, Address shippingAddress)
        {
            var model = new CheckoutShippingMethodModel()
            {
                DisplayPickupInStore = _orderSettings.DisplayPickupInStoreOnShippingMethodPage
            };

            if (_orderSettings.DisplayPickupInStoreOnShippingMethodPage)
            {
                model.PickupPointsModel = PrepareCheckoutPickupPointsModel(cart);
            }

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, shippingAddress, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                //performance optimization. cache returned shipping options.
                //we'll use them later (after a customer has selected an option).
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                       NopCustomerDefaults.OfferedShippingOptionsAttribute,
                                                       getShippingOptionResponse.ShippingOptions,
                                                       _storeContext.CurrentStore.Id);

                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new CheckoutShippingMethodModel.ShippingMethodModel
                    {
                        Name        = shippingOption.Name,
                        Description = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                        ShippingOption = shippingOption,
                    };

                    //adjust rate
                    var shippingTotal = _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, cart, out var _, shippingOption.IsPickupInStore);

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

                    model.ShippingMethods.Add(soModel);
                }

                //find a selected (previously) shipping method
                var selectedShippingOption = _genericAttributeService.GetAttribute <ShippingOption>(_workContext.CurrentCustomer,
                                                                                                    NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id);
                if (selectedShippingOption != null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.ToList()
                                                 .Find(so =>
                                                       !string.IsNullOrEmpty(so.Name) &&
                                                       so.Name.Equals(selectedShippingOption.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                       !string.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName) &&
                                                       so.ShippingRateComputationMethodSystemName.Equals(selectedShippingOption.ShippingRateComputationMethodSystemName, StringComparison.InvariantCultureIgnoreCase));
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
                //if no option has been selected, let's do it for the first one
                if (model.ShippingMethods.FirstOrDefault(so => so.Selected) == null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.FirstOrDefault();
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }

                //notify about shipping from multiple locations
                if (_shippingSettings.NotifyCustomerAboutShippingFromMultipleLocations)
                {
                    model.NotifyCustomerAboutShippingFromMultipleLocations = getShippingOptionResponse.ShippingFromMultipleLocations;
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            return(model);
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            if (!_ePayPaymentSettings.EnableEasyPay && !_ePayPaymentSettings.EnableEpay)
            {
                return;
            }

            var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);

            var orderDescription = _localizationService.GetResource("Plugins.Payments.ePay.Fields.Configure.OrderDescription") + postProcessPaymentRequest.Order.Id;

            var bulgarianCurrency = _currencyService.GetCurrencyByCode("BGN");

            if (bulgarianCurrency != null)
            {
                orderTotal = _currencyService.ConvertFromPrimaryStoreCurrency(orderTotal, bulgarianCurrency);
            }

            var expDate = DateTime.Today.AddDays(1);

            if (_ePayPaymentSettings.ExpirationTimeDays > 0)
            {
                expDate = DateTime.Today.AddDays(_ePayPaymentSettings.ExpirationTimeDays);
            }

            var expDateFormated = expDate.ToString("dd.MM.yyyy");

            var paymentRequest =
                String.Format(
                    "min={0}\nemail={1}\ninvoice={2}\namount={3}\nexp_time={4}\ndescr={5}\nencoding={6}\ncurrency={7}",
                    _ePayPaymentSettings.CustomerNumber, _ePayPaymentSettings.DealerEmail,
                    postProcessPaymentRequest.Order.Id, orderTotal.ToString("0.00", CultureInfo.InvariantCulture), expDateFormated, orderDescription, "cp1251", "BGN");

            var encoded = EncodeTo64(paymentRequest);

            var builder = new StringBuilder();


            //var paymentMethod =
            //    _workContext.CurrentCustomer.GetAttribute<PaymentType>(Constants.CurrentPaymentTypeAttributeKey);

            var paymentMethod =
                _genericAttributeService.GetAttribute <PaymentType>(_workContext.CurrentCustomer, Constants.CurrentPaymentTypeAttributeKey);

            if (paymentMethod == PaymentType.Epay)
            {
                var returnUrl       = _webHelper.GetStoreLocation(false) + "Plugins/PaymentEpay/PDTHandler";
                var cancelReturnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentEpay/CancelOrder";

                builder.Append(GetEpaylUrl());
                builder.AppendFormat("?PAGE=paylogin&encoded={0}&checksum={1}&url_ok={2}&url_cancel={3}", WebUtility.UrlEncode(encoded), EncodeHMACSHA1(encoded, _ePayPaymentSettings.SecretKey), returnUrl, cancelReturnUrl);

                _httpContextAccessor.HttpContext.Response.Redirect(builder.ToString());
            }
            else if (paymentMethod == PaymentType.EasyPay)
            {
                builder.AppendFormat("?encoded={0}&checksum={1}", WebUtility.UrlEncode(encoded), EncodeHMACSHA1(encoded, _ePayPaymentSettings.SecretKey));

                var req = (HttpWebRequest)WebRequest.Create(GetEasyPayUrl() + builder);
                req.Method = "GET";

                string response;


                using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
                {
                    response = WebUtility.UrlDecode(sr.ReadToEnd());
                }

                if (!String.IsNullOrEmpty(response))
                {
                    var responseInfo = response.Split('\n')[0];

                    var splitResponse = responseInfo.Split('=');

                    if (splitResponse[0].ToLower() == "idn")
                    {
                        var responseCode = splitResponse[1];

                        if (!String.IsNullOrEmpty(responseCode))
                        {
                            postProcessPaymentRequest.Order.OrderNotes.Add(new OrderNote
                            {
                                Note = "EasyPay payment code: " + responseCode,
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                            _orderService.UpdateOrder(postProcessPaymentRequest.Order);

                            var easyPayInfoUrl =
                                String.Format("Plugins/PaymentEpay/EasyPayInfo?orderId={0}&easyPayCode={1}",
                                              postProcessPaymentRequest.Order.Id, responseCode);

                            _httpContextAccessor.HttpContext.Response.Redirect(_webHelper.GetStoreLocation(false) + easyPayInfoUrl);
                        }
                    }
                    else
                    {
                        _httpContextAccessor.HttpContext.Response.Redirect(_webHelper.GetStoreLocation(false) + "Plugins/PaymentEpay/EasyPayError?orderId=" + postProcessPaymentRequest.Order.Id);
                    }
                }
            }
        }
        /// <summary>
        /// Prepare details to place an order. It also sets some properties to "processPaymentRequest"
        /// </summary>
        /// <param name="processPaymentRequest">Process payment request</param>
        /// <returns>Details</returns>
        protected override PlaceOrderContainer PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest)
        {
            var details = new PlaceOrderContainer
            {
                //customer
                Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId)
            };

            if (details.Customer == null)
            {
                throw new ArgumentException("Customer is not set");
            }

            //affiliate
            var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId);

            if (affiliate != null && affiliate.Active && !affiliate.Deleted)
            {
                details.AffiliateId = affiliate.Id;
            }

            //check whether customer is guest
            if (details.Customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
            {
                throw new NopException("Anonymous checkout is not allowed");
            }

            //customer currency
            var currencyTmp = _currencyService.GetCurrencyById(
                _genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.CurrencyIdAttribute, processPaymentRequest.StoreId));
            var customerCurrency     = currencyTmp != null && currencyTmp.Published ? currencyTmp : _workContext.WorkingCurrency;
            var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            details.CustomerCurrencyCode = customerCurrency.CurrencyCode;
            details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate;

            //customer language
            details.CustomerLanguage = _languageService.GetLanguageById(
                _genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.LanguageIdAttribute, processPaymentRequest.StoreId));
            if (details.CustomerLanguage == null || !details.CustomerLanguage.Published)
            {
                details.CustomerLanguage = _workContext.WorkingLanguage;
            }

            //billing address
            if (details.Customer.BillingAddress == null)
            {
                throw new NopException("Billing address is not provided");
            }

            if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email))
            {
                throw new NopException("Email is not valid");
            }

            details.BillingAddress = (Address)details.Customer.BillingAddress.Clone();
            if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling)
            {
                throw new NopException($"Country '{details.BillingAddress.Country.Name}' is not allowed for billing");
            }

            //checkout attributes
            details.CheckoutAttributesXml        = _genericAttributeService.GetAttribute <string>(details.Customer, NopCustomerDefaults.CheckoutAttributes, processPaymentRequest.StoreId);
            details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer);

            //load shopping cart
            details.Cart = _shoppingCartService.GetShoppingCart(details.Customer, ShoppingCartType.ShoppingCart, processPaymentRequest.StoreId);

            if (!details.Cart.Any())
            {
                throw new NopException("Cart is empty");
            }

            //validate the entire shopping cart
            var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributesXml, true);

            if (warnings.Any())
            {
                throw new NopException(warnings.Aggregate(string.Empty, (current, next) => $"{current}{next};"));
            }

            //validate individual cart items
            foreach (var sci in details.Cart)
            {
                var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer,
                                                                                   sci.ShoppingCartType, sci.Product, processPaymentRequest.StoreId, sci.AttributesXml,
                                                                                   sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.Id);
                if (sciWarnings.Any())
                {
                    throw new NopException(sciWarnings.Aggregate(string.Empty, (current, next) => $"{current}{next};"));
                }
            }

            //min totals validation
            if (!ValidateMinOrderSubtotalAmount(details.Cart))
            {
                var minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);
                throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"),
                                                     _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false)));
            }

            if (!ValidateMinOrderTotalAmount(details.Cart))
            {
                var minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency);
                throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"),
                                                     _priceFormatter.FormatPrice(minOrderTotalAmount, true, false)));
            }

            //tax display type
            if (_taxSettings.AllowCustomersToSelectTaxDisplayType)
            {
                details.CustomerTaxDisplayType = (TaxDisplayType)_genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.TaxDisplayTypeIdAttribute, processPaymentRequest.StoreId);
            }
            else
            {
                details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType;
            }

            //sub total (incl tax)
            _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true, out var orderSubTotalDiscountAmount, out var orderSubTotalAppliedDiscounts, out var subTotalWithoutDiscountBase, out var _);
            details.OrderSubTotalInclTax         = subTotalWithoutDiscountBase;
            details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount;

            //discount history
            foreach (var disc in orderSubTotalAppliedDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            //sub total (excl tax)
            _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false, out orderSubTotalDiscountAmount,
                                                                  out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out _);
            details.OrderSubTotalExclTax         = subTotalWithoutDiscountBase;
            details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount;

            //shipping info
            if (_shoppingCartService.ShoppingCartRequiresShipping(details.Cart))
            {
                var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(details.Customer,
                                                                                      NopCustomerDefaults.SelectedPickupPointAttribute, processPaymentRequest.StoreId);
                if (_shippingSettings.AllowPickupInStore && pickupPoint != null)
                {
                    var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode);
                    var state   = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id);

                    details.PickupInStore = true;
                    details.PickupAddress = new Address
                    {
                        Address1      = pickupPoint.Address,
                        City          = pickupPoint.City,
                        County        = pickupPoint.County,
                        Country       = country,
                        StateProvince = state,
                        ZipPostalCode = pickupPoint.ZipPostalCode,
                        CreatedOnUtc  = DateTime.UtcNow
                    };
                }
                else
                {
                    if (details.Customer.ShippingAddress == null)
                    {
                        throw new NopException("Shipping address is not provided");
                    }

                    if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email))
                    {
                        throw new NopException("Email is not valid");
                    }

                    //clone shipping address
                    details.ShippingAddress = (Address)details.Customer.ShippingAddress.Clone();
                    if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping)
                    {
                        throw new NopException($"Country '{details.ShippingAddress.Country.Name}' is not allowed for shipping");
                    }
                }

                var shippingOption = _genericAttributeService.GetAttribute <ShippingOption>(details.Customer,
                                                                                            NopCustomerDefaults.SelectedShippingOptionAttribute, processPaymentRequest.StoreId);
                if (shippingOption != null)
                {
                    details.ShippingMethodName = shippingOption.Name;
                    details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName;
                }

                details.ShippingStatus = ShippingStatus.NotYetShipped;
            }
            else
            {
                details.ShippingStatus = ShippingStatus.ShippingNotRequired;
            }

            //LoadAllShippingRateComputationMethods
            var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id);

            //shipping total
            var orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, shippingRateComputationMethods, out var _, out var shippingTotalDiscounts);
            var orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false, shippingRateComputationMethods);

            if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)
            {
                throw new NopException("Shipping total couldn't be calculated");
            }

            details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;
            details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;

            foreach (var disc in shippingTotalDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            //payment total
            var paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName);

            details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer);
            details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer);

            //tax amount
            details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, shippingRateComputationMethods, out var taxRatesDictionary);

            //Avalara plugin changes
            //get previously saved tax details received from the Avalara tax service
            var taxDetails = _httpContextAccessor.HttpContext.Session.Get <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue);

            if (taxDetails != null)
            {
                //adjust tax total according to received value from the Avalara
                if (taxDetails.TaxTotal.HasValue)
                {
                    details.OrderTaxTotal = taxDetails.TaxTotal.Value;
                }

                if (taxDetails.TaxRates?.Any() ?? false)
                {
                    taxRatesDictionary = new SortedDictionary <decimal, decimal>(taxDetails.TaxRates);
                }
            }
            //Avalara plugin changes

            //VAT number
            var customerVatStatus = (VatNumberStatus)_genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.VatNumberStatusIdAttribute);

            if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid)
            {
                details.VatNumber = _genericAttributeService.GetAttribute <string>(details.Customer, NopCustomerDefaults.VatNumberAttribute);
            }

            //tax rates
            details.TaxRates = taxRatesDictionary.Aggregate(string.Empty, (current, next) =>
                                                            $"{current}{next.Key.ToString(CultureInfo.InvariantCulture)}:{next.Value.ToString(CultureInfo.InvariantCulture)};   ");

            //order total (and applied discounts, gift cards, reward points)
            var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount);

            if (!orderTotal.HasValue)
            {
                throw new NopException("Order total couldn't be calculated");
            }

            details.OrderDiscountAmount        = orderDiscountAmount;
            details.RedeemedRewardPoints       = redeemedRewardPoints;
            details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount;
            details.AppliedGiftCards           = appliedGiftCards;
            details.OrderTotal      = orderTotal.Value;
            details.RefundablePrice = details.Cart.Sum(x => x.Product.RefundablePrice * x.Quantity);

            //discount history
            foreach (var disc in orderAppliedDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            processPaymentRequest.OrderTotal = details.OrderTotal;

            //Avalara plugin changes
            //delete custom value
            _httpContextAccessor.HttpContext.Session.Set <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue, null);
            //Avalara plugin changes

            //recurring or standard shopping cart?
            details.IsRecurringShoppingCart = _shoppingCartService.ShoppingCartIsRecurring(details.Cart);
            if (!details.IsRecurringShoppingCart)
            {
                return(details);
            }

            var recurringCyclesError = _shoppingCartService.GetRecurringCycleInfo(details.Cart,
                                                                                  out var recurringCycleLength, out var recurringCyclePeriod, out var recurringTotalCycles);

            if (!string.IsNullOrEmpty(recurringCyclesError))
            {
                throw new NopException(recurringCyclesError);
            }

            processPaymentRequest.RecurringCycleLength = recurringCycleLength;
            processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod;
            processPaymentRequest.RecurringTotalCycles = recurringTotalCycles;

            return(details);
        }
Exemple #28
0
        /// <summary>
        /// Create request parameters to charge transaction
        /// </summary>
        /// <param name="paymentRequest">Payment request parameters</param>
        /// <param name="isRecurringPayment">Whether it is a recurring payment</param>
        /// <returns>Charge request parameters</returns>
        private ExtendedChargeRequest CreateChargeRequest(ProcessPaymentRequest paymentRequest, bool isRecurringPayment)
        {
            //get customer
            var customer = _customerService.GetCustomerById(paymentRequest.CustomerId);

            if (customer == null)
            {
                throw new NopException("Customer cannot be loaded");
            }

            //get the primary store currency
            var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            if (currency == null)
            {
                throw new NopException("Primary store currency cannot be loaded");
            }

            //whether the currency is supported by the Square
            if (!Enum.TryParse(currency.CurrencyCode, out SquareModel.Money.CurrencyEnum moneyCurrency))
            {
                throw new NopException($"The {currency.CurrencyCode} currency is not supported by the Square");
            }

            //check customer's billing address, shipping address and email,
            Func <Address, SquareModel.Address> createAddress = (address) => address == null ? null : new SquareModel.Address
                                                                (
                AddressLine1: address.Address1,
                AddressLine2: address.Address2,
                AdministrativeDistrictLevel1: address.StateProvince?.Abbreviation,
                AdministrativeDistrictLevel2: address.County,
                Country: Enum.TryParse(address.Country?.TwoLetterIsoCode, out SquareModel.Address.CountryEnum countryCode)
                    ? (SquareModel.Address.CountryEnum?)countryCode: null,
                FirstName: address.FirstName,
                LastName: address.LastName,
                Locality: address.City,
                PostalCode: address.ZipPostalCode
                                                                );
            var billingAddress  = createAddress(customer.BillingAddress);
            var shippingAddress = billingAddress == null?createAddress(customer.ShippingAddress) : null;

            var email = customer.BillingAddress != null ? customer.BillingAddress.Email : customer.ShippingAddress?.Email;

            //the transaction is ineligible for chargeback protection if they are not provided
            if ((billingAddress == null && shippingAddress == null) || string.IsNullOrEmpty(email))
            {
                _logger.Warning("Square payment warning: Address or email is not provided, so the transaction is ineligible for chargeback protection", customer: customer);
            }

            //the amount of money, in the smallest denomination of the currency indicated by currency. For example, when currency is USD, amount is in cents;
            //most currencies consist of 100 units of smaller denomination, so we multiply the total by 100
            var orderTotal  = (int)(paymentRequest.OrderTotal * 100);
            var amountMoney = new SquareModel.Money(Amount: orderTotal, Currency: moneyCurrency);

            //create common charge request parameters
            var chargeRequest = new ExtendedChargeRequest
                                (
                AmountMoney: amountMoney,
                BillingAddress: billingAddress,
                BuyerEmailAddress: email,
                DelayCapture: _squarePaymentSettings.TransactionMode == TransactionMode.Authorize,
                IdempotencyKey: Guid.NewGuid().ToString(),
                IntegrationId: !string.IsNullOrEmpty(SquarePaymentDefaults.IntegrationId) ? SquarePaymentDefaults.IntegrationId : null,
                Note: string.Format(SquarePaymentDefaults.PaymentNote, paymentRequest.OrderGuid),
                ReferenceId: paymentRequest.OrderGuid.ToString(),
                ShippingAddress: shippingAddress
                                );

            //try to get previously stored card details
            var storedCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.StoredCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(storedCardKey, out object storedCardId) && !storedCardId.ToString().Equals("0"))
            {
                //check whether customer exists
                var customerId     = _genericAttributeService.GetAttribute <string>(customer, SquarePaymentDefaults.CustomerIdAttribute);
                var squareCustomer = _squarePaymentManager.GetCustomer(customerId);
                if (squareCustomer == null)
                {
                    throw new NopException("Failed to retrieve customer");
                }

                //set 'card on file' to charge
                chargeRequest.CustomerId     = squareCustomer.Id;
                chargeRequest.CustomerCardId = storedCardId.ToString();
                return(chargeRequest);
            }

            //or try to get the card nonce
            var cardNonceKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.CardNonce.Key");

            if (!paymentRequest.CustomValues.TryGetValue(cardNonceKey, out object cardNonce) || string.IsNullOrEmpty(cardNonce?.ToString()))
            {
                throw new NopException("Failed to get the card nonce");
            }

            //remove the card nonce from payment custom values, since it is no longer needed
            paymentRequest.CustomValues.Remove(cardNonceKey);

            //whether to save card details for the future purchasing
            var saveCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.SaveCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(saveCardKey, out object saveCardValue) && saveCardValue is bool saveCard && saveCard && !customer.IsGuest())
            {
                //remove the value from payment custom values, since it is no longer needed
                paymentRequest.CustomValues.Remove(saveCardKey);

                try
                {
                    //check whether customer exists
                    var customerId     = _genericAttributeService.GetAttribute <string>(customer, SquarePaymentDefaults.CustomerIdAttribute);
                    var squareCustomer = _squarePaymentManager.GetCustomer(customerId);

                    if (squareCustomer == null)
                    {
                        //try to create the new one, if not exists
                        var customerRequest = new SquareModel.CreateCustomerRequest
                                              (
                            EmailAddress: customer.Email,
                            Nickname: customer.Username,
                            GivenName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute),
                            FamilyName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute),
                            PhoneNumber: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute),
                            CompanyName: _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute),
                            ReferenceId: customer.CustomerGuid.ToString()
                                              );
                        squareCustomer = _squarePaymentManager.CreateCustomer(customerRequest);
                        if (squareCustomer == null)
                        {
                            throw new NopException("Failed to create customer. Error details in the log");
                        }

                        //save customer identifier as generic attribute
                        _genericAttributeService.SaveAttribute(customer, SquarePaymentDefaults.CustomerIdAttribute, squareCustomer.Id);
                    }

                    //create request parameters to create the new card
                    var cardRequest = new SquareModel.CreateCustomerCardRequest
                                      (
                        BillingAddress: chargeRequest.BillingAddress ?? chargeRequest.ShippingAddress,
                        CardNonce: cardNonce.ToString()
                                      );

                    //set postal code
                    var postalCodeKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.PostalCode.Key");
                    if (paymentRequest.CustomValues.TryGetValue(postalCodeKey, out object postalCode) && !string.IsNullOrEmpty(postalCode.ToString()))
                    {
                        //remove the value from payment custom values, since it is no longer needed
                        paymentRequest.CustomValues.Remove(postalCodeKey);

                        cardRequest.BillingAddress            = cardRequest.BillingAddress ?? new SquareModel.Address();
                        cardRequest.BillingAddress.PostalCode = postalCode.ToString();
                    }

                    //try to create card
                    var card = _squarePaymentManager.CreateCustomerCard(squareCustomer.Id, cardRequest);
                    if (card == null)
                    {
                        throw new NopException("Failed to create card. Error details in the log");
                    }

                    //save card identifier to payment custom values for further purchasing
                    if (isRecurringPayment)
                    {
                        paymentRequest.CustomValues.Add(storedCardKey, card.Id);
                    }

                    //set 'card on file' to charge
                    chargeRequest.CustomerId     = squareCustomer.Id;
                    chargeRequest.CustomerCardId = card.Id;
                    return(chargeRequest);
                }
                catch (Exception exception)
                {
                    _logger.Warning(exception.Message, exception, customer);
                    if (isRecurringPayment)
                    {
                        throw new NopException("For recurring payments you need to save the card details");
                    }
                }
            }
        /// <summary>
        /// Validate customer
        /// </summary>
        /// <param name="usernameOrEmail">Username or email</param>
        /// <param name="password">Password</param>
        /// <returns>Result</returns>
        public virtual CustomerLoginResults ValidateCustomer(string usernameOrEmail, string password)
        {
            var customer = _customerSettings.UsernamesEnabled ?
                           _customerService.GetCustomerByUsername(usernameOrEmail) :
                           _customerService.GetCustomerByEmail(usernameOrEmail);

            if (customer == null)
            {
                return(CustomerLoginResults.CustomerNotExist);
            }
            if (customer.Deleted)
            {
                return(CustomerLoginResults.Deleted);
            }
            if (!customer.Active)
            {
                return(CustomerLoginResults.NotActive);
            }
            //only registered can login
            if (!_customerService.IsRegistered(customer))
            {
                return(CustomerLoginResults.NotRegistered);
            }
            //check whether a customer is locked out
            if (customer.CannotLoginUntilDateUtc.HasValue && customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow)
            {
                return(CustomerLoginResults.LockedOut);
            }

            if (!PasswordsMatch(_customerService.GetCurrentPassword(customer.Id), password))
            {
                //wrong password
                customer.FailedLoginAttempts++;
                if (_customerSettings.FailedPasswordAllowedAttempts > 0 &&
                    customer.FailedLoginAttempts >= _customerSettings.FailedPasswordAllowedAttempts)
                {
                    //lock out
                    customer.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(_customerSettings.FailedPasswordLockoutMinutes);
                    //reset the counter
                    customer.FailedLoginAttempts = 0;
                }

                _customerService.UpdateCustomer(customer);

                return(CustomerLoginResults.WrongPassword);
            }

            var selectedProvider = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.SelectedMultiFactorAuthenticationProviderAttribute);
            var methodIsActive   = _multiFactorAuthenticationPluginManager.IsPluginActive(selectedProvider, customer, _storeContext.CurrentStore.Id);

            if (methodIsActive)
            {
                return(CustomerLoginResults.MultiFactorAuthenticationRequired);
            }
            else if (!string.IsNullOrEmpty(selectedProvider))
            {
                _notificationService.WarningNotification(_localizationService.GetResource("MultiFactorAuthentication.Notification.SelectedMethodIsNotActive"));
            }

            //update login details
            customer.FailedLoginAttempts     = 0;
            customer.CannotLoginUntilDateUtc = null;
            customer.RequireReLogin          = false;
            customer.LastLoginDateUtc        = DateTime.UtcNow;
            _customerService.UpdateCustomer(customer);

            return(CustomerLoginResults.Successful);
        }
        private ProcessPaymentResult ProcessPayment(ProcessPaymentRequest paymentRequest, bool isRecurringPayment)
        {
            var result         = new ProcessPaymentResult();
            var iyzicoSettings = _settingService.LoadSetting <IyzicoPayPaymentSettings>();
            var customer       = _customerService.GetCustomerById(_workContext.CurrentCustomer.Id);

            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_storeContext.CurrentStore.Id)
                       .ToList();
            var subTotalIncludingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal;

            _orderTotalCalculationService.GetShoppingCartSubTotal(cart, subTotalIncludingTax, out decimal orderSubTotalDiscountAmountBase, out List <DiscountForCaching> _, out decimal subTotalWithoutDiscountBase, out decimal _);

            var subtotalBase = subTotalWithoutDiscountBase;
            var subtotal     = _currencyService.ConvertFromPrimaryStoreCurrency(subtotalBase, _workContext.WorkingCurrency);

            CreatePaymentRequest request = new CreatePaymentRequest
            {
                Locale         = Locale.TR.ToString(),
                ConversationId = customer.CustomerGuid.ToString(),
                Price          = subtotal.ToString("##.###").Replace(',', '.')
            };
            var paidprice  = paymentRequest.CustomValues["Installments"].ToString();
            var instalment = paymentRequest.CustomValues["InstalmentCount"].ToString();
            var forceDs    = false;

            if (!string.IsNullOrEmpty(paymentRequest.CustomValues["force3ds"].ToString()))
            {
                forceDs = paymentRequest.CustomValues["force3ds"].ToString() == "1" ? true : false;
            }

            request.PaidPrice = paidprice;
            request.Currency  = _workContext.WorkingCurrency.CurrencyCode.ToString();
            if (!string.IsNullOrEmpty(instalment))
            {
                request.Installment = Convert.ToInt32(instalment);
            }

            request.BasketId       = customer.Id.ToString();
            request.PaymentChannel = PaymentChannel.WEB.ToString();
            request.PaymentGroup   = PaymentGroup.PRODUCT.ToString();

            PaymentCard paymentCard = new PaymentCard
            {
                CardHolderName = paymentRequest.CreditCardName,
                CardNumber     = paymentRequest.CreditCardNumber,
                ExpireMonth    = paymentRequest.CreditCardExpireMonth.ToString(),
                ExpireYear     = paymentRequest.CreditCardExpireYear.ToString(),
                Cvc            = paymentRequest.CreditCardCvv2,
                RegisterCard   = 0
            };

            request.PaymentCard = paymentCard;

            Buyer buyer = new Buyer
            {
                Id   = customer.Id.ToString(),
                Name =
                    _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute) ??
                    customer.BillingAddress.FirstName,
                Surname =
                    _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute) ??
                    customer.BillingAddress.LastName,
                GsmNumber =
                    _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute) ??
                    customer.BillingAddress.PhoneNumber,
                Email          = customer.Email ?? customer.BillingAddress.Email,
                IdentityNumber = paymentRequest.CustomValues["IdentityNumber"].ToString() ??
                                 _genericAttributeService.GetAttribute <string>(customer,
                                                                                NopCustomerDefaults.VatNumberAttribute),
                LastLoginDate       = Convert.ToDateTime(customer.LastLoginDateUtc).ToString("yyyy-M-d hh:mm:ff"),
                RegistrationDate    = customer.CreatedOnUtc.ToString("yyyy-M-d  hh:mm:ff"),
                RegistrationAddress = customer.BillingAddress.Address1,
                Ip      = customer.LastIpAddress,
                City    = customer.BillingAddress.City,
                Country = customer.BillingAddress.Country.Name,
                ZipCode = ""
            };

            request.Buyer = buyer;

            Address shippingAddress = new Address
            {
                ContactName = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName,
                City        = customer.ShippingAddress.City,
                Country     = customer.ShippingAddress.Country.Name,
                Description = customer.ShippingAddress.Address1,
                ZipCode     = ""
            };

            request.ShippingAddress = shippingAddress;

            Address billingAddress = new Address
            {
                ContactName = customer.BillingAddress.FirstName + " " + customer.BillingAddress.LastName,
                City        = customer.BillingAddress.City,
                Country     = customer.BillingAddress.Country.Name,
                Description = customer.BillingAddress.Address1,
                ZipCode     = ""
            };

            request.BillingAddress = billingAddress;

            List <BasketItem> basketItems = new List <BasketItem>();

            foreach (var cartItem in cart)
            {
                var categorys    = _categoryService.GetProductCategoriesByProductId(cartItem.ProductId);
                var categoryName = string.Empty;
                foreach (var category in categorys)
                {
                    if (_categoryService.FindProductCategory(categorys, cartItem.ProductId, category.CategoryId) != null)
                    {
                        categoryName = category.Category.Name;
                    }
                }

                var basketItem = new BasketItem
                {
                    Id        = cartItem.Id.ToString(),
                    Name      = cartItem.Product.Name,
                    Category1 = categoryName,
                    Category2 = "",
                    ItemType  = BasketItemType.PHYSICAL.ToString(),
                    Price     = (_currencyService.ConvertFromPrimaryStoreCurrency(
                                     (cartItem.Product.Price * cartItem.Quantity), _workContext.WorkingCurrency))
                                .ToString("##.###")
                                .Replace(',', '.')
                };
                basketItems.Add(basketItem);
            }
            request.BasketItems = basketItems;
            if (forceDs)
            {
                request.CallbackUrl = $"{_webHelper.GetStoreLocation()}PaymentIyzicoPay/Success";
                ThreedsInitialize threedsInitialize = ThreedsInitialize.Create(request, HelperApiOptions.GetApiContext(iyzicoSettings));
                if (threedsInitialize.Status == "success")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(threedsInitialize.HtmlContent);
                    this._httpContextAccessor.HttpContext.Response.Clear();
                    this._httpContextAccessor.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
                    this._httpContextAccessor.HttpContext.Response.Body.Close();
                    result.AllowStoringCreditCardNumber = true;
                }
                else
                {
                    result.Errors = new List <string> {
                        threedsInitialize.ErrorCode, threedsInitialize.ErrorGroup, threedsInitialize.ErrorMessage
                    };
                }
            }
            else
            {
                Payment payment = Payment.Create(request, HelperApiOptions.GetApiContext(iyzicoSettings));
                if (payment.Status == "success")
                {
                    result.NewPaymentStatus             = payment.FraudStatus == 1 ? PaymentStatus.Paid : PaymentStatus.Pending;
                    result.AuthorizationTransactionId   = payment.PaymentId;
                    result.AuthorizationTransactionCode = payment.AuthCode;
                    result.AllowStoringCreditCardNumber = true;
                    var trans = string.Empty;
                    foreach (var item in payment.PaymentItems)
                    {
                        trans += item.ItemId + "-" + item.PaymentTransactionId + "-";
                    }
                    result.AuthorizationTransactionResult = trans;
                }
                else
                {
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    result.Errors           = new List <string> {
                        payment.ErrorCode, payment.ErrorGroup, payment.ErrorMessage
                    };
                }
            }

            return(result);
        }