Пример #1
0
        public JsonResult StoreDashboardReport()
        {
            var allOrders        = _orderService.GetOrders(0, 0, null, null, null, null, null, null, null);
            var registeredRoleId = _customerService.GetCustomerRoleBySystemName("Registered").Id;
            var model            = new StoreDashboardReportModel
            {
                ProductsCount              = _catalogSearchService.PrepareQuery(new CatalogSearchQuery()).Count().ToString("N0"),
                CategoriesCount            = _categoryService.BuildCategoriesQuery(showHidden: true).Count().ToString("N0"),
                ManufacturersCount         = _manufacturerService.GetManufacturers().Count().ToString("N0"),
                AttributesCount            = _productAttributeService.GetAllProductAttributes(0, int.MaxValue).TotalCount.ToString("N0"),
                AttributeCombinationsCount = _productService.CountAllProductVariants().ToString("N0"),
                MediaCount = _mediaService.CountFiles(new MediaSearchQuery {
                    Deleted = false
                }).ToString("N0"),
                CustomersCount = _customerService.SearchCustomers(
                    new CustomerSearchQuery
                {
                    Deleted         = false,
                    CustomerRoleIds = new int[] { registeredRoleId }
                }
                    ).TotalCount.ToString("N0"),
                OrdersCount          = allOrders.Count().ToString("N0"),
                Sales                = (allOrders.Sum(x => (decimal?)x.OrderTotal) ?? 0).ToString("C0"),
                OnlineCustomersCount = _customerService.GetOnlineCustomers(DateTime.UtcNow.AddMinutes(-15), null, 0, int.MaxValue).TotalCount.ToString("N0"),
                CartsValue           = _shoppingCartService.GetAllOpenCartSubTotal().ToString("C0"),
                WishlistsValue       = _shoppingCartService.GetAllOpenWishlistSubTotal().ToString("C0")
            };

            return(new JsonResult
            {
                Data = new { model },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Пример #2
0
        private void ProcessAssociatedProducts(Product product, Product clone, bool isPublished, bool copyImages)
        {
            var searchQuery = new CatalogSearchQuery().HasParentGroupedProduct(product.Id);

            var query = _catalogSearchService.PrepareQuery(searchQuery);
            var associatedProducts = query.OrderBy(p => p.DisplayOrder).ToList();

            foreach (var associatedProduct in associatedProducts)
            {
                var associatedProductCopy = CopyProduct(associatedProduct, T("Admin.Common.CopyOf", associatedProduct.Name), isPublished, copyImages, false);
                associatedProductCopy.ParentGroupedProductId = clone.Id;
            }
        }
Пример #3
0
        protected virtual IEnumerable <XmlSitemapNode> GetProductNodes(string protocol)
        {
            var nodes = new List <XmlSitemapNode>();

            var searchQuery = new CatalogSearchQuery()
                              .VisibleOnly()
                              .VisibleIndividuallyOnly(true)
                              .HasStoreId(_services.StoreContext.CurrentStoreIdIfMultiStoreMode);

            var query = _catalogSearchService.PrepareQuery(searchQuery);

            query = query.OrderByDescending(x => x.CreatedOnUtc);

            for (var pageIndex = 0; pageIndex < 9999999; ++pageIndex)
            {
                var products = new PagedList <Product>(query, pageIndex, 1000);

                nodes.AddRange(products.Select(x =>
                {
                    var node = new XmlSitemapNode
                    {
                        Loc     = _urlHelper.RouteUrl("Product", new { SeName = x.GetSeName() }, protocol),
                        LastMod = x.UpdatedOnUtc,
                        //ChangeFreq = ChangeFrequency.Weekly,
                        //Priority = 0.8f
                    };

                    // TODO: add hreflang links if LangCount is > 1 and PrependSeoCode is true
                    return(node);
                }));

                _services.DbContext.DetachAll();

                if (!products.HasNextPage)
                {
                    break;
                }
            }

            return(nodes);
        }
Пример #4
0
        public async Task <JsonResult> StoreDashboardReportAsync()
        {
            var ordersQuery    = _db.Orders.AsNoTracking();
            var registeredRole = await _db.CustomerRoles
                                 .AsNoTracking()
                                 .FirstOrDefaultAsync(x => x.SystemName == SystemCustomerRoleNames.Registered);

            var registeredCustomersQuery = _db.Customers
                                           .AsNoTracking()
                                           .ApplyRolesFilter(new[] { registeredRole.Id });

            var sumAllOrders = await ordersQuery.SumAsync(x => (decimal?)x.OrderTotal) ?? 0;

            var sumOpenCarts = await _db.ShoppingCartItems.GetOpenCartTypeSubTotalAsync(ShoppingCartType.ShoppingCart);

            var sumWishlists = await _db.ShoppingCartItems.GetOpenCartTypeSubTotalAsync(ShoppingCartType.Wishlist);

            var model = new StoreDashboardReportModel
            {
                ProductsCount              = (await _catalogSearchService.PrepareQuery(new CatalogSearchQuery()).CountAsync()).ToString("N0"),
                CategoriesCount            = (await _db.Categories.CountAsync()).ToString("N0"),
                ManufacturersCount         = (await _db.Manufacturers.CountAsync()).ToString("N0"),
                AttributesCount            = (await _db.ProductAttributes.CountAsync()).ToString("N0"),
                AttributeCombinationsCount = (await _db.ProductVariantAttributeCombinations.CountAsync(x => x.IsActive)).ToString("N0"),
                MediaCount           = (await Services.MediaService.CountFilesAsync(new MediaSearchQuery {
                    Deleted = false
                })).ToString("N0"),
                CustomersCount       = (await registeredCustomersQuery.CountAsync()).ToString("N0"),
                OrdersCount          = (await ordersQuery.CountAsync()).ToString("N0"),
                Sales                = Services.CurrencyService.PrimaryCurrency.AsMoney(sumAllOrders).ToString(),
                OnlineCustomersCount = (await _db.Customers.ApplyOnlineCustomersFilter(15).CountAsync()).ToString("N0"),
                CartsValue           = Services.CurrencyService.PrimaryCurrency.AsMoney(sumOpenCarts).ToString(),
                WishlistsValue       = Services.CurrencyService.PrimaryCurrency.AsMoney(sumWishlists).ToString()
            };

            return(new JsonResult(new { model }));
        }
Пример #5
0
        public virtual void InheritAclIntoChildren(
            int categoryId,
            bool touchProductsWithMultipleCategories = false,
            bool touchExistingAcls = false,
            bool categoriesOnly    = false)
        {
            var category              = GetCategoryById(categoryId);
            var subcategories         = GetAllCategoriesByParentCategoryId(categoryId, true);
            var allCustomerRoles      = _customerService.GetAllCustomerRoles(true);
            var categoryCustomerRoles = _aclService.GetCustomerRoleIdsWithAccessTo(category);

            var categoryIds = new HashSet <int>(subcategories.Select(x => x.Id));

            categoryIds.Add(categoryId);

            var searchQuery = new CatalogSearchQuery()
                              .WithCategoryIds(null, categoryIds.ToArray());

            var query    = _catalogSearchService.PrepareQuery(searchQuery);
            var products = query.OrderBy(p => p.Id).ToList();

            using (var scope = new DbContextScope(ctx: _aclRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                _aclRepository.AutoCommitEnabled = false;

                foreach (var subcategory in subcategories)
                {
                    if (subcategory.SubjectToAcl != category.SubjectToAcl)
                    {
                        subcategory.SubjectToAcl = category.SubjectToAcl;
                        _categoryRepository.Update(subcategory);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(subcategory).ToDictionarySafe(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord {
                                    CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = subcategory.Id, EntityName = "Category"
                                });
                            }
                        }
                        else
                        {
                            if (existingAclRecords.TryGetValue(customerRole.Id, out var aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }

                _aclRepository.Context.SaveChanges();

                foreach (var product in products)
                {
                    if (product.SubjectToAcl != category.SubjectToAcl)
                    {
                        product.SubjectToAcl = category.SubjectToAcl;
                        _productRepository.Update(product);
                    }

                    var existingAclRecords = _aclService.GetAclRecords(product).ToDictionarySafe(x => x.CustomerRoleId);

                    foreach (var customerRole in allCustomerRoles)
                    {
                        if (categoryCustomerRoles.Contains(customerRole.Id))
                        {
                            if (!existingAclRecords.ContainsKey(customerRole.Id))
                            {
                                _aclRepository.Insert(new AclRecord {
                                    CustomerRole = customerRole, CustomerRoleId = customerRole.Id, EntityId = product.Id, EntityName = "Product"
                                });
                            }
                        }
                        else
                        {
                            if (existingAclRecords.TryGetValue(customerRole.Id, out var aclRecordToDelete))
                            {
                                _aclRepository.Delete(aclRecordToDelete);
                            }
                        }
                    }
                }

                _aclRepository.Context.SaveChanges();
            }
        }
Пример #6
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product entity</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            Product productCopy = null;
            var     utcNow      = DateTime.UtcNow;

            // product download & sample download
            int downloadId       = 0;
            int?sampleDownloadId = null;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                        UpdatedOnUtc   = utcNow
                    };

                    if ((download.MediaStorageId ?? 0) != 0 && download.MediaStorage != null)
                    {
                        _downloadService.InsertDownload(downloadCopy, download.MediaStorage.Data);
                    }
                    else
                    {
                        _downloadService.InsertDownload(downloadCopy, null);
                    }

                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew,
                            UpdatedOnUtc   = utcNow
                        };

                        if ((sampleDownload.MediaStorageId ?? 0) != 0 && sampleDownload.MediaStorage != null)
                        {
                            _downloadService.InsertDownload(sampleDownloadCopy, sampleDownload.MediaStorage.Data);
                        }
                        else
                        {
                            _downloadService.InsertDownload(sampleDownloadCopy, null);
                        }

                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                HomePageDisplayOrder = product.HomePageDisplayOrder,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                IsEsd                            = product.IsEsd,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                ManageInventoryMethod            = product.ManageInventoryMethod,
                StockQuantity                    = product.StockQuantity,
                DisplayStockAvailability         = product.DisplayStockAvailability,
                DisplayStockQuantity             = product.DisplayStockQuantity,
                MinStockQuantity                 = product.MinStockQuantity,
                LowStockActivityId               = product.LowStockActivityId,
                NotifyAdminForQuantityBelow      = product.NotifyAdminForQuantityBelow,
                BackorderMode                    = product.BackorderMode,
                AllowBackInStockSubscriptions    = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity             = product.OrderMinimumQuantity,
                OrderMaximumQuantity             = product.OrderMaximumQuantity,
                HideQuantityControl              = product.HideQuantityControl,
                AllowedQuantities                = product.AllowedQuantities,
                DisableBuyButton                 = product.DisableBuyButton,
                DisableWishlistButton            = product.DisableWishlistButton,
                AvailableForPreOrder             = product.AvailableForPreOrder,
                CallForPrice                     = product.CallForPrice,
                Price                            = product.Price,
                OldPrice                         = product.OldPrice,
                ProductCost                      = product.ProductCost,
                SpecialPrice                     = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc     = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc       = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice              = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice      = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice      = product.MaximumCustomerEnteredPrice,
                LowestAttributeCombinationPrice  = product.LowestAttributeCombinationPrice,
                Weight                           = product.Weight,
                Length                           = product.Length,
                Width                            = product.Width,
                Height                           = product.Height,
                AvailableStartDateTimeUtc        = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc          = product.AvailableEndDateTimeUtc,
                DisplayOrder                     = product.DisplayOrder,
                Published                        = isPublished,
                Deleted                          = product.Deleted,
                DeliveryTimeId                   = product.DeliveryTimeId,
                QuantityUnitId                   = product.QuantityUnitId,
                BasePriceEnabled                 = product.BasePriceEnabled,
                BasePriceMeasureUnit             = product.BasePriceMeasureUnit,
                BasePriceAmount                  = product.BasePriceAmount,
                BasePriceBaseAmount              = product.BasePriceBaseAmount,
                BundleTitleText                  = product.BundleTitleText,
                BundlePerItemShipping            = product.BundlePerItemShipping,
                BundlePerItemPricing             = product.BundlePerItemPricing,
                BundlePerItemShoppingCart        = product.BundlePerItemShoppingCart,
                CustomsTariffNumber              = product.CustomsTariffNumber,
                CountryOfOriginId                = product.CountryOfOriginId
            };

            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                var bundleTitleText = product.GetLocalized(x => x.BundleTitleText, lang.Id, false, false);
                if (!String.IsNullOrEmpty(bundleTitleText))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.BundleTitleText, bundleTitleText, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            // product pictures
            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        true,
                        false,
                        false);

                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                }
            }

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory
                {
                    ProductId         = productCopy.Id,
                    CategoryId        = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder      = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer
                {
                    ProductId         = productCopy.Id,
                    ManufacturerId    = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder      = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(new RelatedProduct
                {
                    ProductId1   = productCopy.Id,
                    ProductId2   = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(new CrossSellProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute
                {
                    ProductId = productCopy.Id,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder      = productSpecificationAttribute.DisplayOrder
                };

                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }

            // product <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id))
            {
                var productVariantAttributeCopy = new ProductVariantAttribute
                {
                    ProductId              = productCopy.Id,
                    ProductAttributeId     = productVariantAttribute.ProductAttributeId,
                    TextPrompt             = productVariantAttribute.TextPrompt,
                    IsRequired             = productVariantAttribute.IsRequired,
                    AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                    DisplayOrder           = productVariantAttribute.DisplayOrder
                };

                _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                // product variant attribute values
                var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);

                foreach (var productVariantAttributeValue in productVariantAttributeValues)
                {
                    var pvavCopy = new ProductVariantAttributeValue
                    {
                        ProductVariantAttributeId = productVariantAttributeCopy.Id,
                        Name             = productVariantAttributeValue.Name,
                        Color            = productVariantAttributeValue.Color,
                        PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                        WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                        IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                        DisplayOrder     = productVariantAttributeValue.DisplayOrder,
                        ValueTypeId      = productVariantAttributeValue.ValueTypeId,
                        LinkedProductId  = productVariantAttributeValue.LinkedProductId,
                        Quantity         = productVariantAttributeValue.Quantity,
                    };

                    _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }

            // attribute combinations
            using (var scope = new DbContextScope(lazyLoading: false, forceNoTracking: false))
            {
                scope.LoadCollection(product, (Product p) => p.ProductVariantAttributeCombinations);
            }

            foreach (var combination in product.ProductVariantAttributeCombinations)
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml = "";
                var    parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                foreach (var oldPva in parsedProductVariantAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldPva.Id))
                    {
                        int newPvaId = associatedAttributes[oldPva.Id];
                        var newPva   = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                        if (newPva != null)
                        {
                            var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                            foreach (var oldPvaValueStr in oldPvaValuesStr)
                            {
                                if (newPva.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldPvaValue = int.Parse(oldPvaValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                    {
                                        int newPvavId = associatedAttributeValues[oldPvaValue];
                                        var newPvav   = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                        if (newPvav != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductVariantAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,

                    // SmartStore extension
                    Sku  = combination.Sku,
                    Gtin = combination.Gtin,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Price = combination.Price,
                    AssignedPictureIds = copyImages ? combination.AssignedPictureIds : null,
                    Length             = combination.Length,
                    Width               = combination.Width,
                    Height              = combination.Height,
                    BasePriceAmount     = combination.BasePriceAmount,
                    BasePriceBaseAmount = combination.BasePriceBaseAmount,
                    DeliveryTimeId      = combination.DeliveryTimeId,
                    QuantityUnitId      = combination.QuantityUnitId,
                    IsActive            = combination.IsActive
                                          //IsDefaultCombination = combination.IsDefaultCombination
                };
                _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
            }

            // tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(new TierPrice
                {
                    ProductId      = productCopy.Id,
                    StoreId        = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity       = tierPrice.Quantity,
                    Price          = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }

            // update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateLowestAttributeCombinationPriceProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);

            // associated products
            if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct)
            {
                var copyOf      = _localizationService.GetResource("Admin.Common.CopyOf");
                var searchQuery = new CatalogSearchQuery()
                                  .HasParentGroupedProduct(product.Id);

                var query = _catalogSearchService.PrepareQuery(searchQuery);
                var associatedProducts = query.OrderBy(p => p.DisplayOrder).ToList();

                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, $"{copyOf} {associatedProduct.Name}", isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;

                    _productService.UpdateProduct(productCopy);
                }
            }

            // bundled products
            var bundledItems = _productService.GetBundleItems(product.Id, true);

            foreach (var bundleItem in bundledItems)
            {
                var newBundleItem = bundleItem.Item.Clone();
                newBundleItem.BundleProductId = productCopy.Id;

                _productService.InsertBundleItem(newBundleItem);

                foreach (var itemFilter in bundleItem.Item.AttributeFilters)
                {
                    var newItemFilter = itemFilter.Clone();
                    newItemFilter.BundleItemId = newBundleItem.Id;

                    _productAttributeService.InsertProductBundleItemAttributeFilter(newItemFilter);
                }
            }

            return(productCopy);
        }
Пример #7
0
        public ActionResult Picker(EntityPickerModel model, FormCollection form)
        {
            try
            {
                var languageId = model.LanguageId == 0 ? Services.WorkContext.WorkingLanguage.Id : model.LanguageId;
                var disableIf  = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList();
                var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList();
                var selected   = model.Selected.SplitSafe(",");
                var returnSku  = model.ReturnField.IsCaseInsensitiveEqual("sku");

                using (var scope = new DbContextScope(Services.DbContext, autoDetectChanges: false, proxyCreation: true, validateOnSave: false, forceNoTracking: true))
                {
                    if (model.EntityType.IsCaseInsensitiveEqual("product"))
                    {
                        model.SearchTerm = model.SearchTerm.TrimSafe();

                        var hasPermission             = Services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog);
                        var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct");
                        var disableIfGroupedProduct   = disableIf.Contains("groupedproduct");
                        var labelTextGrouped          = T("Admin.Catalog.Products.ProductType.GroupedProduct.Label").Text;
                        var labelTextBundled          = T("Admin.Catalog.Products.ProductType.BundledProduct.Label").Text;
                        var sku = T("Products.Sku").Text;

                        var fields = new List <string> {
                            "name"
                        };
                        if (_searchSettings.SearchFields.Contains("sku"))
                        {
                            fields.Add("sku");
                        }
                        if (_searchSettings.SearchFields.Contains("shortdescription"))
                        {
                            fields.Add("shortdescription");
                        }

                        var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm)
                                          .HasStoreId(model.StoreId);

                        if (!hasPermission)
                        {
                            searchQuery = searchQuery.VisibleOnly(Services.WorkContext.CurrentCustomer);
                        }

                        if (model.ProductTypeId > 0)
                        {
                            searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId);
                        }

                        if (model.ManufacturerId != 0)
                        {
                            searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId);
                        }

                        if (model.CategoryId != 0)
                        {
                            var node = _categoryService.GetCategoryTree(model.CategoryId, true);
                            if (node != null)
                            {
                                searchQuery = searchQuery.WithCategoryIds(null, node.Flatten(true).Select(x => x.Id).ToArray());
                            }
                        }

                        var skip  = model.PageIndex * model.PageSize;
                        var query = _catalogSearchService.PrepareQuery(searchQuery);

                        var products = query
                                       .Select(x => new
                        {
                            x.Id,
                            x.Sku,
                            x.Name,
                            x.Published,
                            x.ProductTypeId,
                            x.MainPictureId
                        })
                                       .OrderBy(x => x.Name)
                                       .Skip(() => skip)
                                       .Take(() => model.PageSize)
                                       .ToList();

                        var allPictureIds   = products.Select(x => x.MainPictureId.GetValueOrDefault());
                        var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds);

                        model.SearchResult = products
                                             .Select(x =>
                        {
                            var item = new EntityPickerModel.SearchResultModel
                            {
                                Id           = x.Id,
                                Title        = x.Name,
                                Summary      = x.Sku,
                                SummaryTitle = "{0}: {1}".FormatInvariant(sku, x.Sku.NaIfEmpty()),
                                Published    = hasPermission ? x.Published : (bool?)null,
                                ReturnValue  = returnSku ? x.Sku : x.Id.ToString()
                            };

                            item.Selected = selected.Contains(item.ReturnValue);

                            if (disableIfNotSimpleProduct)
                            {
                                item.Disable = x.ProductTypeId != (int)ProductType.SimpleProduct;
                            }
                            else if (disableIfGroupedProduct)
                            {
                                item.Disable = x.ProductTypeId == (int)ProductType.GroupedProduct;
                            }

                            if (!item.Disable && disableIds.Contains(x.Id))
                            {
                                item.Disable = true;
                            }

                            if (x.ProductTypeId == (int)ProductType.GroupedProduct)
                            {
                                item.LabelText      = labelTextGrouped;
                                item.LabelClassName = "badge-success";
                            }
                            else if (x.ProductTypeId == (int)ProductType.BundledProduct)
                            {
                                item.LabelText      = labelTextBundled;
                                item.LabelClassName = "badge-info";
                            }

                            var pictureInfo  = allPictureInfos.Get(x.MainPictureId.GetValueOrDefault());
                            var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

                            item.ImageUrl = _pictureService.GetUrl(
                                allPictureInfos.Get(x.MainPictureId.GetValueOrDefault()),
                                _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage,
                                fallbackType);

                            return(item);
                        })
                                             .ToList();
                    }
                    else if (model.EntityType.IsCaseInsensitiveEqual("category"))
                    {
                        var categories      = _categoryService.GetAllCategories(model.SearchTerm, showHidden: true);
                        var allPictureIds   = categories.Select(x => x.PictureId.GetValueOrDefault());
                        var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds);

                        model.SearchResult = categories
                                             .Select(x =>
                        {
                            var path = ((ICategoryNode)x).GetCategoryPath(_categoryService, languageId, "({0})");
                            var item = new EntityPickerModel.SearchResultModel
                            {
                                Id           = x.Id,
                                Title        = x.Name,
                                Summary      = path,
                                SummaryTitle = path,
                                Published    = x.Published,
                                ReturnValue  = x.Id.ToString(),
                                Selected     = selected.Contains(x.Id.ToString()),
                                Disable      = disableIds.Contains(x.Id)
                            };

                            if (x.Alias.HasValue())
                            {
                                item.LabelText      = x.Alias;
                                item.LabelClassName = "badge-secondary";
                            }

                            var pictureInfo  = allPictureInfos.Get(x.PictureId.GetValueOrDefault());
                            var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

                            item.ImageUrl = _pictureService.GetUrl(
                                allPictureInfos.Get(x.PictureId.GetValueOrDefault()),
                                _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage,
                                fallbackType);

                            return(item);
                        })
                                             .ToList();
                    }
                    else if (model.EntityType.IsCaseInsensitiveEqual("manufacturer"))
                    {
                        var manufacturers   = _manufacturerService.GetAllManufacturers(model.SearchTerm, model.PageIndex, model.PageSize, showHidden: true);
                        var allPictureIds   = manufacturers.Select(x => x.PictureId.GetValueOrDefault());
                        var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds);

                        model.SearchResult = manufacturers
                                             .Select(x =>
                        {
                            var item = new EntityPickerModel.SearchResultModel
                            {
                                Id          = x.Id,
                                Title       = x.Name,
                                Published   = x.Published,
                                ReturnValue = x.Id.ToString(),
                                Selected    = selected.Contains(x.Id.ToString()),
                                Disable     = disableIds.Contains(x.Id)
                            };

                            var pictureInfo  = allPictureInfos.Get(x.PictureId.GetValueOrDefault());
                            var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

                            item.ImageUrl = _pictureService.GetUrl(
                                allPictureInfos.Get(x.PictureId.GetValueOrDefault()),
                                _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage,
                                fallbackType);

                            return(item);
                        })
                                             .ToList();
                    }
                    else if (model.EntityType.IsCaseInsensitiveEqual("customer"))
                    {
                        var registeredRoleId         = _customerService.GetCustomerRoleBySystemName("Registered").Id;
                        var searchTermName           = string.Empty;
                        var searchTermEmail          = string.Empty;
                        var searchTermCustomerNumber = string.Empty;

                        if (model.CustomerSearchType.IsCaseInsensitiveEqual("Name"))
                        {
                            searchTermName = model.SearchTerm;
                        }
                        else if (model.CustomerSearchType.IsCaseInsensitiveEqual("Email"))
                        {
                            searchTermEmail = model.SearchTerm;
                        }
                        else if (model.CustomerSearchType.IsCaseInsensitiveEqual("CustomerNumber"))
                        {
                            searchTermCustomerNumber = model.SearchTerm;
                        }

                        var q = new CustomerSearchQuery
                        {
                            SearchTerm      = searchTermName,
                            Email           = searchTermEmail,
                            CustomerNumber  = searchTermCustomerNumber,
                            CustomerRoleIds = new int[] { registeredRoleId },
                            PageIndex       = model.PageIndex,
                            PageSize        = model.PageSize
                        };

                        var customers = _customerService.SearchCustomers(q);

                        model.SearchResult = customers
                                             .Select(x =>
                        {
                            var fullName = x.GetFullName();

                            var item = new EntityPickerModel.SearchResultModel
                            {
                                Id           = x.Id,
                                ReturnValue  = x.Id.ToString(),
                                Title        = x.Username.NullEmpty() ?? x.Email,
                                Summary      = fullName,
                                SummaryTitle = fullName,
                                Published    = true,
                                Selected     = selected.Contains(x.Id.ToString()),
                                Disable      = disableIds.Contains(x.Id)
                            };

                            return(item);
                        })
                                             .ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                NotifyError(ex.ToAllMessages());
            }

            return(PartialView("Picker.List", model));
        }
        private async Task <List <RuleValueSelectListOption> > SearchProducts(RuleOptionsResult result, string term, int skip, int take)
        {
            List <RuleValueSelectListOption> products;
            var fields = new List <string> {
                "name"
            };

            if (_searchSettings.SearchFields.Contains("sku"))
            {
                fields.Add("sku");
            }
            if (_searchSettings.SearchFields.Contains("shortdescription"))
            {
                fields.Add("shortdescription");
            }

            var searchQuery = new CatalogSearchQuery(fields.ToArray(), term);

            if (_searchSettings.UseCatalogSearchInBackend)
            {
                searchQuery = searchQuery
                              .Slice(skip, take)
                              .SortBy(ProductSortingEnum.NameAsc);

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                var hits = await searchResult.GetHitsAsync();

                result.HasMoreData = hits.HasNextPage;

                products = hits
                           .AsQueryable()
                           .Select(x => new RuleValueSelectListOption
                {
                    Value = x.Id.ToString(),
                    Text  = x.Name,
                    Hint  = x.Sku
                })
                           .ToList();
            }
            else
            {
                var query = _catalogSearchService.PrepareQuery(searchQuery);

                var pageIndex = take == 0 ? 0 : Math.Max(skip / take, 0);
                result.HasMoreData = (pageIndex + 1) * take < query.Count();

                products = await query
                           .Select(x => new RuleValueSelectListOption
                {
                    Value = x.Id.ToString(),
                    Text  = x.Name,
                    Hint  = x.Sku
                })
                           .OrderBy(x => x.Text)
                           .Skip(skip)
                           .Take(take)
                           .ToListAsync();
            }

            return(products);
        }
Пример #9
0
        public async Task <IActionResult> ProductList(GridCommand command, ProductListModel model)
        {
            var gridModel = new GridModel <ProductOverviewModel>();

            var fields = new List <string> {
                "name"
            };

            if (_searchSettings.SearchFields.Contains("sku"))
            {
                fields.Add("sku");
            }

            if (_searchSettings.SearchFields.Contains("shortdescription"))
            {
                fields.Add("shortdescription");
            }

            var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchProductName)
                              .HasStoreId(model.SearchStoreId)
                              .WithCurrency(_workContext.WorkingCurrency)
                              .WithLanguage(_workContext.WorkingLanguage);

            if (model.SearchIsPublished.HasValue)
            {
                searchQuery = searchQuery.PublishedOnly(model.SearchIsPublished.Value);
            }

            if (model.SearchHomePageProducts.HasValue)
            {
                searchQuery = searchQuery.HomePageProductsOnly(model.SearchHomePageProducts.Value);
            }

            if (model.SearchProductTypeId > 0)
            {
                searchQuery = searchQuery.IsProductType((ProductType)model.SearchProductTypeId);
            }

            if (model.SearchWithoutManufacturers.HasValue)
            {
                searchQuery = searchQuery.HasAnyManufacturer(!model.SearchWithoutManufacturers.Value);
            }
            else if (model.SearchManufacturerId != 0)
            {
                searchQuery = searchQuery.WithManufacturerIds(null, model.SearchManufacturerId);
            }


            if (model.SearchWithoutCategories.HasValue)
            {
                searchQuery = searchQuery.HasAnyCategory(!model.SearchWithoutCategories.Value);
            }
            else if (model.SearchCategoryId != 0)
            {
                searchQuery = searchQuery.WithCategoryIds(null, model.SearchCategoryId);
            }

            IPagedList <Product> products;

            if (_searchSettings.UseCatalogSearchInBackend)
            {
                searchQuery = searchQuery.Slice((command.Page - 1) * command.PageSize, command.PageSize);

                var sort = command.Sorting?.FirstOrDefault();
                if (sort != null)
                {
                    switch (sort.Member)
                    {
                    case nameof(ProductModel.Name):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.NameDesc : ProductSortingEnum.NameAsc);
                        break;

                    case nameof(ProductModel.Price):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.PriceDesc : ProductSortingEnum.PriceAsc);
                        break;

                    case nameof(ProductModel.CreatedOn):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.CreatedOn : ProductSortingEnum.CreatedOnAsc);
                        break;
                    }
                }

                if (!searchQuery.Sorting.Any())
                {
                    searchQuery = searchQuery.SortBy(ProductSortingEnum.NameAsc);
                }

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                products = await searchResult.GetHitsAsync();
            }
            else
            {
                var query = _catalogSearchService
                            .PrepareQuery(searchQuery)
                            .ApplyGridCommand(command, false);

                products = await new PagedList <Product>(query, command.Page - 1, command.PageSize).LoadAsync();
            }

            var fileIds = products.AsEnumerable()
                          .Select(x => x.MainPictureId ?? 0)
                          .Where(x => x != 0)
                          .Distinct()
                          .ToArray();

            var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

            gridModel.Rows = products.AsEnumerable().Select(x =>
            {
                var productModel = new ProductOverviewModel
                {
                    Sku                  = x.Sku,
                    Published            = x.Published,
                    ProductTypeLabelHint = x.ProductTypeLabelHint,
                    Name                 = x.Name,
                    Id                        = x.Id,
                    StockQuantity             = x.StockQuantity,
                    Price                     = x.Price,
                    LimitedToStores           = x.LimitedToStores,
                    EditUrl                   = Url.Action("Edit", "Product", new { id = x.Id }),
                    ManufacturerPartNumber    = x.ManufacturerPartNumber,
                    Gtin                      = x.Gtin,
                    MinStockQuantity          = x.MinStockQuantity,
                    OldPrice                  = x.OldPrice,
                    AvailableStartDateTimeUtc = x.AvailableStartDateTimeUtc,
                    AvailableEndDateTimeUtc   = x.AvailableEndDateTimeUtc
                };

                //MiniMapper.Map(x, productModel);

                files.TryGetValue(x.MainPictureId ?? 0, out var file);

                // TODO: (core) Use IImageModel
                productModel.PictureThumbnailUrl = _mediaService.GetUrl(file, _mediaSettings.CartThumbPictureSize);
                productModel.NoThumb             = file == null;

                productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService);
                productModel.UpdatedOn       = _dateTimeHelper.ConvertToUserTime(x.UpdatedOnUtc, DateTimeKind.Utc);
                productModel.CreatedOn       = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);

                return(productModel);
            });

            gridModel.Total = products.TotalCount;

            return(Json(gridModel));
        }
Пример #10
0
        public ActionResult Picker(EntityPickerModel model, FormCollection form)
        {
            model.PageSize = 96; // _commonSettings.EntityPickerPageSize;

            try
            {
                var disableIf  = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList();
                var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList();

                var selIds = new HashSet <int>(model.PreselectedEntityIds.ToIntArray());

                using (var scope = new DbContextScope(_services.DbContext, autoDetectChanges: false, proxyCreation: true, validateOnSave: false, forceNoTracking: true))
                {
                    if (model.EntityType.IsCaseInsensitiveEqual("product"))
                    {
                        #region Product

                        model.SearchTerm = model.ProductName.TrimSafe();

                        var hasPermission             = _services.Permissions.Authorize(StandardPermissionProvider.ManageCatalog);
                        var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct");
                        var disableIfGroupedProduct   = disableIf.Contains("groupedproduct");
                        var labelTextGrouped          = T("Admin.Catalog.Products.ProductType.GroupedProduct.Label").Text;
                        var labelTextBundled          = T("Admin.Catalog.Products.ProductType.BundledProduct.Label").Text;
                        var sku = T("Products.Sku").Text;

                        var fields = new List <string> {
                            "name"
                        };
                        if (_searchSettings.SearchFields.Contains("sku"))
                        {
                            fields.Add("sku");
                        }
                        if (_searchSettings.SearchFields.Contains("shortdescription"))
                        {
                            fields.Add("shortdescription");
                        }

                        var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm)
                                          .HasStoreId(model.StoreId);

                        if (!hasPermission)
                        {
                            searchQuery = searchQuery.VisibleOnly(_services.WorkContext.CurrentCustomer);
                        }

                        if (model.ProductTypeId > 0)
                        {
                            searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId);
                        }

                        if (model.ManufacturerId != 0)
                        {
                            searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId);
                        }

                        if (model.CategoryId != 0)
                        {
                            var node = _categoryService.GetCategoryTree(model.CategoryId, true);
                            if (node != null)
                            {
                                searchQuery = searchQuery.WithCategoryIds(null, node.Flatten(true).Select(x => x.Id).ToArray());
                            }
                        }

                        var query = _catalogSearchService.PrepareQuery(searchQuery);

                        var products = query
                                       .Select(x => new
                        {
                            x.Id,
                            x.Sku,
                            x.Name,
                            x.Published,
                            x.ProductTypeId,
                            x.MainPictureId
                        })
                                       .OrderBy(x => x.Name)
                                       .Skip(model.PageIndex * model.PageSize)
                                       .Take(model.PageSize)
                                       .ToList();

                        var allPictureIds   = products.Select(x => x.MainPictureId.GetValueOrDefault());
                        var allPictureInfos = _pictureService.GetPictureInfos(allPictureIds);

                        model.SearchResult = products
                                             .Select(x =>
                        {
                            var item = new EntityPickerModel.SearchResultModel
                            {
                                Id           = x.Id,
                                ReturnValue  = (model.ReturnField.IsCaseInsensitiveEqual("sku") ? x.Sku : x.Id.ToString()),
                                Title        = x.Name,
                                Summary      = x.Sku,
                                SummaryTitle = "{0}: {1}".FormatInvariant(sku, x.Sku.NaIfEmpty()),
                                Published    = (hasPermission ? x.Published : (bool?)null),
                                Selected     = selIds.Contains(x.Id)
                            };

                            if (disableIfNotSimpleProduct)
                            {
                                item.Disable = (x.ProductTypeId != (int)ProductType.SimpleProduct);
                            }
                            else if (disableIfGroupedProduct)
                            {
                                item.Disable = (x.ProductTypeId == (int)ProductType.GroupedProduct);
                            }

                            if (!item.Disable && disableIds.Contains(x.Id))
                            {
                                item.Disable = true;
                            }

                            if (x.ProductTypeId == (int)ProductType.GroupedProduct)
                            {
                                item.LabelText      = labelTextGrouped;
                                item.LabelClassName = "badge-success";
                            }
                            else if (x.ProductTypeId == (int)ProductType.BundledProduct)
                            {
                                item.LabelText      = labelTextBundled;
                                item.LabelClassName = "badge-info";
                            }

                            var pictureInfo  = allPictureInfos.Get(x.MainPictureId.GetValueOrDefault());
                            var fallbackType = _catalogSettings.HideProductDefaultPictures ? FallbackPictureType.NoFallback : FallbackPictureType.Entity;

                            item.ImageUrl = _pictureService.GetUrl(
                                allPictureInfos.Get(x.MainPictureId.GetValueOrDefault()),
                                _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage,
                                fallbackType);

                            return(item);
                        })
                                             .ToList();

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                NotifyError(ex.ToAllMessages());
            }

            return(PartialView("Picker.List", model));
        }
Пример #11
0
        public async Task <IActionResult> PickerPost(EntityPickerModel model)
        {
            try
            {
                var form       = Request.Form;
                var disableIf  = model.DisableIf.SplitSafe(",").Select(x => x.ToLower().Trim()).ToList();
                var disableIds = model.DisableIds.SplitSafe(",").Select(x => x.ToInt()).ToList();
                var selected   = model.Selected.SplitSafe(",");
                var returnSku  = model.ReturnField.EqualsNoCase("sku");

                using var scope = new DbContextScope(Services.DbContext, autoDetectChanges: false, forceNoTracking: true);
                if (model.EntityType.EqualsNoCase("product"))
                {
                    model.SearchTerm = model.SearchTerm.TrimSafe();

                    var hasPermission = await Services.Permissions.AuthorizeAsync(Permissions.Catalog.Product.Read);

                    var disableIfNotSimpleProduct = disableIf.Contains("notsimpleproduct");
                    var disableIfGroupedProduct   = disableIf.Contains("groupedproduct");
                    var labelTextGrouped          = T("Admin.Catalog.Products.ProductType.GroupedProduct.Label").Value;
                    var labelTextBundled          = T("Admin.Catalog.Products.ProductType.BundledProduct.Label").Value;
                    var sku = T("Products.Sku");

                    var fields = new List <string> {
                        "name"
                    };
                    if (_searchSettings.SearchFields.Contains("sku"))
                    {
                        fields.Add("sku");
                    }
                    if (_searchSettings.SearchFields.Contains("shortdescription"))
                    {
                        fields.Add("shortdescription");
                    }

                    var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchTerm)
                                      .HasStoreId(model.StoreId);

                    if (!hasPermission)
                    {
                        searchQuery = searchQuery.VisibleOnly(Services.WorkContext.CurrentCustomer);
                    }

                    if (model.ProductTypeId > 0)
                    {
                        searchQuery = searchQuery.IsProductType((ProductType)model.ProductTypeId);
                    }

                    if (model.ManufacturerId != 0)
                    {
                        searchQuery = searchQuery.WithManufacturerIds(null, model.ManufacturerId);
                    }

                    if (model.CategoryId != 0)
                    {
                        var node = await _categoryService.GetCategoryTreeAsync(model.CategoryId, true);

                        if (node != null)
                        {
                            searchQuery = searchQuery.WithCategoryIds(null, node.Flatten(true).Select(x => x.Id).ToArray());
                        }
                    }

                    List <EntityPickerProduct> products;
                    var skip = model.PageIndex * model.PageSize;

                    if (_searchSettings.UseCatalogSearchInBackend)
                    {
                        searchQuery = searchQuery
                                      .Slice(skip, model.PageSize)
                                      .SortBy(ProductSortingEnum.NameAsc);

                        var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                        products = (await searchResult.GetHitsAsync())
                                   .Select(x => new EntityPickerProduct
                        {
                            Id            = x.Id,
                            Sku           = x.Sku,
                            Name          = x.Name,
                            Published     = x.Published,
                            ProductTypeId = x.ProductTypeId,
                            MainPictureId = x.MainPictureId
                        })
                                   .ToList();
                    }
                    else
                    {
                        var query = _catalogSearchService.PrepareQuery(searchQuery).AsNoTracking();

                        products = await query
                                   .Select(x => new EntityPickerProduct
                        {
                            Id            = x.Id,
                            Sku           = x.Sku,
                            Name          = x.Name,
                            Published     = x.Published,
                            ProductTypeId = x.ProductTypeId,
                            MainPictureId = x.MainPictureId
                        })
                                   .OrderBy(x => x.Name)
                                   .Skip(skip)
                                   .Take(model.PageSize)
                                   .ToListAsync();
                    }

                    var fileIds = products
                                  .Select(x => x.MainPictureId ?? 0)
                                  .Where(x => x != 0)
                                  .Distinct()
                                  .ToArray();

                    var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

                    model.SearchResult = products
                                         .Select(x =>
                    {
                        var item = new EntityPickerModel.SearchResultModel
                        {
                            Id           = x.Id,
                            Title        = x.Name,
                            Summary      = x.Sku,
                            SummaryTitle = $"{sku}: {x.Sku.NaIfEmpty()}",
                            Published    = hasPermission ? x.Published : null,
                            ReturnValue  = returnSku ? x.Sku : x.Id.ToString()
                        };

                        item.Selected = selected.Contains(item.ReturnValue);

                        if (disableIfNotSimpleProduct)
                        {
                            item.Disable = x.ProductTypeId != (int)ProductType.SimpleProduct;
                        }
                        else if (disableIfGroupedProduct)
                        {
                            item.Disable = x.ProductTypeId == (int)ProductType.GroupedProduct;
                        }

                        if (!item.Disable && disableIds.Contains(x.Id))
                        {
                            item.Disable = true;
                        }

                        if (x.ProductTypeId == (int)ProductType.GroupedProduct)
                        {
                            item.LabelText      = labelTextGrouped;
                            item.LabelClassName = "badge-success";
                        }
                        else if (x.ProductTypeId == (int)ProductType.BundledProduct)
                        {
                            item.LabelText      = labelTextBundled;
                            item.LabelClassName = "badge-info";
                        }

                        files.TryGetValue(x.MainPictureId ?? 0, out var file);
                        item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures);

                        return(item);
                    })
                                         .ToList();
                }
                else if (model.EntityType.EqualsNoCase("category"))
                {
                    var categoryQuery = _db.Categories
                                        .AsNoTracking()
                                        .ApplyStandardFilter(includeHidden: true)
                                        .AsQueryable();

                    if (model.SearchTerm.HasValue())
                    {
                        categoryQuery = categoryQuery.Where(c => c.Name.Contains(model.SearchTerm) || c.FullName.Contains(model.SearchTerm));
                    }

                    var categories = await categoryQuery.ToListAsync();

                    var fileIds = categories
                                  .Select(x => x.MediaFileId ?? 0)
                                  .Where(x => x != 0)
                                  .Distinct()
                                  .ToArray();

                    var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

                    model.SearchResult = await categories
                                         .SelectAsync(async x =>
                    {
                        var path = await _categoryService.GetCategoryPathAsync(x, Services.WorkContext.WorkingLanguage.Id, "({0})");
                        var item = new EntityPickerModel.SearchResultModel
                        {
                            Id           = x.Id,
                            Title        = x.Name,
                            Summary      = path,
                            SummaryTitle = path,
                            Published    = x.Published,
                            ReturnValue  = x.Id.ToString(),
                            Selected     = selected.Contains(x.Id.ToString()),
                            Disable      = disableIds.Contains(x.Id)
                        };

                        if (x.Alias.HasValue())
                        {
                            item.LabelText      = x.Alias;
                            item.LabelClassName = "badge-secondary";
                        }

                        files.TryGetValue(x.MediaFileId ?? 0, out var file);
                        item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures);

                        return(item);
                    }).AsyncToList();
                }
                else if (model.EntityType.EqualsNoCase("manufacturer"))
                {
                    var manufacturerQuery = _db.Manufacturers
                                            .AsNoTracking()
                                            .ApplyStandardFilter(includeHidden: true)
                                            .AsQueryable();

                    if (model.SearchTerm.HasValue())
                    {
                        manufacturerQuery = manufacturerQuery.Where(c => c.Name.Contains(model.SearchTerm));
                    }

                    var manufacturers = await manufacturerQuery
                                        .ApplyPaging(model.PageIndex, model.PageSize)
                                        .ToListAsync();

                    var fileIds = manufacturers
                                  .Select(x => x.MediaFileId ?? 0)
                                  .Where(x => x != 0)
                                  .Distinct()
                                  .ToArray();

                    var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

                    model.SearchResult = manufacturers
                                         .Select(x =>
                    {
                        var item = new EntityPickerModel.SearchResultModel
                        {
                            Id          = x.Id,
                            Title       = x.Name,
                            Published   = x.Published,
                            ReturnValue = x.Id.ToString(),
                            Selected    = selected.Contains(x.Id.ToString()),
                            Disable     = disableIds.Contains(x.Id)
                        };

                        files.TryGetValue(x.MediaFileId ?? 0, out var file);
                        item.ImageUrl = _mediaService.GetUrl(file, _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage, null, !_catalogSettings.HideProductDefaultPictures);

                        return(item);
                    })
                                         .ToList();
                }
                else if (model.EntityType.EqualsNoCase("customer"))
                {
                    var registeredRole = await _db.CustomerRoles
                                         .AsNoTracking()
                                         .FirstOrDefaultAsync(x => x.SystemName == SystemCustomerRoleNames.Registered);

                    var registeredRoleId = registeredRole.Id;

                    var customerQuery = _db.Customers
                                        .AsNoTracking()
                                        .AsQueryable();

                    if (model.SearchTerm.HasValue())
                    {
                        if (model.CustomerSearchType.EqualsNoCase("Name"))
                        {
                            customerQuery = customerQuery.ApplySearchTermFilter(model.SearchTerm);
                        }
                        else if (model.CustomerSearchType.EqualsNoCase("Email"))
                        {
                            customerQuery = customerQuery.ApplyIdentFilter(email: model.SearchTerm, userName: model.SearchTerm);
                        }
                        else if (model.CustomerSearchType.EqualsNoCase("CustomerNumber"))
                        {
                            customerQuery = customerQuery.ApplyIdentFilter(customerNumber: model.SearchTerm);
                        }
                    }

                    var customers = await customerQuery
                                    .ApplyRolesFilter(new[] { registeredRoleId })
                                    .ApplyPaging(model.PageIndex, model.PageSize)
                                    .ToListAsync();

                    model.SearchResult = customers
                                         .Select(x =>
                    {
                        var fullName = x.GetFullName();

                        var item = new EntityPickerModel.SearchResultModel
                        {
                            Id           = x.Id,
                            ReturnValue  = x.Id.ToString(),
                            Title        = x.Username.NullEmpty() ?? x.Email,
                            Summary      = fullName,
                            SummaryTitle = fullName,
                            Published    = true,
                            Selected     = selected.Contains(x.Id.ToString()),
                            Disable      = disableIds.Contains(x.Id)
                        };

                        return(item);
                    })
                                         .ToList();
                }
            }
            catch (Exception ex)
            {
                NotifyError(ex.ToAllMessages());
            }

            return(PartialView("Picker.List", model));
        }