Represents a customer
Inheritance: BaseEntity
        public virtual void SignIn(Customer customer, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedCustomer = customer;
        }
        /// <summary>
        /// Add reward points history record
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="points">Number of points to add</param>
        /// <param name="storeId">Store identifier</param>
        /// <param name="message">Message</param>
        /// <param name="usedWithOrder">the order for which points were redeemed as a payment</param>
        /// <param name="usedAmount">Used amount</param>
        public virtual void AddRewardPointsHistoryEntry(Customer customer,
            int points, int storeId, string message = "",
            Order usedWithOrder = null, decimal usedAmount = 0M)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            if (storeId <= 0)
                throw new ArgumentException("Store ID should be valid");

            var rph = new RewardPointsHistory
            {
                Customer = customer,
                StoreId = storeId,
                UsedWithOrder = usedWithOrder,
                Points = points,
                PointsBalance = GetRewardPointsBalance(customer.Id, storeId) + points,
                UsedAmount = usedAmount,
                Message = message,
                CreatedOnUtc = DateTime.UtcNow
            };

            _rphRepository.Insert(rph);

            //event notification
            _eventPublisher.EntityInserted(rph);
        }
        public void Can_check_whether_customer_is_admin()
        {
            var customer = new Customer();

            customer.CustomerRoles.Add(new CustomerRole()
            {
                Active = true,
                Name = "Registered",
                SystemName = SystemCustomerRoleNames.Registered
            });
            customer.CustomerRoles.Add(new CustomerRole()
            {
                Active = true,
                Name = "Guests",
                SystemName = SystemCustomerRoleNames.Guests
            });

            customer.IsAdmin().ShouldBeFalse();

            customer.CustomerRoles.Add(
                new CustomerRole()
                {
                    Active = true,
                    Name = "Administrators",
                    SystemName = SystemCustomerRoleNames.Administrators
                });
            customer.IsAdmin().ShouldBeTrue();
        }
        public virtual int SendVendorEmailValidationMessage(Customer customer, int languageId)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            var store = _storeContext.CurrentStore;
            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplate = GetActiveMessageTemplate("Vendor.EmailValidationMessage", store.Id);
            if (messageTemplate == null)
                return 0;

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List<Token>();
            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);
            _messageTokenProvider.AddVendorTokens(tokens, customer);

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = customer.Email;
            var toName = customer.GetFullName();
            return SendNotification(messageTemplate, emailAccount,
                languageId, tokens,
                toEmail, toName);
        }
 /// <summary>
 /// Gets discount amount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <param name="additionalCharge">Additional charge</param>
 /// <returns>Discount amount</returns>
 public virtual decimal GetDiscountAmount(ProductVariant productVariant, 
     Customer customer,
     decimal additionalCharge)
 {
     Discount appliedDiscount = null;
     return GetDiscountAmount(productVariant, customer, additionalCharge, out appliedDiscount);
 }
 private IList<Token> GenerateTokens(Customer customer)
 {
     var tokens = new List<Token>();
     _messageTokenProvider.AddStoreTokens(tokens);
     _messageTokenProvider.AddCustomerTokens(tokens, customer);
     return tokens;
 }
        public void Can_validate_discount_code()
        {
            var discount = new Discount
            {
                DiscountType = DiscountType.AssignedToSkus,
                Name = "Discount 2",
                UsePercentage = false,
                DiscountPercentage = 0,
                DiscountAmount = 5,
                RequiresCouponCode = true,
                CouponCode = "CouponCode 1",
                DiscountLimitation = DiscountLimitationType.Unlimited,
            };

            var customer = new Customer
            {
                CustomerGuid = Guid.NewGuid(),
                AdminComment = "",
                DiscountCouponCode = "CouponCode 1",
                Active = true,
                Deleted = false,
                CreatedOnUtc = new DateTime(2010, 01, 01),
                LastActivityDateUtc = new DateTime(2010, 01, 02)
            };

            var result1 = _discountService.IsDiscountValid(discount, customer);
            result1.ShouldEqual(true);

            customer.DiscountCouponCode = "CouponCode 2";
            var result2 = _discountService.IsDiscountValid(discount, customer);
            result2.ShouldEqual(false);
        }
        /// <summary>
        /// Filter tier prices for a customer
        /// </summary>
        /// <param name="source">Tier prices</param>
        /// <param name="customer">Customer</param>
        /// <returns>Filtered tier prices</returns>
        public static IList<TierPrice> FilterForCustomer(this IList<TierPrice> source,
            Customer customer)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            var result = new List<TierPrice>();
            foreach (var tierPrice in source)
            {
                //check customer role requirement
                if (tierPrice.CustomerRoleId != 0)
                {
                    if (customer == null)
                        continue;

                    var customerRoles = customer.CustomerRoles.Where(cr => cr.Active).ToList();
                    if (customerRoles.Count == 0)
                        continue;

                    bool roleIsFound = false;
                    foreach (var customerRole in customerRoles)
                        if (customerRole.Id == tierPrice.CustomerRoleId)
                            roleIsFound = true;

                    if (!roleIsFound)
                        continue;

                }

                result.Add(tierPrice);
            }

            return result;
        }
        public virtual IList<ExternalAuthenticationRecord> GetExternalIdentifiersFor(Customer customer)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            return customer.ExternalAuthenticationRecords.ToList();
        }
Beispiel #10
0
        public void Can_get_customer_timeZone_with_customTimeZones_enabled()
        {
            _dateTimeSettings.AllowCustomersToSetTimeZone = true;
            _dateTimeSettings.DefaultStoreTimeZoneId = "E. Europe Standard Time"; //(GMT+02:00) Minsk;

            var customer = new Customer
            {
                Id = 10,
            };

            _genericAttributeService.Expect(x => x.GetAttributesForEntity(customer.Id, "Customer"))
                .Return(new List<GenericAttribute>
                            {
                                new GenericAttribute
                                    {
                                        StoreId = 0,
                                        EntityId = customer.Id,
                                        Key = SystemCustomerAttributeNames.TimeZoneId,
                                        KeyGroup = "Customer",
                                        Value = "Russian Standard Time" //(GMT+03:00) Moscow, St. Petersburg, Volgograd
                                    }
                            });
            var timeZone = _dateTimeHelper.GetCustomerTimeZone(customer);
            timeZone.ShouldNotBeNull();
            timeZone.Id.ShouldEqual("Russian Standard Time");
        }
        private void SyncKlarnaAndNopOrder(KlarnaCheckoutEntity klarnaRequest, Customer customer, out Order nopOrder, out KlarnaCheckoutOrder klarnaCheckoutOrder)
        {
            nopOrder = _orderService.GetOrderByGuid(klarnaRequest.OrderGuid);
            var resourceUri = new Uri(klarnaRequest.KlarnaResourceUri);
            var apiOrder    = _klarnaCheckoutPaymentService.Fetch(resourceUri);

            klarnaCheckoutOrder = KlarnaCheckoutOrder.FromApiOrder(apiOrder);

            // Create the order if it doesn't exist in nop. According to the Klarna Checkout
            // developer guidelines, one should only create the order if the status is
            // 'checkout_complete'.
            // https://developers.klarna.com/en/klarna-checkout/acknowledge-an-order
            if (nopOrder == null && klarnaCheckoutOrder.Status == KlarnaCheckoutOrder.StatusCheckoutComplete)
            {
                if (klarnaCheckoutOrder.Status == KlarnaCheckoutOrder.StatusCheckoutComplete)
                {
                    klarnaRequest.Status = KlarnaCheckoutStatus.Complete;
                    _repository.Update(klarnaRequest);
                }

                _klarnaCheckoutPaymentService.SyncBillingAndShippingAddress(customer, klarnaCheckoutOrder);

                nopOrder = CreateOrderAndSyncWithKlarna(klarnaRequest, customer, klarnaCheckoutOrder, resourceUri);
            }
        }
        /// <summary>
        /// 重写此方法用处理昵称(nickname)
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="parameters"></param>
        public override void AssociateExternalAccountWithUser(Nop.Core.Domain.Customers.Customer customer, Nop.Services.Authentication.External.OpenAuthenticationParameters parameters)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            //find nick name
            string nickName = null;

            if (parameters.UserClaims != null)
            {
                foreach (var userClaim in parameters.UserClaims
                         .Where(x => x.Name != null && !String.IsNullOrEmpty(x.Name.Nickname)))
                {
                    //found
                    nickName = userClaim.Name.Nickname;
                    break;
                }
            }

            var externalAuthenticationRecord = new ExternalAuthenticationRecord()
            {
                CustomerId                = customer.Id,
                Email                     = string.Empty,
                ExternalIdentifier        = parameters.ExternalIdentifier,
                ExternalDisplayIdentifier = nickName,
                OAuthToken                = parameters.OAuthToken,
                OAuthAccessToken          = parameters.OAuthAccessToken,
                ProviderSystemName        = parameters.ProviderSystemName,
            };

            _externalAuthenticationRecordRepository.Insert(externalAuthenticationRecord);
        }
        public virtual void AssociateExternalAccountWithUser(Customer customer, OpenAuthenticationParameters parameters)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            //find email
            string email = null;
            if (parameters.UserClaims != null)
                foreach (var userClaim in parameters.UserClaims
                    .Where(x => x.Contact != null && !String.IsNullOrEmpty(x.Contact.Email)))
                    {
                        //found
                        email = userClaim.Contact.Email;
                        break;
                    }

            var externalAuthenticationRecord = new ExternalAuthenticationRecord()
            {
                CustomerId = customer.Id,
                Email = email,
                ExternalIdentifier = parameters.ExternalIdentifier,
                ExternalDisplayIdentifier = parameters.ExternalDisplayIdentifier,
                OAuthToken = parameters.OAuthToken,
                OAuthAccessToken = parameters.OAuthAccessToken,
                ProviderSystemName = parameters.ProviderSystemName,
            };

            _externalAuthenticationRecordRepository.Insert(externalAuthenticationRecord);
        }
        /// <summary>
        /// Checks discount limitation for customer
        /// </summary>
        /// <param name="discount">Discount</param>
        /// <param name="customer">Customer</param>
        /// <returns>Value indicating whether discount can be used</returns>
        protected virtual bool CheckDiscountLimitations(Discount discount, Customer customer)
        {
            if (discount == null)
                throw new ArgumentNullException("discount");

            switch (discount.DiscountLimitation)
            {
                case DiscountLimitationType.Unlimited:
                    {
                        return true;
                    }
                case DiscountLimitationType.NTimesOnly:
                    {
                        var totalDuh = GetAllDiscountUsageHistory(discount.Id, null, 0, 1).TotalCount;
                        return totalDuh < discount.LimitationTimes;
                    }
                case DiscountLimitationType.NTimesPerCustomer:
                    {
                        if (customer != null && !customer.IsGuest())
                        {
                            //registered customer
                            var totalDuh = GetAllDiscountUsageHistory(discount.Id, customer.Id, 0, 1).TotalCount;
                            return totalDuh < discount.LimitationTimes;
                        }
                        else
                        {
                            //guest
                            return true;
                        }
                    }
                default:
                    break;
            }
            return false;
        }
        public void Can_get_rewardPointsHistoryBalance()
        {
            var customer = new Customer();
            customer.AddRewardPointsHistoryEntry(1, "Points for registration");
            //customer.AddRewardPointsHistoryEntry(3, "Points for registration");

            customer.GetRewardPointsBalance().ShouldEqual(1);
        }
        public void Can_add_rewardPointsHistoryEntry()
        {
            var customer = new Customer();
            customer.AddRewardPointsHistoryEntry(1, "Points for registration");

            customer.RewardPointsHistory.Count.ShouldEqual(1);
            customer.RewardPointsHistory.First().Points.ShouldEqual(1);
        }
 public void Can_check_taxExempt_customer()
 {
     var customer = new Customer();
     customer.IsTaxExempt = true;
     _taxService.IsTaxExempt(null, customer).ShouldEqual(true);
     customer.IsTaxExempt = false;
     _taxService.IsTaxExempt(null, customer).ShouldEqual(false);
 }
        /// <summary>
        /// Create request for tax calculation
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="taxCategoryId">Tax category identifier</param>
        /// <param name="customer">Customer</param>
        /// <returns>Package for tax calculation</returns>
        protected virtual CalculateTaxRequest CreateCalculateTaxRequest(Product product, 
            int taxCategoryId, Customer customer)
        {
            var calculateTaxRequest = new CalculateTaxRequest();
            calculateTaxRequest.Customer = customer;
            if (taxCategoryId > 0)
            {
                calculateTaxRequest.TaxCategoryId = taxCategoryId;
            }
            else
            {
                if (product != null)
                    calculateTaxRequest.TaxCategoryId = product.TaxCategoryId;
            }

            var basedOn = _taxSettings.TaxBasedOn;

            if (basedOn == TaxBasedOn.BillingAddress)
            {
                if (customer == null || customer.BillingAddress == null)
                {
                    basedOn = TaxBasedOn.DefaultAddress;
                }
            }
            if (basedOn == TaxBasedOn.ShippingAddress)
            {
                if (customer == null || customer.ShippingAddress == null)
                {
                    basedOn = TaxBasedOn.DefaultAddress;
                }
            }

            Address address = null;

            switch (basedOn)
            {
                case TaxBasedOn.BillingAddress:
                    {
                        address = customer.BillingAddress;
                    }
                    break;
                case TaxBasedOn.ShippingAddress:
                    {
                        address = customer.ShippingAddress;
                    }
                    break;
                case TaxBasedOn.DefaultAddress:
                default:
                    {
                        address = _addressService.GetAddressById(_taxSettings.DefaultTaxAddressId);
                    }
                    break;
            }

            calculateTaxRequest.Address = address;
            return calculateTaxRequest;
        }
        public virtual void AddVendorTokens(IList<Token> tokens, Customer customer)
        {
            string accountActivationUrl = string.Format("{0}customer/activation?token={1}&email={2}&v={3}", GetStoreUrl(), customer.GetAttribute<string>(SystemCustomerAttributeNames.AccountActivationToken), HttpUtility.UrlEncode(customer.Email), customer.VendorId.ToString());

            tokens.Add(new Token("Vendor.AccountActivationURL", accountActivationUrl, true));

            //event notification
            _eventPublisher.EntityTokensAdded(customer, tokens);
        }
        private void ClearItemsInCart(Customer customer, int storeId)
        {
            var itemsToRemove = customer.ShoppingCartItems.Where(x => x.StoreId == storeId && x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToArray();

            foreach (var item in itemsToRemove)
            {
                _shoppingCartService.DeleteShoppingCartItem(item, ensureOnlyActiveCheckoutAttributes: true);
            }
        }
        public void Can_add_address()
        {
            var customer = new Customer();
            var address = new Address { Id = 1 };

            customer.Addresses.Add(address);

            customer.Addresses.Count.ShouldEqual(1);
            customer.Addresses.First().Id.ShouldEqual(1);
        }
 public FacebookClient GetClient(Customer customer)
 {
     var parameters = new OAuthAuthenticationParameters(Provider.SystemName);
     var identifier = _openAuthenticationService
         .GetExternalIdentifiersFor(customer)
         .FirstOrDefault(o => o.ProviderSystemName == parameters.ProviderSystemName);
     if (identifier== null)
         throw new Exception("No identifier could be loaded");
     return !string.IsNullOrEmpty(identifier.OAuthAccessToken) ? new FacebookClient(identifier.OAuthAccessToken) : null;
 }
        private void AddShippingItemToCart(Customer customer, CartItem item, int currentStoreId)
        {
            var shippingOptions = _shippingService.GetShippingOptions(customer.ShoppingCartItems.ToList(), customer.ShippingAddress, storeId: currentStoreId);

            if (shippingOptions.Success)
            {
                var selectedShippingOption = shippingOptions.ShippingOptions.SingleOrDefault(x => x.Name == item.Reference);
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.SelectedShippingOption, selectedShippingOption, _storeContext.CurrentStore.Id);
            }
        }
        /// <summary>
        /// Delete a customer
        /// </summary>
        /// <param name="customer">Customer</param>
        public virtual void DeleteCustomer(Customer customer)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            if (customer.IsSystemAccount)
                throw new NopException(string.Format("System customer account ({0}) could not be deleted", customer.SystemName));

            customer.Deleted = true;
            UpdateCustomer(customer);
        }
 /// <summary>
 /// Gets the final price
 /// </summary>
 /// <param name="product">Product</param>
 /// <param name="customer">The customer</param>
 /// <param name="additionalCharge">Additional charge</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
 /// <param name="quantity">Shopping cart item quantity</param>
 /// <returns>Final price</returns>
 public virtual decimal GetFinalPrice(Product product,
     Customer customer,
     decimal additionalCharge = decimal.Zero,
     bool includeDiscounts = true,
     int quantity = 1)
 {
     decimal discountAmount;
     Discount appliedDiscount;
     return GetFinalPrice(product, customer, additionalCharge, includeDiscounts,
         quantity, out discountAmount, out appliedDiscount);
 }
        public FacebookClient GetClient(Customer customer)
        {
            var parameters = new OAuthAuthenticationParameters(Provider.SystemName);
            var identifier = _openAuthenticationService
                .GetExternalIdentifiersFor(customer)
                .Where(o => o.ProviderSystemName == parameters.ProviderSystemName)
                .ToList()
                .FirstOrDefault();

            return !string.IsNullOrEmpty(identifier.OAuthAccessToken) ? new FacebookClient(identifier.OAuthAccessToken) : null;
        }
 public new void SetUp()
 {
     _activityType1 = new ActivityLogType
     {
         Id = 1,
         SystemKeyword = "TestKeyword1",
         Enabled = true,
         Name = "Test name1"
     };
     _activityType2 = new ActivityLogType
     {
         Id = 2,
         SystemKeyword = "TestKeyword2",
         Enabled = true,
         Name = "Test name2"
     };
     _customer1 = new Customer
     {
         Id = 1,
         Email = "*****@*****.**",
         Username = "******",
         Deleted = false,
     };
        _customer2 = new Customer
        {
        Id = 2,
        Email = "*****@*****.**",
        Username = "******",
        Deleted = false,
        };
     _activity1 = new ActivityLog
     {
         Id = 1,
         ActivityLogType = _activityType1,
         CustomerId = _customer1.Id,
         Customer = _customer1
     };
     _activity2 = new ActivityLog
     {
         Id = 2,
         ActivityLogType = _activityType1,
         CustomerId = _customer2.Id,
         Customer = _customer2
     };
     _cacheManager = new NopNullCache();
     _workContext = MockRepository.GenerateMock<IWorkContext>();
     _webHelper = MockRepository.GenerateMock<IWebHelper>();
     _activityLogRepository = MockRepository.GenerateMock<IRepository<ActivityLog>>();
     _activityLogTypeRepository = MockRepository.GenerateMock<IRepository<ActivityLogType>>();
     _activityLogTypeRepository.Expect(x => x.Table).Return(new List<ActivityLogType> { _activityType1, _activityType2 }.AsQueryable());
     _activityLogRepository.Expect(x => x.Table).Return(new List<ActivityLog> { _activity1, _activity2 }.AsQueryable());
     _customerActivityService = new CustomerActivityService(_cacheManager, _activityLogRepository, _activityLogTypeRepository, _workContext, null, null, null, _webHelper);
 }
        private void UseCouponCode(Customer customer, string couponCode)
        {
            // nopCommerce currently only has support for one coupon being applied at a time. An issue has been created to fix this.
            // This code will have to be changed when they do so.
            // https://github.com/nopSolutions/nopCommerce/issues/1617

            if (!string.IsNullOrWhiteSpace(couponCode))
            {
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DiscountCouponCode,
                                                       couponCode);
            }
        }
        private static void FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, Customer customer = null)
        {
            //don't log thread abort exception
            if (exception is System.Threading.ThreadAbortException)
                return;

            if (logger.IsEnabled(level))
            {
                string fullMessage = exception == null ? string.Empty : exception.ToString();
                logger.InsertLog(level, message, fullMessage, customer);
            }
        }
 public CustomerRegistrationRequest(Customer customer, string email, string username,
     string password, 
     PasswordFormat passwordFormat,
     bool isApproved = true)
 {
     this.Customer = customer;
     this.Email = email;
     this.Username = username;
     this.Password = password;
     this.PasswordFormat = passwordFormat;
     this.IsApproved = isApproved;
 }
        public void Can_not_add_duplicate_giftCardCouponCodes()
        {
            var customer = new Customer();
            customer.ApplyGiftCardCouponCode("code1");
            customer.ApplyGiftCardCouponCode("code2");
            customer.ApplyGiftCardCouponCode("code1");

            var codes = customer.ParseAppliedGiftCardCouponCodes();
            codes.Length.ShouldEqual(2);
            codes[0].ShouldEqual("code1");
            codes[1].ShouldEqual("code2");
        }
        public void Can_remove_address_assigned_as_billing_address()
        {
            var customer = new Customer();
            var address = new Address { Id = 1 };

            customer.Addresses.Add(address);
            customer.BillingAddress  = address;

            customer.BillingAddress.ShouldBeTheSameAs(customer.Addresses.First());

            customer.RemoveAddress(address);
            customer.Addresses.Count.ShouldEqual(0);
            customer.BillingAddress.ShouldBeNull();
        }
        private void AddPhysicalItemToCart(Customer customer, CartItem item, int currentStoreId)
        {
            var productId     = item.GetProductIdFromPhysicalCartItem();
            var attributesXml = item.GetAttributesXmlFromPhysicalCartItem();
            var product       = _productService.GetProductById(productId);

            _shoppingCartService.AddToCart(
                customer,
                product,
                ShoppingCartType.ShoppingCart,
                currentStoreId,
                attributesXml,
                quantity: item.Quantity);
        }
Beispiel #34
0
        public void Can_not_add_duplicate_addresses()
        {
            var customer = new Customer();
            var address = new Address { Id = 1 };
            var address2 = new Address { Id = 2 };

            customer.AddAddress(address);
            customer.AddAddress(address); // should not add
            customer.AddAddress(address2);

            customer.Addresses.Count.ShouldEqual(2);
            var addresses = customer.Addresses.ToList();
            addresses[0].Id.ShouldEqual(1);
            addresses[1].Id.ShouldEqual(2);
        }
Beispiel #35
0
        /// <summary>
        /// Gets a value indicating whether customer already vited for this poll
        /// </summary>
        /// <param name="poll">Poll</param>
        /// <param name="customer">Customer</param>
        /// <returns>Result</returns>
        public static bool AlreadyVoted(this Poll poll,
            Customer customer)
        {
            if (poll == null)
                throw new ArgumentNullException("poll");

            if (customer == null)
                return false;

            var result = (from pa in poll.PollAnswers
                         from pvr in pa.PollVotingRecords
                         where pvr.CustomerId == customer.Id
                         select pvr).FirstOrDefault() != null;
            return result;
        }
        public void Can_add_render_attributes_withoutPrices()
        {
            string attributes = "";
            //color: green
            attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca1, cav1_1.Id.ToString());
            //custom option: option 1, option 2
            attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_1.Id.ToString());
            attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_2.Id.ToString());
            //custom text
            attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca3, "Some custom text goes here");

            var customer = new Customer();
            string formattedAttributes = _checkoutAttributeFormatter.FormatAttributes(attributes, customer, "<br />", false, false);
            formattedAttributes.ShouldEqual("Color: Green<br />Custom option: Option 1<br />Custom option: Option 2<br />Custom text: Some custom text goes here");
        }
        private string GetSelectedCheckoutAttributesThatHasNotBeenSentToKlarna(Customer customer, int currentStoreId)
        {
            string checkoutAttributesXml = null;

            var originalCheckoutAttributesXml = customer.GetAttribute <string>(SystemCustomerAttributeNames.CheckoutAttributes, currentStoreId);
            var allCheckoutAttributes         = _checkoutAttributeService.GetAllCheckoutAttributes(currentStoreId);

            foreach (var checkoutAttribute in allCheckoutAttributes.Where(x => !x.ShouldHaveValues()))
            {
                var selectedValues = _checkoutAttributeParser.ParseValues(originalCheckoutAttributesXml, checkoutAttribute.Id);
                foreach (var selectedValue in selectedValues)
                {
                    checkoutAttributesXml = _checkoutAttributeParser.AddCheckoutAttribute(checkoutAttributesXml, checkoutAttribute, selectedValue);
                }
            }

            return(checkoutAttributesXml);
        }
        private Order CreateOrderAndSyncWithKlarna(KlarnaCheckoutEntity klarnaRequest, Customer customer, KlarnaCheckoutOrder klarnaCheckoutOrder, Uri resourceUri)
        {
            SyncCartWithKlarnaOrder(customer, klarnaCheckoutOrder);

            var processPaymentRequest = new ProcessPaymentRequest
            {
                OrderGuid  = klarnaRequest.OrderGuid,
                CustomerId = customer.Id,
                StoreId    = _storeContext.CurrentStore.Id,
                PaymentMethodSystemName = KlarnaCheckoutProcessor.PaymentMethodSystemName
            };

            var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);

            // If you tamper with the cart after the klarna widget is rendered nop fails to create the order.
            if (!placeOrderResult.Success)
            {
                var errors = string.Join("; ", placeOrderResult.Errors);
                _logger.Error(string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Klarna has been processed but order could not be created in Nop! Klarna ID={0}, ResourceURI={1}. Errors: {2}",
                                            klarnaCheckoutOrder.Id, klarnaRequest.KlarnaResourceUri, errors), customer: customer);

                _klarnaCheckoutPaymentService.CancelPayment(klarnaCheckoutOrder.Reservation, customer);

                throw new KlarnaCheckoutException("Error creating order: " + errors);
            }

            // Order was successfully created.
            var orderId       = placeOrderResult.PlacedOrder.Id;
            var nopOrder      = _orderService.GetOrderById(orderId);
            var klarnaPayment =
                _paymentService.LoadPaymentMethodBySystemName(KlarnaCheckoutProcessor.PaymentMethodSystemName);

            klarnaPayment.PostProcessPayment(new PostProcessPaymentRequest
            {
                Order = nopOrder
            });

            var orderTotalInCurrentCurrency = _currencyService.ConvertFromPrimaryStoreCurrency(nopOrder.OrderTotal, _workContext.WorkingCurrency);

            // Due to rounding when using prices contains more than 2 decimals (e.g. currency conversion), we allow
            // a slight diff in paid price and nop's reported price.
            // For example nop rounds the prices after _all_ cart item prices have been summed but when sending
            // items to Klarna, each price needs to be rounded separately (Klarna uses 2 decimals).

            // Assume a cart with two items.
            // 1.114 + 2.114 = 3.228 which nop rounds to 3.23.
            // 1.11 + 2.11 is sent to Klarna, which totals 3.22.

            var allowedPriceDiff = orderTotalInCurrentCurrency * 0.01m;
            var diff             = Math.Abs(orderTotalInCurrentCurrency - (klarnaCheckoutOrder.Cart.TotalPriceIncludingTax.Value / 100m));

            if (diff >= allowedPriceDiff)
            {
                var orderTotalInCents = _klarnaCheckoutHelper.ConvertToCents(orderTotalInCurrentCurrency);

                nopOrder.OrderNotes.Add(new OrderNote
                {
                    Note = string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Order total differs from Klarna order. OrderTotal: {0}, OrderTotalInCents: {1}, KlarnaTotal: {2}, AllowedDiff: {3}, Diff: {4}, Uri: {5}",
                                         orderTotalInCurrentCurrency, orderTotalInCents, klarnaCheckoutOrder.Cart.TotalPriceIncludingTax, allowedPriceDiff, diff, resourceUri),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
            }

            nopOrder.OrderNotes.Add(new OrderNote
            {
                Note = "KlarnaCheckout: Order acknowledged. Uri: " + resourceUri,
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });
            _orderService.UpdateOrder(nopOrder);

            if (_orderProcessingService.CanMarkOrderAsAuthorized(nopOrder))
            {
                _orderProcessingService.MarkAsAuthorized(nopOrder);

                // Sometimes shipping isn't required, e.g. if only ordering virtual gift cards.
                // In those cases, make sure the Klarna order is activated.
                if (nopOrder.OrderStatus == OrderStatus.Complete || nopOrder.ShippingStatus == ShippingStatus.ShippingNotRequired)
                {
                    nopOrder.OrderNotes.Add(new OrderNote
                    {
                        Note              = "KlarnaCheckout: Order complete after payment, will try to capture payment.",
                        CreatedOnUtc      = DateTime.UtcNow,
                        DisplayToCustomer = false
                    });
                    _orderService.UpdateOrder(nopOrder);

                    if (_orderProcessingService.CanCapture(nopOrder))
                    {
                        _orderProcessingService.Capture(nopOrder);
                    }
                }
            }

            return(nopOrder);
        }
        private void SyncCartWithKlarnaOrder(Customer customer, KlarnaCheckoutOrder klarnaCheckoutOrder)
        {
            var currentStoreId = _storeContext.CurrentStore.Id;

            var orderCurrency = _currencyService.GetCurrencyByCode(klarnaCheckoutOrder.PurchaseCurrency);

            if (orderCurrency != null)
            {
                _workContext.WorkingCurrency = orderCurrency;
            }

            ClearItemsInCart(customer, currentStoreId);
            ClearDiscountsAndShippingSelection(customer, currentStoreId);

            var physicalItems       = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypePhysical);
            var appliedCoupons      = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypeDiscount && x.HasOrderLevelDiscountCouponCode());
            var appliedGiftCards    = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypeDiscount && x.IsDiscountGiftCardCartItem());
            var appliedRewardPoints = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypeDiscount && x.IsRewardPointsCartItem());
            var checkoutAttributes  = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypeDiscount && x.IsCheckoutAttribtue());
            var shippingItems       = klarnaCheckoutOrder.Cart.Items.Where(x => x.Type == CartItem.TypeShippingFee);

            foreach (var physicalItem in physicalItems)
            {
                AddPhysicalItemToCart(customer, physicalItem, currentStoreId);
                var couponCodes = physicalItem.GetCouponCodesFromPhysicalCartItem();
                foreach (var couponCode in couponCodes)
                {
                    UseCouponCode(customer, couponCode);
                }
            }

            foreach (var coupon in appliedCoupons)
            {
                var couponCode = coupon.GetCouponCodeFromDiscountCouponCartItem();
                UseCouponCode(customer, couponCode);
            }

            foreach (var giftCardCartItem in appliedGiftCards)
            {
                var giftCardId = giftCardCartItem.GetGiftCardIdFromDiscountGiftCardCartItem();
                var giftCard   = _giftCardService.GetGiftCardById(giftCardId);
                customer.ApplyGiftCardCouponCode(giftCard.GiftCardCouponCode);
            }

            if (appliedRewardPoints.Any())
            {
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.UseRewardPointsDuringCheckout, true, currentStoreId);
            }

            var checkoutAttributesXml = GetSelectedCheckoutAttributesThatHasNotBeenSentToKlarna(customer, currentStoreId);

            foreach (var item in checkoutAttributes)
            {
                var ca = _checkoutAttributeService.GetCheckoutAttributeById(item.GetCheckoutAttributeId());
                checkoutAttributesXml = _checkoutAttributeParser.AddCheckoutAttribute(checkoutAttributesXml, ca, item.GetCheckoutAttributeValue());
            }
            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CheckoutAttributes, checkoutAttributesXml, currentStoreId);

            foreach (var shippingItem in shippingItems)
            {
                AddShippingItemToCart(customer, shippingItem, currentStoreId);
                var couponCodes = shippingItem.GetCouponCodesFromShippingItem();
                foreach (var couponCode in couponCodes)
                {
                    UseCouponCode(customer, couponCode);
                }
            }
        }
 private void ClearDiscountsAndShippingSelection(Customer customer, int storeId)
 {
     _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, null);
     _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.DiscountCouponCode, null);
     _genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null, storeId);
 }