예제 #1
0
        /// <summary>
        /// Add customer tokens
        /// </summary>
        /// <param name="tokens">List of already added tokens</param>
        /// <param name="customer">Customer</param>
        public virtual void AddCustomerTokens(IList <Token> tokens, Core.Domain.Customers.Customer customer)
        {
            var firstName =
                _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
            var lastName = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);

            tokens.Add(new Token("Customer.Email", customer.Email));
            tokens.Add(new Token("Customer.Username", customer.Username));
            tokens.Add(new Token("Customer.FullName", $"{firstName} {lastName}"));
            tokens.Add(new Token("Customer.FirstName", firstName));
            tokens.Add(new Token("Customer.LastName", lastName));
            tokens.Add(new Token("Customer.VatNumber", _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.VatNumberAttribute)));
            tokens.Add(new Token("Customer.VatNumberStatus", ((VatNumberStatus)_genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.VatNumberStatusIdAttribute)).ToString()));

            //note: we do not use SEO friendly URLS for these links because we can get errors caused by having .(dot) in the URL (from the email address)
            var passwordRecoveryUrl  = RouteUrl(routeName: "PasswordRecoveryConfirm", routeValues: new { token = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PasswordRecoveryTokenAttribute), guid = customer.Id });
            var accountActivationUrl = RouteUrl(routeName: "AccountActivation", routeValues: new { token = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.AccountActivationTokenAttribute), guid = customer.Id });
            var emailRevalidationUrl = RouteUrl(routeName: "EmailRevalidation", routeValues: new { token = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.EmailRevalidationTokenAttribute), guid = customer.Id });
            var wishlistUrl          = RouteUrl(routeName: "Wishlist", routeValues: new { customerGuid = customer.Id });

            tokens.Add(new Token("Customer.PasswordRecoveryURL", passwordRecoveryUrl, true));
            tokens.Add(new Token("Customer.AccountActivationURL", accountActivationUrl, true));
            tokens.Add(new Token("Customer.EmailRevalidationURL", emailRevalidationUrl, true));
            tokens.Add(new Token("Wishlist.URLForCustomer", wishlistUrl, true));
        }
예제 #2
0
        /// <summary>
        /// Get category identifiers to which a discount is applied
        /// </summary>
        /// <param name="discount">Discount</param>
        /// <param name="customer">Customer</param>
        /// <returns>Category identifiers</returns>
        public virtual IList <Guid> GetAppliedCategoryIds(Discount discount, Core.Domain.Customers.Customer customer, Guid storeId)
        {
            if (discount == null)
            {
                throw new ArgumentNullException(nameof(discount));
            }

            var cacheKey = _cacheKeyService.PrepareKeyForDefaultCache(NopDiscountDefaults.DiscountCategoryIdsModelCacheKey,
                                                                      discount,
                                                                      _customerService.GetCustomerRoleIds(customer),
                                                                      storeId);

            var result = _staticCacheManager.Get(cacheKey, () =>
            {
                var ids = _discountCategoryMappingRepository.Table.Where(dmm => dmm.DiscountId == discount.Id).Select(dmm => dmm.EntityId).Distinct().ToList();

                if (!discount.AppliedToSubCategories)
                {
                    return(ids);
                }

                ids.AddRange(ids.SelectMany(categoryId => GetChildCategoryIds(categoryId, customer, storeId)).ToList());

                return(ids.Distinct().ToList());
            });

            return(result);
        }
        /// <summary>
        /// Sends password recovery message to a customer
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual IList <Guid> SendCustomerPasswordRecoveryMessage(Core.Domain.Customers.Customer customer, Guid languageId, Core.Domain.Stores.Store store)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplates = GetActiveMessageTemplates(MessageTemplateSystemNames.CustomerPasswordRecoveryMessage, store.Id);

            if (!messageTemplates.Any())
            {
                return(new List <Guid>());
            }

            //tokens
            var commonTokens = new List <Token>();

            _messageTokenProvider.AddCustomerTokens(commonTokens, customer);

            return(messageTemplates.Select(messageTemplate =>
            {
                //email account
                var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

                var tokens = new List <Token>(commonTokens);
                _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);

                var toEmail = customer.Email;
                var toName = _customerService.GetCustomerFullName(customer);

                return SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName);
            }).ToList());
        }
        private void InsertNewCustomers(DataTable data)
        {
            IList <CustomerRole> roles = _customerService.GetAllCustomerRoles();

            foreach (DataRow row in data.Rows)
            {
                var email = row[(int)SpreadSheet.Header.EMail].ToString();
                // empty row ??
                if (email.Length < 3)
                {
                    BadCount++;
                    continue;
                }

                // Existing customer ??

                var current = _customerService.GetCustomerByEmail(email);

                bool excludeProperties = current != null;

                _workContext.CurrentCustomer = excludeProperties ? current : _customerService.InsertGuestCustomer();

                Core.Domain.Customers.Customer customer = _workContext.CurrentCustomer;
                CustomerModel model = new CustomerModel();

                var v = new Import(_storeService, _localizationService, _workContext, _dateTimeHelper);

                v.PrepareCustomerModel(model, customer, excludeProperties);
            }
        }
예제 #5
0
        /// <summary>
        /// Get full name
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <returns>Customer full name</returns>
        public virtual string GetCustomerFullName(Core.Domain.Customers.Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var firstName = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
            var lastName  = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);

            var fullName = string.Empty;

            if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName))
            {
                fullName = $"{firstName} {lastName}";
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(firstName))
                {
                    fullName = firstName;
                }

                if (!string.IsNullOrWhiteSpace(lastName))
                {
                    fullName = lastName;
                }
            }

            return(fullName);
        }
예제 #6
0
 public bool AddCustomer(Core.Domain.Customers.Customer customer, List <User> users)
 {
     try
     {
         customer.Id = Guid.NewGuid();
         _customerRepository.Insert(customer);
         if (!users.Any())
         {
             return(true);
         }
         var passwordHash = new PasswordHasher();
         foreach (var user in users)
         {
             if (_objectContext.Users.Any(u => u.UserName == user.UserName))
             {
                 continue;
             }
             user.PasswordHash = passwordHash.HashPassword(user.Password);
             user.CustomerId   = customer.Id;
             _userManager.Create(user);
             _userManager.AddToRole(user.Id, user.Role);
         }
         return(true);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e);
         return(false);
     }
 }
예제 #7
0
        /// <summary>
        /// Gets a customer shipping address
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <returns>Result</returns>
        public virtual Address GetCustomerShippingAddress(Core.Domain.Customers.Customer customer)
        {
            if (customer is null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            return(GetCustomerAddress(customer.Id, customer.ShippingAddressId ?? Guid.Empty));
        }
예제 #8
0
        /// <summary>
        /// Insert the customer
        /// </summary>
        /// <param name="customer">Customer</param>
        public virtual void InsertCustomer(Core.Domain.Customers.Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            _customerRepository.Insert(customer);
        }
예제 #9
0
        /// <summary>
        /// Gets all categories
        /// </summary>
        /// <param name="storeId">Store identifier; 0 if you want to get all records</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Categories</returns>
        public virtual IList <Category> GetAllCategories(Core.Domain.Customers.Customer currentCustomer, Guid storeId = default, bool showHidden = false)
        {
            var key = _cacheKeyService.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesAllCacheKey,
                                                                 storeId,
                                                                 _customerService.GetCustomerRoleIds(currentCustomer),
                                                                 showHidden);

            var categories = _staticCacheManager.Get(key, () => GetAllCategories(string.Empty, storeId, showHidden: showHidden).ToList());

            return(categories);
        }
예제 #10
0
        /// <summary>
        /// Delete Categories
        /// </summary>
        /// <param name="categories">Categories</param>
        public virtual void DeleteCategories(IList <Category> categories, Core.Domain.Customers.Customer currentCustomer, Guid storeId)
        {
            if (categories == null)
            {
                throw new ArgumentNullException(nameof(categories));
            }

            foreach (var category in categories)
            {
                DeleteCategory(category, currentCustomer, storeId);
            }
        }
        /// <summary>
        /// Get transaction line items
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="storeId">Store identifier</param>
        /// <returns>List of transaction items</returns>
        private List <BasketItem> GetItems(Core.Domain.Customers.Customer customer, int storeId)
        {
            var items = new List <BasketItem>();

            //get current shopping cart
            var shoppingCart = _shoppingCartService.GetShoppingCart(customer, ShoppingCartType.ShoppingCart, storeId);

            //define function to create item
            BasketItem createItem(decimal price, string productId, string productName, string categoryName, BasketItemType itemType = BasketItemType.PHYSICAL)
            {
                return(new BasketItem
                {
                    Id = productId,
                    Name = productName,
                    Category1 = categoryName,
                    ItemType = itemType.ToString(),
                    Price = Convert.ToDecimal(price, CultureInfo.InvariantCulture).ToString("f8", CultureInfo.InvariantCulture),
                });
            }

            items.AddRange(shoppingCart.Select(sci =>
            {
                var product = _productService.GetProductById(sci.ProductId);

                var shoppingCartUnitPriceWithDiscountBase = _taxService.GetProductPrice(product, _shoppingCartService.GetUnitPrice(sci), out var _);
                var shoppingCartUnitPriceWithDiscount     = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartUnitPriceWithDiscountBase, _workContext.WorkingCurrency);

                return(createItem(shoppingCartUnitPriceWithDiscount * sci.Quantity,
                                  product.Id.ToString(),
                                  product.Name,
                                  _categoryService.GetProductCategoriesByProductId(sci.ProductId).Aggregate(",", (all, pc) =>
                {
                    var res = _categoryService.GetCategoryById(pc.CategoryId).Name;
                    res = all == "," ? res : all + ", " + res;
                    return res;
                })));
            }));

            //shipping without tax
            var shoppingCartShipping = _orderTotalCalculationService.GetShoppingCartShippingTotal(shoppingCart, false);

            if (shoppingCartShipping.HasValue && shoppingCartShipping.Value != 0)
            {
                items.Add(createItem(shoppingCartShipping ?? 0,
                                     Guid.NewGuid().ToString(),
                                     "Shipping",
                                     "Shipping",
                                     BasketItemType.VIRTUAL));
            }

            return(items);
        }
예제 #12
0
        /// <summary>
        /// Gets list of customer roles
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="showHidden">A value indicating whether to load hidden records</param>
        /// <returns>Result</returns>
        public virtual IList <CustomerRole> GetCustomerRoles(Core.Domain.Customers.Customer customer, bool showHidden = false)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var query = GetCustomerRolesBase(customer.Id, showHidden);

            var key = _cacheKeyService.PrepareKeyForShortTermCache(NopCustomerServicesDefaults.CustomerRolesCacheKey, customer, showHidden);

            return(_staticCacheManager.Get(key, () => query.ToList()));
        }
예제 #13
0
        /// <summary>
        /// Get transaction line items
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="storeId">Store identifier</param>
        /// <returns>List of transaction items</returns>
        private List <BasketItem> GetItems(Core.Domain.Customers.Customer customer, int storeId)
        {
            var items = new List <BasketItem>();

            //get current shopping cart
            var shoppingCart = _shoppingCartService.GetShoppingCart(customer, ShoppingCartType.ShoppingCart, storeId);

            //define function to create item
            BasketItem createItem(decimal price, string productId, string productName, string categoryName, BasketItemType itemType = BasketItemType.PHYSICAL)
            {
                return(new BasketItem
                {
                    Id = productId,
                    Name = productName,
                    Category1 = categoryName,
                    ItemType = itemType.ToString(),
                    Price = Convert.ToDecimal(price, CultureInfo.InvariantCulture).ToString("f8", CultureInfo.InvariantCulture),
                });
            }

            items.AddRange(shoppingCart.Where(shoppingCartItem => shoppingCartItem.ProductId != 0).Select(shoppingCartItem =>
            {
                var product = _productService.GetProductById(shoppingCartItem.ProductId);

                var productCategories = _categoryService.GetProductCategoriesByProductId(product.Id).FirstOrDefault();

                var category = _categoryService.GetCategoryById(productCategories.CategoryId);

                return(createItem(product.Price * shoppingCartItem.Quantity,
                                  product.Id.ToString(),
                                  product.Name,
                                  category.Name));
            }));

            //LoadAllShippingRateComputationMethods
            var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id);
            //shipping without tax
            decimal taxRate = 0;
            var     shoppingCartShipping = _orderTotalCalculationService.GetShoppingCartShippingTotal(shoppingCart, false, out taxRate /*shippingRateComputationMethods*/);

            if (shoppingCartShipping.HasValue)
            {
                items.Add(createItem(shoppingCartShipping ?? 0,
                                     Guid.NewGuid().ToString(),
                                     "Shipping",
                                     "Shipping",
                                     BasketItemType.VIRTUAL));
            }

            return(items);
        }
예제 #14
0
        public static stripe.CustomerCreateOptions CreateCustomerOptions(this Core.Domain.Customers.Customer customer, StripePaymentSettings paymentSettings)
        {
            var customerCreateOptions = new stripe.CustomerCreateOptions()
            {
                Email = customer.Email,
            };

            customerCreateOptions.Metadata = new Dictionary <string, string>()
            {
                { paymentSettings.GetCustomerIdKey(), customer.Id.ToString() }
            };

            return(customerCreateOptions);
        }
        protected virtual void WriteCustomerToXml(XmlTextWriter writer, Order order, Core.Domain.Customers.Customer customer)
        {
            writer.WriteStartElement("Customer");

            writer.WriteElementString("CustomerCode", customer.Email);
            writer.WriteStartElement("BillTo");
            WriteAddressToXml(writer, true, order.BillingAddress);
            writer.WriteEndElement();
            writer.WriteStartElement("ShipTo");
            WriteAddressToXml(writer, false, order.BillingAddress);
            writer.WriteEndElement();

            writer.WriteEndElement();
            writer.Flush();
        }
예제 #16
0
        /// <summary>
        /// Get customer role identifiers
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="showHidden">A value indicating whether to load hidden records</param>
        /// <returns>Customer role identifiers</returns>
        public virtual Guid[] GetCustomerRoleIds(Core.Domain.Customers.Customer customer, bool showHidden = false)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var query = from cr in _customerRoleRepository.Table
                        join crm in _customerCustomerRoleMappingRepository.Table on cr.Id equals crm.CustomerRoleId
                        where crm.CustomerId == customer.Id &&
                        (showHidden || cr.Active)
                        select cr.Id;

            var key = _cacheKeyService.PrepareKeyForShortTermCache(NopCustomerServicesDefaults.CustomerRoleIdsCacheKey, customer, showHidden);

            return(_staticCacheManager.Get(key, () => query.ToArray()));
        }
예제 #17
0
        private bool Authorized()
        {
            return(true);

            Core.Domain.Customers.Customer curCustomer = _workContext.CurrentCustomer;

            if (curCustomer.IsInCustomerRole("Administrators"))
            {
                return(true);
            }
            if (curCustomer.IsInCustomerRole("PaaManagementAdministrators"))
            {
                return(true);
            }

            return(false);
        }
예제 #18
0
        /// <summary>
        /// Get manufacturer identifiers to which a discount is applied
        /// </summary>
        /// <param name="discount">Discount</param>
        /// <param name="customer">Customer</param>
        /// <returns>Manufacturer identifiers</returns>
        public virtual IList <Guid> GetAppliedManufacturerIds(Discount discount, Core.Domain.Customers.Customer customer)
        {
            if (discount == null)
            {
                throw new ArgumentNullException(nameof(discount));
            }

            var cacheKey = _cacheKeyService.PrepareKeyForDefaultCache(NopDiscountDefaults.DiscountManufacturerIdsModelCacheKey,
                                                                      discount,
                                                                      _customerService.GetCustomerRoleIds(customer),
                                                                      _storeRepository.Table.FirstOrDefault());

            var result = _discountManufacturerMappingRepository.Table.Where(dmm => dmm.DiscountId == discount.Id)
                         .Select(dmm => dmm.EntityId).ToCachedList(cacheKey);

            return(result);
        }
예제 #19
0
        /// <summary>
        /// Gets a value indicating whether customer is in a certain customer role
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="customerRoleSystemName">Customer role system name</param>
        /// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
        /// <returns>Result</returns>
        public virtual bool IsInCustomerRole(Core.Domain.Customers.Customer customer,
                                             string customerRoleSystemName, bool onlyActiveCustomerRoles = true)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (string.IsNullOrEmpty(customerRoleSystemName))
            {
                throw new ArgumentNullException(nameof(customerRoleSystemName));
            }

            var customerRoles = GetCustomerRoles(customer, !onlyActiveCustomerRoles);

            return(customerRoles?.Any(cr => cr.SystemName == customerRoleSystemName) ?? false);
        }
예제 #20
0
        public ActionResult ProcessRoute(Core.Domain.Customers.Customer customer, string returnUrl)
        {
            var registerResult = Utilities.ViewPath(_storeName, "RegisterResult");


            switch (_customerSettings.UserRegistrationType)

            {
            case UserRegistrationType.EmailValidation:
            {
                //email validation message
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken,
                                                       Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                //result
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            case UserRegistrationType.AdminApproval:
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            case UserRegistrationType.Standard:
            {
                //send customer welcome message
                _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                var redirectUrl = Url.RouteUrl(registerResult, new { resultId = (int)UserRegistrationType.Standard });

                if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                }

                return(Redirect(redirectUrl));
            }

            default:
            {
                return(RedirectToRoute("HomePage"));
            }
            }
        }
예제 #21
0
        /// <summary>
        /// Delete category
        /// </summary>
        /// <param name="category">Category</param>
        public virtual void DeleteCategory(Category category, Core.Domain.Customers.Customer currentCustomer, Guid storeId)
        {
            if (category == null)
            {
                throw new ArgumentNullException(nameof(category));
            }

            category.Deleted = true;
            UpdateCategory(category);


            //reset a "Parent category" property of all child subcategories
            var subcategories = GetAllCategoriesByParentCategoryId(category.Id, currentCustomer, storeId, true);

            foreach (var subcategory in subcategories)
            {
                subcategory.ParentCategoryId = Guid.Empty;
                UpdateCategory(subcategory);
            }
        }
예제 #22
0
        /// <summary>
        /// Remove a customer-address mapping record
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="address">Address</param>
        public virtual void RemoveCustomerAddress(Core.Domain.Customers.Customer customer, Address address)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (_customerAddressMappingRepository.Table.FirstOrDefault(m => m.AddressId == address.Id && m.CustomerId == customer.Id) is CustomerAddressMapping mapping)
            {
                if (customer.BillingAddressId == address.Id)
                {
                    customer.BillingAddressId = null;
                }
                if (customer.ShippingAddressId == address.Id)
                {
                    customer.ShippingAddressId = null;
                }

                _customerAddressMappingRepository.Delete(mapping);
            }
        }
예제 #23
0
        public void   PrepareCustomerModel(CustomerModel model, Core.Domain.Customers.Customer customer,
                                           bool excludeProperties)
        {
            if (customer != null)
            {
                var allStores = _storeService.GetAllStores();
                model.Id = customer.Id;
                if (!excludeProperties)
                {
                    model.Email        = customer.Email;
                    model.Username     = customer.Username;
                    model.VendorId     = customer.VendorId;
                    model.AdminComment = customer.AdminComment;
                    model.IsTaxExempt  = customer.IsTaxExempt;
                    model.Active       = customer.Active;


                    if (customer.RegisteredInStoreId == 0 || allStores.All(s => s.Id != customer.RegisteredInStoreId))
                    {
                        model.RegisteredInStore = string.Empty;
                    }
                    else
                    {
                        model.RegisteredInStore = allStores.First(s => s.Id == customer.RegisteredInStoreId).Name;
                    }


                    model.TimeZoneId          = customer.GetAttribute <string>(SystemCustomerAttributeNames.TimeZoneId);
                    model.VatNumber           = customer.GetAttribute <string>(SystemCustomerAttributeNames.VatNumber);
                    model.VatNumberStatusNote = ((VatNumberStatus)customer.GetAttribute <int>(SystemCustomerAttributeNames.VatNumberStatusId))
                                                .GetLocalizedEnum(_localizationService, _workContext);
                    model.CreatedOn        = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc);
                    model.LastActivityDate = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc);
                    model.LastIpAddress    = customer.LastIpAddress;
                    model.LastVisitedPage  = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastVisitedPage);

                    model.SelectedCustomerRoleIds = customer.CustomerRoles.Select(cr => cr.Id).ToList();
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Inserts a customer-address mapping record
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="address">Address</param>
        public virtual void InsertCustomerAddress(Core.Domain.Customers.Customer customer, Address address)
        {
            if (customer is null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (address is null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            if (_customerAddressMappingRepository.Table.FirstOrDefault(m => m.AddressId == address.Id && m.CustomerId == customer.Id) is null)
            {
                var mapping = new CustomerAddressMapping
                {
                    AddressId  = address.Id,
                    CustomerId = customer.Id
                };

                _customerAddressMappingRepository.Insert(mapping);
            }
        }
예제 #25
0
        /// <summary>
        /// Gets all categories displayed on the home page
        /// </summary>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Categories</returns>
        public virtual IList <Category> GetAllCategoriesDisplayedOnHomepage(Core.Domain.Customers.Customer currentCustomer, Guid storeId, bool showHidden = false)
        {
            var query = from c in _categoryRepository.Table
                        orderby c.DisplayOrder, c.Id
            where c.Published &&
            !c.Deleted &&
            c.ShowOnHomepage
            select c;

            var categories = query.ToCachedList(_cacheKeyService.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesAllDisplayedOnHomepageCacheKey));

            if (showHidden)
            {
                return(categories);
            }

            var cacheKey = _cacheKeyService.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesDisplayedOnHomepageWithoutHiddenCacheKey,
                                                                      currentCustomer, _customerService.GetCustomerRoleIds(currentCustomer));

            var result = _staticCacheManager.Get(cacheKey, () => categories);

            return(result);
        }
        public virtual CustomerShortModel PrepareCustomerShortModel(int Id)
        {
            var customer = _customerService.Find(Id, p => p.Posts);

            if (customer == null)
            {
                customer                    = new Core.Domain.Customers.Customer();
                customer.Name               = "Cengiz";
                customer.Email              = "*****@*****.**";
                customer.Password           = "******";
                customer.PasswordSalt       = "001453";
                customer.PasswordFormatType = 1;
                _customerService.Insert(customer);
                // throw new ArgumentNullException($"Customer",$"Customer cannot be null");
            }

            var customerShortModel = new CustomerShortModel();

            customerShortModel.Email = customer.Email;
            customerShortModel.Name  = customer.Name;

            return(customerShortModel);
        }
예제 #27
0
        /// <summary>
        /// Gets child category identifiers
        /// </summary>
        /// <param name="parentCategoryId">Parent category identifier</param>
        /// <param name="storeId">Store identifier; 0 if you want to get all records</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Category identifiers</returns>
        public virtual IList <Guid> GetChildCategoryIds(Guid parentCategoryId, Core.Domain.Customers.Customer currentCustomer, Guid storeId = default, bool showHidden = false)
        {
            var cacheKey = _cacheKeyService.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesChildIdentifiersCacheKey,
                                                                      parentCategoryId,
                                                                      _customerService.GetCustomerRoleIds(currentCustomer),
                                                                      storeId,
                                                                      showHidden);

            return(_staticCacheManager.Get(cacheKey, () =>
            {
                //little hack for performance optimization
                //there's no need to invoke "GetAllCategoriesByParentCategoryId" multiple times (extra SQL commands) to load childs
                //so we load all categories at once (we know they are cached) and process them server-side
                var categoriesIds = new List <Guid>();
                var categories = GetAllCategories(currentCustomer, storeId: storeId, showHidden: showHidden)
                                 .Where(c => c.ParentCategoryId == parentCategoryId)
                                 .Select(c => c.Id)
                                 .ToList();
                categoriesIds.AddRange(categories);
                categoriesIds.AddRange(categories.SelectMany(cId => GetChildCategoryIds(cId, currentCustomer, storeId, showHidden)));

                return categoriesIds;
            }));
        }
예제 #28
0
 public static stripe.Customer GetOrCreateCustomer(this stripe.CustomerService customerService, Core.Domain.Customers.Customer customer, string stripeCustomerId, StripePaymentSettings paymentSettings)
 {
     if (!string.IsNullOrEmpty(stripeCustomerId))
     {
         return(customerService.Get(stripeCustomerId));
     }
     else
     {
         return(customerService.Create(customer.CreateCustomerOptions(paymentSettings)));
     }
 }
예제 #29
0
        public static stripe.Customer GetOrCreateCustomer(this stripe.CustomerService customerService, Core.Domain.Customers.Customer customer, IGenericAttributeService genericAttributeService, StripePaymentSettings paymentSettings)
        {
            string stripeCustomerId = genericAttributeService.GetAttribute <string>(customer, paymentSettings.GetCustomerIdKey());

            stripe.Customer result = customerService.GetOrCreateCustomer(customer, stripeCustomerId, paymentSettings);

            if (string.IsNullOrEmpty(stripeCustomerId))
            {
                genericAttributeService.SaveAttribute(customer, paymentSettings.GetCustomerIdKey(), result.Id);
            }

            return(result);
        }
예제 #30
0
        /// <summary>
        /// Gets all categories filtered by parent category identifier
        /// </summary>
        /// <param name="parentCategoryId">Parent category identifier</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Categories</returns>
        public virtual IList <Category> GetAllCategoriesByParentCategoryId(Guid parentCategoryId, Core.Domain.Customers.Customer currentCustomer, Guid storeId,
                                                                           bool showHidden = false)
        {
            var key = _cacheKeyService.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoriesByParentCategoryIdCacheKey,
                                                                 parentCategoryId, showHidden, currentCustomer, storeId);

            var query = _categoryRepository.Table;

            if (!showHidden)
            {
                query = query.Where(c => c.Published);
            }

            query = query.Where(c => c.ParentCategoryId == parentCategoryId);
            query = query.Where(c => !c.Deleted);
            query = query.OrderBy(c => c.DisplayOrder).ThenBy(c => c.Id);

            if (!showHidden)
            {
                query = query.Distinct().OrderBy(c => c.DisplayOrder).ThenBy(c => c.Id);
            }

            var categories = query.ToCachedList(key);

            return(categories);
        }