public ManufacturerModel() { PictureModel = new PictureModel(); FeaturedProducts = new List<ProductModel>(); Products = new List<ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); }
public ProductsByTagModel() { Products = new List <ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); AvailableSortOptions = new List <SelectListItem>(); AvailableViewModes = new List <SelectListItem>(); }
private ICollection<Branch> _branches; //add by hz #endregion Fields #region Constructors public VendorModel() { PictureModel = new PictureModel(); FeaturedProducts = new List<ProductOverviewModel>(); Products = new List<ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); Branches = new List<BranchModel>(); }
public ProductsByTagModel() { Products = new List<ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); AvailableSortOptions = new List<SelectListItem>(); AvailableViewModes = new List<SelectListItem>(); PageSizeOptions = new List<SelectListItem>(); }
public CategoryModel() { PictureModel = new PictureModel(); FeaturedProducts = new List <ProductOverviewModel>(); Products = new List <ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); SubCategories = new List <SubCategoryModel>(); CategoryBreadcrumb = new List <CategoryModel>(); }
public CategoryModel() { PictureModel = new PictureModel(); FeaturedProducts = new List<ProductOverviewModel>(); Products = new List<ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); SubCategories = new List<SubCategoryModel>(); CategoryBreadcrumb = new List<CategoryModel>(); }
public SearchModel() { PagingFilteringContext = new CatalogPagingFilteringModel(); Products = new List <ProductOverviewModel>(); AvailableCategories = new List <SelectListItem>(); AvailableManufacturers = new List <SelectListItem>(); AvailableVendors = new List <SelectListItem>(); }
public ManufacturerModel() { PictureModel = new PictureModel(); FeaturedProducts = new List <ProductModel>(); Products = new List <ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); AvailableSortOptions = new List <SelectListItem>(); AvailableViewModes = new List <SelectListItem>(); PageSizeOptions = new List <SelectListItem>(); }
public ManufacturerModel() { PictureModel = new PictureModel(); FeaturedProducts = new List<ProductModel>(); Products = new List<ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); AvailableSortOptions = new List<SelectListItem>(); AvailableViewModes = new List<SelectListItem>(); PageSizeOptions = new List<SelectListItem>(); }
public CategoryModel() { PictureModel = new PictureModel(); FeaturedProducts = new List <ProductModel>(); Products = new List <ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); SubCategories = new List <SubCategoryModel>(); CategoryBreadcrumb = new List <CategoryModel>(); AvailableSortOptions = new List <SelectListItem>(); AvailableViewModes = new List <SelectListItem>(); PageSizeOptions = new List <SelectListItem>(); }
public CategoryModel() { PictureModel = new PictureModel(); FeaturedProducts = new List<ProductModel>(); Products = new List<ProductModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); SubCategories = new List<SubCategoryModel>(); CategoryBreadcrumb = new List<CategoryModel>(); AvailableSortOptions = new List<SelectListItem>(); AvailableViewModes = new List<SelectListItem>(); PageSizeOptions = new List<SelectListItem>(); }
public CategoryModel() { PictureModel = new PictureModel(); FeaturedProducts = new List <ProductOverviewModel>(); Products = new List <ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); SubCategories = new List <SubCategoryModel>(); CategoryBreadcrumb = new List <CategoryModel>(); PictureModels = new List <PictureModel>(); //Price for Product AddToCart = new AddToCartModel(); TierPrices = new List <TierPriceModel>(); ProductPrice = new ProductPriceModel(); }
public ActionResult Manufacturer(int manufacturerId, CatalogPagingFilteringModel command) { var manufacturer = _manufacturerService.GetManufacturerById(manufacturerId); if (manufacturer == null || manufacturer.Deleted) return InvokeHttp404(); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a manufacturer before publishing if (!manufacturer.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageManufacturers)) return InvokeHttp404(); //ACL (access control list) if (!_aclService.Authorize(manufacturer)) return InvokeHttp404(); //Store mapping if (!_storeMappingService.Authorize(manufacturer)) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); var model = manufacturer.ToModel(); //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, manufacturer.AllowCustomersToSelectPageSize, manufacturer.PageSizeOptions, manufacturer.PageSize); //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(manufacturer.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, manufacturer.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //featured products if (!_catalogSettings.IgnoreFeaturedProducts) { IPagedList<Product> featuredProducts = null; //We cache a value indicating whether we have featured products var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles .Where(cr => cr.Active).Select(cr => cr.Id).ToList(); string cacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_HAS_FEATURED_PRODUCTS_KEY, manufacturerId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var hasFeaturedProductsCache = _cacheManager.Get<bool?>(cacheKey); if (!hasFeaturedProductsCache.HasValue) { //no value in the cache yet //let's load products and cache the result (true/false) featuredProducts = _productService.SearchProducts( manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); hasFeaturedProductsCache = featuredProducts.TotalCount > 0; _cacheManager.Set(cacheKey, hasFeaturedProductsCache, 60); } if (hasFeaturedProductsCache.Value && featuredProducts == null) { //cache indicates that the manufacturer has featured products //let's load them featuredProducts = _productService.SearchProducts( manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); } if (featuredProducts != null) { model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } } //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin: minPriceConverted, priceMax: maxPriceConverted, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_TEMPLATE_MODEL_KEY, manufacturer.ManufacturerTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _manufacturerTemplateService.GetManufacturerTemplateById(manufacturer.ManufacturerTemplateId); if (template == null) template = _manufacturerTemplateService.GetAllManufacturerTemplates().FirstOrDefault(); if (template == null) throw new Exception("No default template could be loaded"); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewManufacturer", _localizationService.GetResource("ActivityLog.PublicStore.ViewManufacturer"), manufacturer.Name); return View(templateViewPath, model); }
protected virtual void PreparePageSizeOptions(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command, bool allowCustomersToSelectPageSize, string pageSizeOptions, int fixedPageSize) { if (pagingFilteringModel == null) throw new ArgumentNullException("pagingFilteringModel"); if (command == null) throw new ArgumentNullException("command"); if (command.PageNumber <= 0) { command.PageNumber = 1; } pagingFilteringModel.AllowCustomersToSelectPageSize = false; if (allowCustomersToSelectPageSize && pageSizeOptions != null) { var pageSizes = pageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (category page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } pagingFilteringModel.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } if (pagingFilteringModel.PageSizeOptions.Any()) { pagingFilteringModel.PageSizeOptions = pagingFilteringModel.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); pagingFilteringModel.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(pagingFilteringModel.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = fixedPageSize; } //ensure pge size is specified if (command.PageSize <= 0) { command.PageSize = fixedPageSize; } }
public ActionResult Category(int categoryId, CatalogPagingFilteringModel command) { var category = _categoryService.GetCategoryById(categoryId); if (category == null || category.Deleted) return InvokeHttp404(); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a category before publishing if (!category.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) return InvokeHttp404(); //ACL (access control list) if (!_aclService.Authorize(category)) return InvokeHttp404(); //Store mapping if (!_storeMappingService.Authorize(category)) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); var model = category.ToModel(); //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, category.AllowCustomersToSelectPageSize, category.PageSizeOptions, category.PageSize); //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, category.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //category breadcrumb model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled; if (model.DisplayCategoryBreadcrumb) { foreach (var catBr in category.GetCategoryBreadCrumb(_categoryService, _aclService, _storeMappingService)) { model.CategoryBreadcrumb.Add(new CategoryModel() { Id = catBr.Id, Name = catBr.GetLocalized(x => x.Name), SeName = catBr.GetSeName() }); } } var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles .Where(cr => cr.Active).Select(cr => cr.Id).ToList(); //subcategories string subCategoriesCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_SUBCATEGORIES_KEY, categoryId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); model.SubCategories = _cacheManager.Get(subCategoriesCacheKey, () => { return _categoryService.GetAllCategoriesByParentCategoryId(categoryId) .Select(x => { var subCatModel = new CategoryModel.SubCategoryModel() { Id = x.Id, Name = x.GetLocalized(y => y.Name), SeName = x.GetSeName(), }; //prepare picture model int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var picture = _pictureService.GetPictureById(x.PictureId); var pictureModel = new PictureModel() { FullSizeImageUrl = _pictureService.GetPictureUrl(picture), ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatModel.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatModel.Name) }; return pictureModel; }); return subCatModel; }) .ToList(); }); //sibcategories string sibCategoriesCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_SIBCATEGORIES_KEY, categoryId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); model.SibCategories = _cacheManager.Get(sibCategoriesCacheKey, () => { return _categoryService.GetAllCategoriesByParentCategoryId(category.ParentCategoryId) .Select(x => { var sibCatModel = new CategoryModel.SubCategoryModel() { Id = x.Id, Name = x.GetLocalized(y => y.Name), SeName = x.GetSeName(), }; //prepare picture model int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); sibCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var picture = _pictureService.GetPictureById(x.PictureId); var pictureModel = new PictureModel() { FullSizeImageUrl = _pictureService.GetPictureUrl(picture), ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), sibCatModel.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), sibCatModel.Name) }; return pictureModel; }); return sibCatModel; }) .ToList(); }); //featured products if (!_catalogSettings.IgnoreFeaturedProducts) { //We cache a value indicating whether we have featured products IPagedList<Product> featuredProducts = null; string cacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY, categoryId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var hasFeaturedProductsCache = _cacheManager.Get<bool?>(cacheKey); if (!hasFeaturedProductsCache.HasValue) { //no value in the cache yet //let's load products and cache the result (true/false) featuredProducts = _productService.SearchProducts( categoryIds: new List<int>() { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); hasFeaturedProductsCache = featuredProducts.TotalCount > 0; _cacheManager.Set(cacheKey, hasFeaturedProductsCache, 60); } if (hasFeaturedProductsCache.Value && featuredProducts == null) { //cache indicates that the category has featured products //let's load them featuredProducts = _productService.SearchProducts( categoryIds: new List<int>() { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); } if (featuredProducts != null) { model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } } var categoryIds = new List<int>(); categoryIds.Add(category.Id); if (_catalogSettings.ShowProductsFromSubcategories) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(category.Id)); } //products IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, categoryIds: categoryIds, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts:_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin:minPriceConverted, priceMax:maxPriceConverted, filteredSpecs: alreadyFilteredSpecOptionIds, orderBy: ProductSortingEnum.StockAvailabilityAndPosition, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); //specs model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId); if (template == null) template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault(); if (template == null) throw new Exception("No default template could be loaded"); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewCategory", _localizationService.GetResource("ActivityLog.PublicStore.ViewCategory"), category.Name); return View(templateViewPath, model); }
protected virtual void PrepareSortingOptions(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command) { if (pagingFilteringModel == null) throw new ArgumentNullException("pagingFilteringModel"); if (command == null) throw new ArgumentNullException("command"); pagingFilteringModel.AllowProductSorting = _catalogSettings.AllowProductSorting; if (pagingFilteringModel.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } }
protected virtual void PrepareViewModes(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command) { if (pagingFilteringModel == null) throw new ArgumentNullException("pagingFilteringModel"); if (command == null) throw new ArgumentNullException("command"); pagingFilteringModel.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; pagingFilteringModel.ViewMode = viewMode; if (pagingFilteringModel.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid pagingFilteringModel.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Catalog.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list pagingFilteringModel.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Catalog.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } }
public ActionResult ShopByCategoryPaged(SearchModel model, CatalogPagingFilteringModel command) { model = GetCatalogSearhModel(model, command); return PartialView("_ProductList",model); }
public ActionResult Vendor(int vendorId, CatalogPagingFilteringModel command) { var vendor = _vendorService.GetVendorById(vendorId); if (vendor == null || vendor.Deleted) return InvokeHttp404(); //Vendor is active? if (!vendor.Active) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (command.PageNumber <= 0) command.PageNumber = 1; var model = new VendorModel() { Id = vendor.Id, Name = vendor.Name, Description = vendor.Description, SeName = SeoExtensions.GetSeName(vendor.Name) }; //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Vendors.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Vendors.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (_vendorSettings.AllowCustomersToSelectPageSize && _vendorSettings.PageSizeOptions != null) { var pageSizes = _vendorSettings.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (manufacturer page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = _vendorSettings.PageSize; } if (command.PageSize <= 0) command.PageSize = _vendorSettings.PageSize; //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, vendorId: vendor.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: null, priceMin: null, priceMax: null, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; return View(model); }
protected virtual void PrepareSortingOptions(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command) { if (pagingFilteringModel == null) throw new ArgumentNullException("pagingFilteringModel"); if (command == null) throw new ArgumentNullException("command"); var allDisabled = _catalogSettings.ProductSortingEnumDisabled.Count == Enum.GetValues(typeof(ProductSortingEnum)).Length; pagingFilteringModel.AllowProductSorting = _catalogSettings.AllowProductSorting && !allDisabled; var activeOptions = Enum.GetValues(typeof(ProductSortingEnum)).Cast<int>() .Except(_catalogSettings.ProductSortingEnumDisabled) .Select((idOption) => { int order; return new KeyValuePair<int, int>(idOption, _catalogSettings.ProductSortingEnumDisplayOrder.TryGetValue(idOption, out order) ? order : idOption); }) .OrderBy(x => x.Value); if (command.OrderBy == null) command.OrderBy = allDisabled ? 0 : activeOptions.First().Key; if (pagingFilteringModel.AllowProductSorting) { foreach (var option in activeOptions) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + (option.Key).ToString(), null); var sortValue = ((ProductSortingEnum)option.Key).GetLocalizedEnum(_localizationService, _workContext); pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem { Text = sortValue, Value = sortUrl, Selected = option.Key == command.OrderBy }); } } }
private SearchModel GetCatalogSearhModel(SearchModel model, CatalogPagingFilteringModel command) { //var model = new SearchModel(); //string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY, //_workContext.WorkingLanguage.Id, //string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), //_storeContext.CurrentStore.Id); var categoryIds = new List<int>(); var pvendorIds = new List<int>(); var customKeys = model.ss ?? new List<string>(); if (model.sms != null) customKeys.AddRange(model.sms); if (model.cid > 0) { categoryIds.Add(model.cid); var subcatids = _categoryService.GetAllCategoriesByParentCategoryId(model.cid).Select(c => c.Id).ToArray(); categoryIds.AddRange(subcatids); } var mdId = 0; decimal dsizeFrm = model.hm; decimal dsizeTo = model.hmx; PrepareViewModes(model.PagingFilteringContext, command); PreparePageSizeOptions(model.PagingFilteringContext, command, _catalogSettings.SearchPageAllowCustomersToSelectPageSize, _catalogSettings.SearchPagePageSizeOptions, _catalogSettings.SearchPageProductsPerPage); model.SelectedDimension = mdId; model.SizeFrom = dsizeFrm; model.SizeTo = dsizeTo; decimal sf = 0; decimal sst = 0; decimal varience = 10; var pgN = model.pg; var ipageSize = _catalogSettings.SearchPageProductsPerPage; if (command.PageSize == 0) command.PageSize = ipageSize; if (pgN == 0) command.PageNumber = 1; else command.PageNumber = pgN; var products = _productService.SearchProductsCustom( categoryIds: categoryIds, vendorIds: pvendorIds, customKeys: customKeys, sizeFrom: model.hm, sizeTo: model.hmx, varience: varience, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, keywords:model.q, languageId: _workContext.WorkingLanguage.Id, orderBy: ProductSortingEnum.Position, pageIndex: command.PageNumber - 1, pageSize: command.PageSize, circaDateFrom:model.cdf ?? "", circaDateTo: model.cdt ?? "", color:model.c ?? "", designBy:model.d ?? "", widthFrom:model.wm, widthTo: model.wmx, priceMax:model.pmx, priceMin:model.pm); model.Products = PrepareProductOverviewModelsIB(products).OrderBy(p => p.Name).ToList(); model.PagingFilteringContext.LoadPagedList(products); return model; }
public ActionResult Search(AUSearchModel model, CatalogPagingFilteringModel command) { //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (model == null) { model = new AUSearchModel(); } var searchTerms = model.q; if (searchTerms == null) searchTerms = ""; searchTerms = searchTerms.Trim(); //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, _catalogSettings.SearchPageAllowCustomersToSelectPageSize, _catalogSettings.SearchPagePageSizeOptions, _catalogSettings.SearchPageProductsPerPage); //TODO: only show searchable categories that have an actual lot? string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id); var categories = _cacheManager.Get(cacheKey, () => { var categoriesModel = new List<SearchModel.CategoryModel>(); //all categories var allCategories = _categoryService.GetAllCategories(); foreach (var c in allCategories) { //generate full category name (breadcrumb) string categoryBreadcrumb = ""; var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService); for (int i = 0; i <= breadcrumb.Count - 1; i++) { categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name); if (i != breadcrumb.Count - 1) categoryBreadcrumb += " >> "; } categoriesModel.Add(new SearchModel.CategoryModel { Id = c.Id, Breadcrumb = categoryBreadcrumb }); } return categoriesModel; }); if (categories.Count > 0) { //first empty entry model.AvailableCategories.Add(new SelectListItem { Value = "0", Text = _localizationService.GetResource("Common.All") }); //all other categories foreach (var c in categories) { model.AvailableCategories.Add(new SelectListItem { Value = c.Id.ToString(), Text = c.Breadcrumb, Selected = model.cid == c.Id }); } } //Load up Countries dropdown only with countries assigned to lots string countryCacheKey = string.Format(AUConsignorCacheEventConsumer.ACTIVE_COUNTRY_NAVIGATION_PATTERN_KEY, _workContext.WorkingLanguage.Id, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id); var countries = _cacheManager.Get(countryCacheKey, () => { var lotcountries = _consignorService.GetLotCountries(); return lotcountries; } ); model.AvailableCountries.Add(new SelectListItem { Value = "0", Text = _localizationService.GetResource("Common.All") }); //all other categories foreach (var co in countries) { model.AvailableCountries.Add(new SelectListItem { Value = co.Id.ToString(), Text = co.Name, Selected = model.countryid == co.Id //?? }); } //TODO: NEED TO CACHE THIS WITH THE COUNTRY ID //Load up Countries dropdown only with countries assigned to lots string stateprovinceCacheKey = string.Format(AUConsignorCacheEventConsumer.ACTIVE_STATEPROVINCES_BY_COUNTRY_MODEL_KEY, model.stateprovinceid, model.stateprovinceid, _workContext.WorkingLanguage.Id); var states = _cacheManager.Get(stateprovinceCacheKey, () => { var lotstates = model.countryid != 0 ? _consignorService.GetLotStateProvincesByCountryId(model.countryid, true).ToList() : new List<StateProvince>(); return lotstates; } ); if (states.Count > 0) { model.AvailableStateProvinces.Add(new SelectListItem { Text = "All", Value = "0", Selected = (0 == model.stateprovinceid) }); foreach (var s in states) { model.AvailableStateProvinces.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == model.stateprovinceid) }); } } else model.AvailableStateProvinces.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" }); //TODO: only show manufactureres in retail or mixed mode stores ////var manufacturers = _manufacturerService.GetAllManufacturers(); ////if (manufacturers.Count > 0) ////{ //// model.AvailableManufacturers.Add(new SelectListItem //// { //// Value = "0", //// Text = _localizationService.GetResource("Common.All") //// }); //// foreach (var m in manufacturers) //// model.AvailableManufacturers.Add(new SelectListItem //// { //// Value = m.Id.ToString(), //// Text = m.GetLocalized(x => x.Name), //// Selected = model.mid == m.Id //// }); ////} IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1); // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load) //NJM: had to add && Request.Params["q"] != "" because Serge's null check was not working if ((Request.Params["q"] != null && Request.Params["q"] != "") || ((Request.Params["q"] == null || Request.Params["q"] == "") && model.adv && (model.cid > 0 || model.countryid > 0 || model.SoldUnsold > 0 || !string.IsNullOrEmpty(model.pf) || !string.IsNullOrEmpty(model.pt)))) { if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength ) { model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength); } else { var categoryIds = new List<int>(); int manufacturerId = 0; decimal? minPriceConverted = null; decimal? maxPriceConverted = null; bool searchInDescriptions = false; if (model.adv) { //advanced search var categoryId = model.cid; if (categoryId > 0) { categoryIds.Add(categoryId); if (model.isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } } manufacturerId = model.mid; //min price if (!string.IsNullOrEmpty(model.pf)) { decimal minPrice; if (decimal.TryParse(model.pf, out minPrice)) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency); } //max price if (!string.IsNullOrEmpty(model.pt)) { decimal maxPrice; if (decimal.TryParse(model.pt, out maxPrice)) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency); } searchInDescriptions = model.sid; } //var searchInProductTags = false; var searchInProductTags = searchInDescriptions; //products ////products = _productService.SearchProducts( //// categoryIds: categoryIds, //// manufacturerId: manufacturerId, //// storeId: _storeContext.CurrentStore.Id, //// visibleIndividuallyOnly: true, //// priceMin: minPriceConverted, //// priceMax: maxPriceConverted, //// keywords: searchTerms, //// searchDescriptions: searchInDescriptions, //// searchSku: searchInDescriptions, //// searchProductTags: searchInProductTags, //// languageId: _workContext.WorkingLanguage.Id, //// orderBy: (ProductSortingEnum)command.OrderBy, //// pageIndex: command.PageNumber - 1, //// pageSize: command.PageSize); IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList<int> filterableSpecificationAttributeOptionIds; var lots = _consignorService.GetAllLots2( out filterableSpecificationAttributeOptionIds, true, //pageIndex: command.PageNumber - 1, //pageSize: command.PageSize, categoryIds: categoryIds, //manufacturerId: manufacturerId, //saleId: saleId, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, //featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin: minPriceConverted, priceMax: maxPriceConverted, soldUnsold: model.SoldUnsold, countryId: model.countryid, stateProvinceId: model.stateprovinceid, keywords: searchTerms, searchDescriptions: searchInDescriptions, searchSku: searchInDescriptions, searchProductTags: searchInProductTags, languageId: _workContext.WorkingLanguage.Id, filteredSpecs: alreadyFilteredSpecOptionIds, orderBy: (AUProductSortingEnum)command.OrderBy, showHidden: false, overridePublished: true ).Select(x => x.ToProduct()).ToList(); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product int totalRecords = lots.Count; int pageIndex = command.PageNumber - 1; int pageSize = command.PageSize; //NJM: need to cast lots List to IPagedList so can be used in model.PagingFilteringContext.LoadPagedList(products); You //can take this shit out when you go straight to IPagedList(AUCombLotProc) and take out ToProduct above products = new PagedList<Product>(lots, pageIndex, pageSize, totalRecords); //products = lots.Select(x => x.ToProduct()).ToList()); //).Select(x => x.ToProduct().ToList()); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product // ).Select(x => x.ToProduct()).ToList(); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product //this is where you need to change to insert the bidding info //Original: model.Products = PrepareProductOverviewModels(products).ToList(); //NJM: third true indicates to create specification model (default was false) model.Products = PrepareProductOverviewModels(products, true, true, null, true, false).ToList(); model.PagingFilteringContext.SpecificationFilter.Enabled = true; //NJM force this to allow spec filtering in search results model.PagingFilteringContext.LoadPagedList(products); //model.PagingFilteringContext.LoadPagedList(products); //NJM: add specsto search results model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); model.NoResults = !model.Products.Any(); //search term statistics if (!String.IsNullOrEmpty(searchTerms)) { var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id); if (searchTerm != null) { searchTerm.Count++; _searchTermService.UpdateSearchTerm(searchTerm); } else { searchTerm = new SearchTerm { Keyword = searchTerms, StoreId = _storeContext.CurrentStore.Id, Count = 1 }; _searchTermService.InsertSearchTerm(searchTerm); } } //event _eventPublisher.Publish(new ProductSearchEvent { SearchTerm = searchTerms, SearchInDescriptions = searchInDescriptions, CategoryIds = categoryIds, ManufacturerId = manufacturerId, WorkingLanguageId = _workContext.WorkingLanguage.Id }); } } else { // model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength); model.Warning = "You must enter at least one search criteria"; } return View(model); }
public ActionResult Manufacturer(int manufacturerId, CatalogPagingFilteringModel command) { var manufacturer = _manufacturerService.GetManufacturerById(manufacturerId); if (manufacturer == null || manufacturer.Deleted || !manufacturer.Published) return RedirectToAction("Index", "Home"); //'Continue shopping' URL _customerService.SaveCustomerAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false)); if (command.PageNumber <= 0) command.PageNumber = 1; var model = manufacturer.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Manufacturers.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Manufacturers.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (manufacturer.AllowCustomersToSelectPageSize && manufacturer.PageSizeOptions != null) { var pageSizes = manufacturer.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (manufacturer page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } if (command.PageSize <= 0) command.PageSize = manufacturer.PageSize; //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(manufacturer.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, manufacturer.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //featured products if (!_catalogSettings.IgnoreFeaturedProducts && _manufacturerService.GetTotalNumberOfFeaturedProducts(manufacturerId) > 0) { //We use the fast GetTotalNumberOfFeaturedProducts before invoking of the slow SearchProducts //to ensure that we have at least one featured product var featuredProducts = _productService.SearchProducts(0, manufacturer.Id, true, null, null, 0, null, false, _workContext.WorkingLanguage.Id, null, ProductSortingEnum.Position, 0, int.MaxValue); model.FeaturedProducts = featuredProducts.Select(x => PrepareProductOverviewModel(x)).ToList(); } //products var products = _productService.SearchProducts(0, manufacturer.Id, _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, minPriceConverted, maxPriceConverted, 0, string.Empty, false, _workContext.WorkingLanguage.Id, null, (ProductSortingEnum)command.OrderBy, command.PageNumber - 1, command.PageSize); model.Products = products.Select(x => PrepareProductOverviewModel(x)).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; //template var templateCacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_TEMPLATE_MODEL_KEY, manufacturer.ManufacturerTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _manufacturerTemplateService.GetManufacturerTemplateById(manufacturer.ManufacturerTemplateId); if (template == null) template = _manufacturerTemplateService.GetAllManufacturerTemplates().FirstOrDefault(); return template.ViewPath; }); return View(templateViewPath, model); }
//---------------------------------------------------------------------------------------------------------------------------------------------------- ////////Make sure sale increments are: //////// consecutive //////// don't intersect //////// begin at 0 //////// end at 9,999,999 //////[NonAction] //////protected virtual Boolean IncrementsAreGood(AUSaleRecord record) //////{ ////// var increments = record.AUIncrementRecords.OrderBy(a => a.FromBidAmt); ////// int count = 0; ////// decimal lowamt = decimal.MaxValue; ////// decimal highamt = 0; ////// decimal previoustoamt = 0; ////// foreach (var increment in increments) ////// { ////// if (increment.FromBidAmt < lowamt) ////// { lowamt = increment.FromBidAmt;} ////// if (increment.ToBidAmt > highamt) ////// { highamt = increment.ToBidAmt;} ////// //must ensure each increment is well formed before doing intersection checks below ////// if (increment.ToBidAmt <= increment.FromBidAmt) ////// return false; ////// //make sure this increment is consecutive to last increment (oncrements ordered by From amt) ////// if (count == 0) ////// {previoustoamt = increment.ToBidAmt;} ////// else ////// if (increment.FromBidAmt != previoustoamt + 1 ) ////// {return false;} ////// else ////// {previoustoamt = increment.ToBidAmt;} ////// count += 1; ////// } ////// //increments must begin in 0 and end in 9,999,999 ////// if (lowamt != 0 || highamt != 9999999) ////// {return false;} ////// var increments2 = record.AUIncrementRecords.OrderBy(a => a.FromBidAmt); ////// count = 0; ////// int count2 = 0; ////// foreach (var increment in increments) ////// { ////// foreach (var increment2 in increments2) ////// { ////// if (((increment.FromBidAmt >= increment2.FromBidAmt && increment.FromBidAmt <= increment2.ToBidAmt) || ////// (increment.ToBidAmt <= increment2.ToBidAmt && increment.ToBidAmt >= increment2.FromBidAmt )) && ////// (count != count2)) ////// { return false; } ////// count2 += 1; ////// } ////// count2 = 0; ////// count += 1; ////// } ////// return true; //////} #endregion #region Methods //--------------------------------------------------------------------------------------------------------------------------------------------- ////////When a view is returned, it expects that an associated .cshtml file is in the same view folder ////////structure as the controller layout for that area (if no areas are in use, then there is only ////////1 view folder and 1 controller folder). The controller name will be the folder name in the views ////////folder, and the actionresult name will be the expected name of the .cshtml file. //------------------------------------------------------------------------------------------------------------------------------------------- ////////[NopHttpsRequirement(SslRequirement.No)] ////////public ActionResult Index() ////////{ //////// return View(); ////////} //--------------------------------------------------------------------------------------------------------------------------------------------- //////public ActionResult CreateUpdateConsignor(int ConsignorId = 0) //////{ ////// AUConsignorRecord consignor = new AUConsignorRecord(); ////// if (ConsignorId > 0) ////// { ////// consignor = _consignorRepo.GetById(ConsignorId); ////// } ////// //indicate if entity has a fee associated. This tells Consignor page not to show fees fields if already has fee (maintain through grid) ////// var fee = _consignorService.GetFeesForOneId(ConsignorId, "AUConsignor"); ////// //return View(consignment); //use with custome view engine ////// //return View("CreateUpdatePromoSlider"); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// return View("~/Views/AUConsignor/CreateUpdateConsignor.cshtml", consignor); //worked first time null ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml", slider); //////} //--------------------------------------------------------------------------------------------------------------------------------------------------- ////////this post happens when you click 'Save' //////[HttpPost] //////public ActionResult CreateUpdateConsignor(AUConsignorRecord record) //////{ ////// if (ModelState.IsValid) ////// { ////// AUConsignorRecord consignor = _consignorRepo.GetById(record.AUConsignorID); ////// if (consignor == null) ////// { ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// record.CreatedBy = CurrentCustomer.Username; ////// record.UpdatedBy = CurrentCustomer.Username; ////// record.CreatedOnDT = System.DateTime.UtcNow; ////// record.UpdatedOnDT = System.DateTime.UtcNow; ////// //Make updated by same as created by date for initial store ////// //record.UpdatedOnDT = System.DateTime.UtcNow; ////// record.UpdatedOnDT = record.CreatedOnDT; ////// _consignorRepo.Insert(record); ////// //store a blank fee at the highest level to make consignor fees easier/more consistent grid design ////// var fee = new AUFeesRecord(); ////// fee.AUEntityID = record.AUConsignorID; ////// fee.AUEntityType = "AUConsignor"; ////// fee.CommissionCanExceedReserveInd = false; ////// fee.ExpertisingFeeAmt = 0; ////// fee.FixedFeeAmt = 0; ////// fee.InsuranceSoldPct = 0; ////// fee.InsuranceUnsoldPct = 0; ////// fee.InterestOnAdvancePct = 0; ////// fee.MinCommissionMailSoldAmt = 0; ////// fee.MinCommissionMailUnsoldAmt = 0; ////// fee.MinCommissionPublicSoldAmt = 0; ////// fee.MinCommissionPublicUnsoldAmt = 0; ////// fee.MinimumConsignorTotalFeeAmt = 0; ////// fee.MiscFeeAmt = 0; ////// fee.SoldPct = 0; ////// fee.UnsoldPct = 0; ////// _feesRepo.Insert(fee); ////// SuccessNotification("Consignor Created Successfully - please add consignments and fees!"); ////// return RedirectToRoute(new ////// { ////// Action = "CreateUpdateConsignor", ////// Controller = "AUConsignor", ////// ConsignorId = record.AUConsignorID ////// }); ////// } ////// else ////// { ////// //use latest consignor record to update with most up-do-date data rather than stale record ////// consignor.Prefix = record.Prefix; ////// consignor.FirstName = record.FirstName; ////// consignor.MiddleName = record.MiddleName; ////// consignor.LastName = record.LastName; ////// consignor.CustomerID = record.CustomerID; ////// consignor.Suffix = record.Suffix; ////// consignor.WEMailID = record.WEMailID; ////// consignor.HEMailID = record.HEMailID; ////// consignor.EMailPrefCode = record.EMailPrefCode; ////// //consignor.CommissionCanExceedReserveInd = record.CommissionCanExceedReserveInd; ////// //consignor.SoldPct = record.SoldPct; ////// //consignor.UnsoldPct = record.UnsoldPct; ////// //consignor.InsuranceSoldPct = record.InsuranceSoldPct; ////// //consignor.InsuranceUnsoldPct = record.InsuranceUnsoldPct; ////// //consignor.MinCommissionPublicSoldAmt = record.MinCommissionPublicSoldAmt; ////// //consignor.MinCommissionPublicUnsoldAmt = record.MinCommissionPublicUnsoldAmt; ////// //consignor.MinCommissionMailSoldAmt = record.MinCommissionMailSoldAmt; ////// //consignor.MinCommissionMailUnsoldAmt = record.MinCommissionMailUnsoldAmt; ////// //consignor.FixedFeeAmt = record.FixedFeeAmt; ////// //consignor.MinimumConsignorTotalFeeAmt = record.MinimumConsignorTotalFeeAmt; ////// //consignor.InterestOnAdvancePct = record.InterestOnAdvancePct; ////// //consignor.MiscFeeAmt = record.MiscFeeAmt; ////// //consignor.MiscFeeAmt = record.MiscFeeAmt; ////// //consignor.MiscFeeType = record.MiscFeeType; ////// //consignor.ExpertisingFeeAmt = record.ExpertisingFeeAmt; ////// //consignor.CreatedOnDT = System.DateTime.UtcNow; --> don't overlay created info ////// //consignor.CreatedBy = CurrentCustomer.Username; ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// consignor.UpdatedBy = CurrentCustomer.Username; ////// consignor.UpdatedOnDT = System.DateTime.UtcNow; ////// //this is how nop converts it back out ////// //consignor.CreatedOnDT = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc); ////// //public virtual DateTime CreatedOnDT { get; set; } ////// //public virtual string CreatedBy { get; set; } ////// //public virtual DateTime UpdatedOnDT { get; set; } ////// //public virtual string UpdatedBy { get; set; } ////// _consignorRepo.Update(consignor); ////// _cacheManager.Clear(); ////// SuccessNotification("Changed Saved!"); ////// //return View(consignment); //now with customer view engine ////// return View("~/Views/AUConsignor/CreateUpdateConsignor.cshtml", consignor); //not hit first time?? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml", slider); ////// } ////// } ////// else ////// { ////// return View(); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); //not hit first time? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// } //////} //---------------------------------------------------------------------------------------------------------------------------------------------- ////////TODO: GET RID OF THIS VIEW?? ////////public ActionResult CreateUpdateOneFees(int oneID = 0, string entityType = null) ////////{ //////// //AUFeesRecord fees = new AUFeesRecord(); //////// //if (oneID > 0 && entityType != null) //////// //{ //////// // fees = _consignorService.GetFeesForOneId(oneID, entityType); //////// //} //////// ViewBag.oneID = oneID; //////// ViewBag.entityType = entityType; //////// return View("~/Views/AUConsignor/CreateUpdateOneFees.cshtml"); ////////} //--------------------------------------------------------------------------------------------------------------------------------------------------- //////public ActionResult GetFeesList(int oneID = 0, string entityType = null) //////{ ////// //var consignments = _consignmentService.GetAllConsignments( ////// // consignorId: consignorID, ////// // consignmentId: 0, ////// // desc: null, ////// // pageIndex: 0, ////// // pageSize: 500); ////// var feeslist = new List<AUFeesRecord>(); ////// var allfees = _consignorService.GetFeesHierarchyForEntryPoint(oneID, entityType); ////// var gridModel = new DataSourceResult(); ////// //may be null if fees never created for consignor or if entries not created in hierachy ////// // if (allfees[0] != null) --fails on index if none found ////// //04/18/16 - fix order of fees list allfees = allfees.OrderBy(f => f.AUEntityType).ToList(); ////// allfees = allfees.OrderBy(f => f.DisplayOrder).ToList(); ////// if (allfees.Count > 0) ////// { ////// gridModel.Data = allfees.Select(x => new ////// { ////// AUFeesID = x.AUFeesID, ////// AUEntityType = x.AUEntityType, ////// AUEntityID = x.AUEntityID, ////// CommissionCanExceedReserveInd = x.CommissionCanExceedReserveInd, ////// SoldPct = x.SoldPct, ////// UnsoldPct = x.UnsoldPct, ////// InsuranceSoldPct = x.InsuranceSoldPct, ////// InsuranceUnsoldPct = x.InsuranceUnsoldPct, ////// MinCommissionPublicSoldAmt = x.MinCommissionPublicSoldAmt, ////// MinCommissionPublicUnsoldAmt = x.MinCommissionPublicUnsoldAmt, ////// MinCommissionMailSoldAmt = x.MinCommissionMailSoldAmt, ////// MinCommissionMailUnsoldAmt = x.MinCommissionMailUnsoldAmt, ////// FixedFeeAmt = x.FixedFeeAmt, ////// MinimumConsignorTotalFeeAmt = x.MinimumConsignorTotalFeeAmt, ////// InterestOnAdvancePct = x.InterestOnAdvancePct, ////// MiscFeeAmt = x.MiscFeeAmt, ////// MiscFeeType = x.MiscFeeType, ////// ExpertisingFeeAmt = x.ExpertisingFeeAmt ////// }); ////// //Total = consignments.TotalCount ////// } ////// //var gridModel = new DataSourceResult ////// //{ ////// // Data = allfees.Select(x => new ////// // { ////// // AUFeesID = x.AUFeesID, ////// // AUEntityType = x.AUEntityType, ////// // AUEntityID = x.AUEntityID, ////// // CommissionCanExceedReserveInd = x.CommissionCanExceedReserveInd, ////// // SoldPct = x.SoldPct, ////// // UnsoldPct = x.UnsoldPct, ////// // InsuranceSoldPct = x.InsuranceSoldPct, ////// // InsuranceUnsoldPct = x.InsuranceUnsoldPct, ////// // MinCommissionPublicSoldAmt = x.MinCommissionPublicSoldAmt, ////// // MinCommissionPublicUnsoldAmt = x.MinCommissionPublicUnsoldAmt, ////// // MinCommissionMailSoldAmt = x.MinCommissionMailSoldAmt, ////// // MinCommissionMailUnsoldAmt = x.MinCommissionMailUnsoldAmt, ////// // FixedFeeAmt = x.FixedFeeAmt, ////// // MinimumConsignorTotalFeeAmt = x.MinimumConsignorTotalFeeAmt, ////// // InterestOnAdvancePct = x.InterestOnAdvancePct, ////// // MiscFeeAmt = x.MiscFeeAmt, ////// // MiscFeeType = x.MiscFeeType, ////// // ExpertisingFeeAmt = x.ExpertisingFeeAmt ////// // }), ////// // //Total = consignments.TotalCount ////// //}; ////// return Json(gridModel); //////} //--------------------------------------------------------------------------------------------------------------------------------------------- ////////02/25/15 - comment for now ////////[HttpPost] ////////public ActionResult CreateUpdateOneFees(AUFeesRecord fees) ////////{ //////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); //////// //session.CreatedBy = CurrentCustomer.Username; //////// //session.UpdatedBy = CurrentCustomer.Username; //////// //session.CreatedOnDT = System.DateTime.UtcNow; //////// //session.UpdatedOnDT = System.DateTime.UtcNow; //////// //var sale = _saleRepo.GetById(session.AUSaleID); //////// //sale.AUSessionRecords.Add(session); //////// //_saleRepo.Update(sale); //////// SuccessNotification("Consignor Fees Updated!", false); //////// return View("~/Views/AUConsignor/CreateUpdateOneFees.cshtml", fees); ////////} //------------------------------------------------------------------------------------------------------------------------------------------------------ //////public ActionResult CreateUpdateConsignment(int ConsignorId = 0, int ConsignmentId = 0) //////{ ////// //AUConsignmentRecord consignment = new AUConsignmentRecord() { ConsignmentDesc = "Test" }; ////// //AUConsignorRecord consignor = new AUConsignorRecord(); ////// AUCombConsignorConsignment combined = new AUCombConsignorConsignment(); ////// //string x = "not there"; ////// //string y = "not there"; ////// //if (RouteData.Values["ConsignmentId"] != null) ////// //{ ////// // x = RouteData.Values["ConsignmentId"].ToString(); ////// //} ////// //if (RouteData.DataTokens != null) ////// //{ ////// // y = RouteData.DataTokens.ToString(); ////// //} ////// if (ConsignmentId > 0) ////// { ////// combined.AUConsignmentRecord = _consignmentRepo.GetById(ConsignmentId); ////// //consignment = _consignmentRepo.GetById(ConsignmentId); ////// } ////// else ////// { ////// //need to do this to make sure model is valid for ADD ////// combined.AUConsignmentRecord = new AUConsignmentRecord(); ////// combined.AUConsignmentRecord.AUConsignmentID = 0; //set this because kick model invalid in POST otherwise ////// } ////// if (ConsignorId > 0) ////// { ////// combined.AUConsignorRecord = _consignorRepo.GetById(ConsignorId); ////// //consignor = _consignorRepo.GetById(ConsignorId); ////// //--AUConsignorConsignmentRecord testc = new AUConsignorConsignmentRecord(); ////// //--testc.AUConsignorID = ConsignorId; ////// // testc.AUConsignorID = consignor.AUConsignorID; ////// //testc.AUConsignmentID = r2.AUConsignmentID; ////// //testc.Term = "F**k"; ////// //--consignment.AUConsignorRecords.Add(testc); ////// //--combined.AUConsignmentRecord.AUConsignorRecords.Add(testc); ////// } ////// //return View(consignment); //use with custome view engine ////// //return View("CreateUpdatePromoSlider"); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// //last one that worked ////// //return View("~/Views/AUConsignor/CreateUpdateConsignment.cshtml", consignment); //worked first time null ////// return View("~/Views/AUConsignor/CreateUpdateConsignment.cshtml", combined); //worked first time null ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml", slider); //////} //-------------------------------------------------------------------------------------------------------------------------------------------- //////[HttpPost] //////public ActionResult CreateUpdateConsignment(AUCombConsignorConsignment r2) //////{ ////// if (ModelState.IsValid) ////// { ////// AUConsignmentRecord consignment = _consignmentRepo.GetById(r2.AUConsignmentRecord.AUConsignmentID); ////// //DEBUG TO SEE IF r1 IS AVAILABLE ////// //TRY THIS WAY FIRST - NOT SURE BECAUSE MIGHT BE ABLE TO USE r1 ////// //MIGHT BE BEST ANYWAY TO ENSURE CORD STILL THERE ////// //no good !! could not instantiate ////// //AUConsignorRecord consignor = _consignorRepo.GetById(r1.AUConsignorID); ////// //string x = "not there"; ////// //if (RouteData.Values["ConsignmentId"] != null) ////// //{ ////// // x = RouteData.Values["ConsignmentId"].ToString(); ////// //} ////// //if (consignor == null) ////// //{ ////// // //place error handling here ////// //} ////// if (consignment == null) ////// { ////// //this worked but trying after insert ////// //AUConsignorConsignmentRecord testc = new AUConsignorConsignmentRecord(); ////// //testc.AUConsignorID = 1; ////// ////testc.AUConsignmentID = 1; ////// //testc.AUConsignmentID = r2.AUConsignmentID; //already known? ////// //testc.Term = "F**k"; ////// //r2.AUConsignorRecords.Add(testc); ////// //no good - can't update 2 entities ////// //r2.AUConsignmentRecord.CreatedOnDT = System.DateTime.UtcNow; ////// //r2.AUConsignmentRecord.UpdatedOnDT = System.DateTime.UtcNow; ////// //_combinedRepo.Insert(r2); ////// //try this first ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// r2.AUConsignmentRecord.CreatedBy = CurrentCustomer.Username; ////// r2.AUConsignmentRecord.UpdatedBy = CurrentCustomer.Username; ////// r2.AUConsignmentRecord.CreatedOnDT = System.DateTime.UtcNow; ////// r2.AUConsignmentRecord.UpdatedOnDT = System.DateTime.UtcNow; ////// _consignmentRepo.Insert(r2.AUConsignmentRecord); ////// //try this second ////// //AUConsignmentRecord consignment2 = new AUConsignmentRecord() { ConsignmentDesc = "Test" }; ////// //consignment2.CreatedOnDT = System.DateTime.UtcNow; ////// //consignment2.UpdatedOnDT = System.DateTime.UtcNow; ////// //consignment2.ConsignmentDate = r2.AUConsignmentRecord.ConsignmentDate; ////// //consignment2.ConsignmentDesc = r2.AUConsignmentRecord.ConsignmentDesc; ////// //_consignmentRepo.Insert(consignment2); ////// /* ////// consignment.ConsignmentDate = r2.AUConsignmentRecord.ConsignmentDate; ////// consignment.ConsignmentDesc = r2.AUConsignmentRecord.ConsignmentDesc; ////// _consignmentRepo.Insert(consignment); ////// */ ////// //try 1 ////// AUConsignorConsignmentRecord testc = new AUConsignorConsignmentRecord(); ////// testc.AUConsignmentID = r2.AUConsignmentRecord.AUConsignmentID; ////// testc.AUConsignorID = r2.AUConsignorRecord.AUConsignorID; ////// testc.Term = "Help!"; ////// r2.AUConsignmentRecord.AUConsignorRecords.Add(testc); ////// _consignmentRepo.Update(r2.AUConsignmentRecord); ////// ////try 2 ////// //AUConsignorConsignmentRecord testc = new AUConsignorConsignmentRecord(); ////// //testc.AUConsignmentID = consignment2.AUConsignmentID; ////// //testc.AUConsignorID = r2.AUConsignorRecord.AUConsignorID; ////// //testc.Term = "Help!"; ////// //consignment2.AUConsignorRecords.Add(testc); ////// //_consignmentRepo.Update(consignment2); ////// //var toUpdate = r2.AUConsignorRecords.First(); ////// //toUpdate.AUConsignmentID = r2.AUConsignmentID; ////// //_consignmentRepo.Update(r2); ////// /* worked ////// //fails because trying to insert AUConsignor again ////// AUConsignorConsignmentRecord testc = new AUConsignorConsignmentRecord(); ////// //AUConsignmentRecord consignment2 = _consignmentRepo.GetById(r2.AUConsignmentID); ////// //testc.AUConsignorID = 1; WORKED ////// testc.AUConsignorID = consignor.AUConsignorID; ////// testc.AUConsignmentID = r2.AUConsignmentID; ////// testc.Term = "F**k"; ////// r2.AUConsignorRecords.Add(testc); ////// _consignmentRepo.Update(r2); ////// */ ////// //No Good - tried to insert AUConsignor again ////// //AUcc.AUConsignorID = 1; ////// //AUcc.AUConsignmentID = r2.AUConsignmentID; ////// //_consignorconsignmentRepo.Insert(AUcc); ////// //test shit out ////// //AUConsignorRecord c2 = new AUConsignorRecord(); ////// //c2.LastName = "consignor Last Name"; ////// //c2.AUConsignorID = 1; ////// //************************************** ////// //can only insert the same type passed in ////// //this is f*****g up consignment id for some reason ////// //************************************************* ////// //AUConsignmentRecord c2 = new AUConsignmentRecord(); ////// //c2.AUConsignmentID = 99; ////// //c2.ConsignmentDesc = "This is the first internally generated consignment"; ////// //_consignmentRepo.Insert(c2); ////// SuccessNotification("Consignment Created Successfully!"); ////// return RedirectToRoute(new ////// { ////// Action = "CreateUpdateConsignment", ////// Controller = "AUConsignor", ////// ConsignorId = r2.AUConsignorRecord.AUConsignorID, ////// ConsignmentId = r2.AUConsignmentRecord.AUConsignmentID ////// }); ////// } ////// else ////// { ////// //use latest data in consignment rather that stale R2 ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// consignment.UpdatedBy = CurrentCustomer.Username; ////// consignment.UpdatedOnDT = System.DateTime.UtcNow; ////// consignment.ConsignmentDate = r2.AUConsignmentRecord.ConsignmentDate; ////// consignment.ConsignmentDesc = r2.AUConsignmentRecord.ConsignmentDesc; ////// //System.DateTime? cDate = null; ////// //try ////// //{ ////// // cDate = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value); ////// //} ////// //catch { } ////// r2.AUConsignmentRecord.UpdatedOnDT = consignment.UpdatedOnDT; ////// r2.AUConsignmentRecord.UpdatedBy = consignment.UpdatedBy; ////// //test ////// //AUConsignorRecord c2 = new AUConsignorRecord(); ////// //c2.LastName = "consignor Last Name"; ////// //c2.AUConsignorID = 1; ////// //consignment.AUConsignorRecords.Add(c2); ////// //ViewBag.RowsAffected = db.Database.ExecuteSqlCommand("UPDATE Course SET Credits = Credits * {0}", multiplier); ////// _consignmentRepo.Update(consignment); ////// //can only insert the same type passed in ////// //AUConsignmentRecord c2 = new AUConsignmentRecord(); ////// //c2.AUConsignmentID = 99; ////// //c2.ConsignmentDesc = "This is the second updated description"; ////// //_consignmentRepo.Update(c2); ////// //AUConsignorRecord c2 = new AUConsignorRecord(); ////// //c2.LastName = "consignor New Last Name"; ////// //c2.AUConsignorID = 1; ////// //_consignmentRepo.Insert(); ////// _cacheManager.Clear(); ////// SuccessNotification("Changed Saved!"); ////// //return View(consignment); //now with customer view engine ////// return View("~/Views/AUConsignor/CreateUpdateConsignment.cshtml", r2); //not hit first time?? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml", slider); ////// } ////// } ////// else ////// { ////// //invalid model will show "default" error messages driven by record annotation/decorations ////// var errors = ModelState.Values.SelectMany(v => v.Errors); ////// return View("~/Views/AUConsignor/CreateUpdateConsignment.cshtml", r2); ////// //return View(); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); //not hit first time? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// } //////} //------------------------------------------------------------------------------------------------------------------------------------------------- //////public ActionResult CreateUpdateSale(int SaleId = 0) //////{ ////// AUSaleRecord sale = new AUSaleRecord(); ////// if (SaleId > 0) ////// { ////// sale = _saleRepo.GetById(SaleId); //this will have all the sessions and addresses!!!!! ////// } ////// ViewBag.SaleIsPublished = sale.SaleIsPublished; ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", sale); ////// // WORKS!! return View("CreateUpdateSale", sale); //This is what works with the view engine!!!! //////} //---------------------------------------------------------------------------------------------------------------------------------------------------- ////////this post happens when you click 'Save' //////[HttpPost] //////public ActionResult CreateUpdateSale(AUSaleRecord record, string save) //////{ ////// if (save.Equals("Award Sale")) //see http://stackoverflow.com/questions/19650345/mvc-razor-form-with-multiple-different-submit-buttons ////// { ////// _consignorService.AwardSale(record.AUSaleID, record.SaleStoreID); ////// //TempData["notice"] = "Sale Successfully Awarded"; --from google ////// SuccessNotification("Sale Awarded!!"); //seems to be nop admin convention ////// return RedirectToAction("CreateUpdateSale"); ////// } ////// //%%%%%the nav properties are gone, but the form values are there! reget the nav properties with getbyid before testing ////// if (ModelState.IsValid) ////// { ////// AUSaleRecord sale = _saleRepo.GetById(record.AUSaleID); ////// if (sale == null) ////// { ////// if (!record.SaleIsPublished) ////// { ////// _consignorService.InsertSale(record); ////// SuccessNotification("Sale Created Successfully!"); ////// return RedirectToRoute(new ////// { ////// Action = "CreateUpdateSale", ////// Controller = "AUConsignor", ////// SaleId = record.AUSaleID ////// }); ////// } ////// else ////// { ////// ErrorNotification("Insert of new sale not successful - trying to publish sale but something is wrong with your sale increments."); ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", record); ////// } ////// } ////// else //sale already exists so this will be an update. Use latest consignor record to update with most up-do-date data rather than stale record ////// { ////// sale.AUSaleNbr = record.AUSaleNbr; ////// sale.SaleTitle = record.SaleTitle; ////// sale.SaleDesc = record.SaleDesc; ////// sale.SaleStartDateTime = record.SaleStartDateTime; ////// sale.SaleEndDateTime = record.SaleEndDateTime; ////// sale.SaleStoreID = record.SaleStoreID; ////// sale.SaleIsAwarded = record.SaleIsAwarded; ////// sale.SaleType = record.SaleType; ////// sale.CreatedOnDT = System.DateTime.UtcNow; ////// sale.UpdatedOnDT = sale.CreatedOnDT; //make sure dates are the same on insert ////// //sale.UpdatedOnDT = System.DateTime.UtcNow; ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// sale.UpdatedBy = CurrentCustomer.Username; ////// if (!record.SaleIsPublished) //not trying to publish sale so no further checking needed ////// { ////// //_consignorService.UpdateSale(sale,record); ////// // _cacheManager.Clear(); ////// sale.SaleIsPublished = record.SaleIsPublished; ////// _saleRepo.Update(sale); ////// SuccessNotification("Changes to Sale saved!"); ////// //return View(consignment); //now with customer view engine ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", sale); //BAD ////// } ////// else if (IncrementsAreGood(sale)) ////// { ////// //_consignorService.UpdateSale(sale,record); ////// sale.SaleIsPublished = record.SaleIsPublished; ////// _saleRepo.Update(sale); ////// //_cacheManager.Clear(); ////// SuccessNotification("Changes to Sale saved!"); ////// //return View(consignment); //now with customer view engine ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", sale); //BAD ////// } ////// else ////// { ////// ModelState.Remove("SaleIsPublished"); ////// sale.SaleIsPublished = false; ////// //ModelState.Remove("SaleIsPublished"); ////// ErrorNotification("Update sale not successful - trying to publish sale but something is wrong with your sale increments. Fix increments before trying to publish"); ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", sale); ////// } ////// } ////// } ////// else //model state is not valid ////// { ////// ErrorNotification("Invalid Model - Update not applied."); ////// return View("~/Views/AUConsignor/CreateUpdateSale.cshtml", record); ////// //return View(); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); //not hit first time? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// } //////} //---------------------------------------------------------------------------------------------------------------------------------------------------- //////public ActionResult CreateUpdateAddress(int addressId = 0, int saleId = 0) //////{ ////// AUCombAddress address = new AUCombAddress(); ////// address.AUAddressRecord = new AUAddressRecord(); //must instantiate the record within the record ////// if (addressId > 0) ////// { ////// address.AUAddressRecord = _addressRepo.GetById(addressId); ////// } ////// else ////// { ////// //need to do this to make sure model is valid for ADD ////// address.AUAddressRecord.AUAddressID = 0; ////// } ////// if (saleId > 0) ////// { ////// address.saleId = saleId; ////// } ////// else ////// { ////// //need to do this to make sure model is valid for ADD ////// address.saleId = saleId = 0; ////// } ////// //Populate Countries (see CustomerController) ////// address.AUAddressRecord.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" }); ////// foreach (var c in _countryService.GetAllCountries(true)) ////// { ////// address.AUAddressRecord.AvailableCountries.Add(new SelectListItem ////// { ////// Text = c.Name, ////// Value = c.Id.ToString(), ////// Selected = c.Id == address.AUAddressRecord.CountryId ////// }); ////// } ////// //Populate State/Province (see CustomerController). Had to take the ? away from Country ID as this statement complained ////// //that the parameter was invalid ////// var states = _stateProvinceService.GetStateProvincesByCountryId(address.AUAddressRecord.CountryId, false).ToList(); ////// if (states.Count > 0) ////// { ////// address.AUAddressRecord.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectState"), Value = "0" }); ////// foreach (var s in states) ////// { ////// address.AUAddressRecord.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == address.AUAddressRecord.StateProvinceId) }); ////// } ////// } ////// else ////// { ////// bool anyCountrySelected = address.AUAddressRecord.AvailableCountries.Any(x => x.Selected); ////// address.AUAddressRecord.AvailableStates.Add(new SelectListItem ////// { ////// Text = _localizationService.GetResource(anyCountrySelected ? "Admin.Address.OtherNonUS" : "Admin.Address.SelectState"), ////// Value = "0" ////// }); ////// } ////// return View("~/Views/AUConsignor/CreateUpdateAddress.cshtml", address); //worked first time null //////} //------------------------------------------------------------------------------------------------------------------------------------- ////////this post happens when you click 'Save' //////[HttpPost] //////public ActionResult CreateUpdateAddress(AUCombAddress record) //////{ ////// if (ModelState.IsValid) ////// { ////// AUAddressRecord address = _addressRepo.GetById(record.AUAddressRecord.AUAddressID); ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// record.AUAddressRecord.CreatedBy = CurrentCustomer.Username; ////// record.AUAddressRecord.UpdatedBy = CurrentCustomer.Username; ////// record.AUAddressRecord.CreatedOnDT = System.DateTime.UtcNow; ////// record.AUAddressRecord.UpdatedOnDT = System.DateTime.UtcNow; ////// if (address == null) ////// { ////// _addressRepo.Insert(record.AUAddressRecord); ////// SuccessNotification("Address Created Successfully!"); ////// return RedirectToRoute(new ////// { ////// Action = "CreateUpdateAddress", ////// Controller = "AUConsignor", ////// addressId = record.AUAddressRecord.AUAddressID, ////// saleId = record.saleId ////// }); ////// } ////// else ////// { ////// //use latest consignor record to update with most up-do-date data rather than stale record ////// address.Address1 = record.AUAddressRecord.Address1; ////// address.Address2 = record.AUAddressRecord.Address2; ////// address.AddressHtml = record.AUAddressRecord.AddressHtml; ////// address.City = record.AUAddressRecord.City; ////// address.CountryId = record.AUAddressRecord.CountryId; ////// address.StateProvinceId = record.AUAddressRecord.StateProvinceId; ////// address.ZipPostalCode = record.AUAddressRecord.ZipPostalCode; ////// //address.StateProvinceName = record.StateProvinceName; ////// //address.CountryName = record.CountryName; ////// //try this ////// //.ForMember(dest => dest.CountryName, mo => mo.MapFrom(src => src.Country != null ? src.Country.Name : null)) ////// address.UpdatedOnDT = record.AUAddressRecord.UpdatedOnDT; ////// address.UpdatedBy = record.AUAddressRecord.UpdatedBy; ////// //int id = NopContext.Current.User != null ? NopContext.Current.User.CustomerId : 0 ////// //NopContext.Current.User.CustomerId is no more present in version 3.0 ////// //this is how nop converts it back out ////// //consignor.CreatedOnDT = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc); ////// //public virtual DateTime CreatedOnDT { get; set; } ////// //public virtual string CreatedBy { get; set; } ////// //public virtual DateTime UpdatedOnDT { get; set; } ////// //public virtual string UpdatedBy { get; set; } ////// _addressRepo.Update(address); ////// // _cacheManager.Clear(); //took this out because it was killing the session ////// SuccessNotification("Changed Saved!"); ////// //return View("~/Views/AUConsignor/CreateUpdateAddress.cshtml", address); //not hit first time?? ////// //need redirect so can pick up country/state lists again ////// //if (record.saleId == 0) ////// //{ ////// return RedirectToRoute(new ////// { ////// Action = "CreateUpdateAddress", ////// Controller = "AUConsignor", ////// addressId = record.AUAddressRecord.AUAddressID, ////// saleId = record.saleId ////// }); ////// //} ////// //else ////// //{ ////// // return RedirectToRoute(new ////// // { ////// // Action = "CreateUpdateSale", ////// // Controller = "AUConsignor", ////// // saleId = record.saleId ////// // }); ////// //} ////// } ////// } ////// else ////// { ////// return View(); ////// //return View("~/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); //not hit first time? ////// //return View("~/Plugins/Widgets.PromoSlider/Views/PromoSlider/CreateUpdatePromoSlider.cshtml"); ////// } //////} //------------------------------------------------------------------------------------------------------------------------------- //////public ActionResult ListOneConsignments(int consignorID = 0) //////{ ////// AUConsignmentList consignments = new AUConsignmentList(); ////// consignments.searchAUConsignorID = consignorID; ////// return View("~/Views/AUConsignor/OneConsignorConsignments.cshtml", consignments); //////} //-------------------------------------------------------------------------------------------------------------------------------- ////////Consignor-consignments is an example of how to use an existing search to limit ////////consignments to one specific consignor. An example of how to use EF record definition ////////is in Sale-Sessions //////[HttpPost] //////public ActionResult ListXConsignments(int consignorID) //////{ ////// var consignments = _consignmentService.GetAllConsignments( ////// consignorId: consignorID, ////// consignmentId: 0, ////// desc: null, ////// pageIndex: 0, ////// pageSize: 500); ////// var gridModel = new DataSourceResult ////// { ////// Data = consignments.Select(x => new ////// { ////// AUConsignorID = x.AUConsignorRecords.First().AUConsignorID, ////// AUConsignmentID = x.AUConsignmentID, ////// ConsignmentDate = x.ConsignmentDate, ////// ConsignmentDesc = x.ConsignmentDesc ////// }), ////// Total = consignments.TotalCount ////// }; ////// return Json(gridModel); //////} //------------------------------------------------------------------------------------------------------------------------------ ////////kill this for now ////////public ActionResult ManageSaleSessions(int saleID = 0) ////////{ //////// AUSaleRecord sale = new AUSaleRecord(); //////// if (saleID > 0) //////// { //////// sale = _saleRepo.GetById(saleID); //this will have all the sessions and addresses!!!!! //////// } //////// return View("~/Views/AUConsignor/OneSaleSessions.cshtml",sale); ////////} //----------------------------------------------------------------------------------------------------------------------------- ////////display all lots associated to a sale for selection //////[ChildActionOnly] //////public ActionResult ManageSaleLots(int saleID = 0) //////{ ////// //AUSaleRecord increment = new AUIncrementRecord(); ////// //increment.AUSaleID = saleID; ////// //increment.AUIncrementID = 0; ////// ////%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ////// //session.AvailableAddresses.Add(new SelectListItem { Text = _localizationService.GetResource("Plugins.Misc.AUConsignor.SelectAddressMsg"), Value = "0" }); ////// //foreach (var c in _consignorService.GetAllAUAddresses()) ////// //{ ////// // session.AvailableAddresses.Add(new SelectListItem ////// // { ////// // Text = c.Address1 + ", " + c.Address2 + ", " + c.City, ////// // Value = c.AUAddressID.ToString(), ////// // Selected = c.AUAddressID == session.AUAddressID ////// // }); ////// //} ////// return View(); ////// //return View("~/Views/AUConsignor/ManageSaleIncrements.cshtml", increment); //////} //------------------------------------------------------------------------------------------------------------------------------- //////// [ChildActionOnly] ////// public ActionResult ManageSaleIncrements(int saleID = 0) ////// { ////// //put SaleIsPublished into ViewBag so view can hide the increment edit/delete buttons if published ////// var sale = _saleRepo.GetById(saleID); ////// ViewBag.SaleIsPublished = sale.SaleIsPublished; ////// AUIncrementRecord increment = new AUIncrementRecord(); ////// increment.AUSaleID = saleID; ////// increment.AUIncrementID = 0; ////// //session.AvailableAddresses.Add(new SelectListItem { Text = _localizationService.GetResource("Plugins.Misc.AUConsignor.SelectAddressMsg"), Value = "0" }); ////// //foreach (var c in _consignorService.GetAllAUAddresses()) ////// //{ ////// // session.AvailableAddresses.Add(new SelectListItem ////// // { ////// // Text = c.Address1 + ", " + c.Address2 + ", " + c.City, ////// // Value = c.AUAddressID.ToString(), ////// // Selected = c.AUAddressID == session.AUAddressID ////// // }); ////// //} ////// return View("~/Views/AUConsignor/ManageSaleIncrements.cshtml", increment); ////// } //////[ChildActionOnly] //////public ActionResult ManageSaleSessions(int saleID = 0) //////{ ////// AUSessionRecord session = new AUSessionRecord(); ////// session.AUSaleID = saleID; ////// session.AUSessionID = 0; ////// //%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ////// session.AvailableAddresses.Add(new SelectListItem { Text = _localizationService.GetResource("Plugins.Misc.AUConsignor.SelectAddressMsg"), Value = "0" }); ////// foreach (var c in _consignorService.GetAllAUAddresses()) ////// { ////// session.AvailableAddresses.Add(new SelectListItem ////// { ////// Text = c.Address1 + ", " + c.Address2 + ", " + c.City, ////// Value = c.AUAddressID.ToString(), ////// Selected = c.AUAddressID == session.AUAddressID ////// }); ////// } ////// return View("~/Views/AUConsignor/ManageSaleSessions.cshtml", session); //////} //////[HttpPost] //////public ActionResult CreateSaleSession(AUSessionRecord session) //////{ ////// if (!ModelState.IsValid) ////// { ////// ErrorNotification("something wrong with the model - notify admin"); ////// return View(); ////// } ////// //Recheck sale dates in case sale changed underneath session browser ////// var sale = _saleRepo.GetById(session.AUSaleID); ////// if (sale == null) ////// throw new NopException("Sale not found - please notify admin"); ////// if (session.SessionStartDateTime < sale.SaleStartDateTime || ////// session.SessionEndDateTime > sale.SaleEndDateTime || ////// session.SessionEndDateTime < sale.SaleStartDateTime || ////// session.SessionStartDateTime > sale.SaleEndDateTime) ////// { ////// ErrorNotification("Session dates must be within sale dates"); ////// return new NullJsonResult(); ////// } ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// session.CreatedBy = CurrentCustomer.Username; ////// session.UpdatedBy = CurrentCustomer.Username; ////// session.CreatedOnDT = System.DateTime.UtcNow; ////// session.UpdatedOnDT = session.CreatedOnDT; ////// //TODO: CHECK SESSION DATES WITHIN SALE FROM-TO ////// sale.AUSessionRecords.Add(session); ////// _saleRepo.Update(sale); ////// SuccessNotification("Session Added!", false); ////// return new NullJsonResult(); //////} //////[HttpPost] //////public ActionResult GetSaleSessionsList(int saleId) //////{ ////// var sessions = _saleRepo.GetById(saleId).AUSessionRecords.OrderBy(x => x.SessionStartDateTime); ////// var gridModel = new DataSourceResult ////// { ////// Data = sessions.Select(x => new ////// { ////// AUSessionID = x.AUSessionID, ////// AUSaleID = x.AUSaleID, ////// SessionStartDateTime = _dateTimeHelper.ConvertToUserTime(x.SessionStartDateTime, DateTimeKind.Local), ////// SessionEndDateTime = _dateTimeHelper.ConvertToUserTime(x.SessionEndDateTime, DateTimeKind.Local), ////// SessionDescription = x.SessionDescription, ////// AUAddressID = x.AUAddressID, ////// AddressName = x.AUAddressRecord.Address1 + ", " + x.AUAddressRecord.Address2 + ", " + x.AUAddressRecord.City ////// }), ////// Total = sessions.Count() ////// }; ////// return Json(gridModel); //////} //////[HttpPost] //////public ActionResult CreateSaleIncrement(AUIncrementRecord increment) //this reference is injected by autofac (the repo is part of dbcontext) //////{ ////// var CurrentCustomer = _authenticationService.GetAuthenticatedCustomer(); ////// increment.CreatedBy = CurrentCustomer.Username; ////// increment.UpdatedBy = CurrentCustomer.Username; ////// increment.CreatedOnDT = System.DateTime.UtcNow; ////// increment.UpdatedOnDT = System.DateTime.UtcNow; ////// var sale = _saleRepo.GetById(increment.AUSaleID); ////// sale.AUIncrementRecords.Add(increment); ////// _saleRepo.Update(sale); ////// _eventPublisher.EntityInserted(increment); //publish event that increment inserted to flush cache in C:\Users\Nicholas\Documents\My Documents\NopCommerce\Plugins\Nop.Plugin.Misc.AUConsignor\Infrastructure\AUConsignorCacheEventConsumer.cs ////// SuccessNotification("Increment Added!", false); ////// return new NullJsonResult(); //////} ////////TODO: this function is redundant to the service in AUConsignor.Services //////[HttpPost] //////public ActionResult GetSaleIncrementsList(int saleId) //////{ ////// var increments = _saleRepo.GetById(saleId).AUIncrementRecords.OrderBy(x => x.FromBidAmt); ////// var gridModel = new DataSourceResult ////// { ////// Data = increments.Select(x => new ////// { ////// AUIncrementID = x.AUIncrementID, ////// AUSaleID = x.AUSaleID, ////// FromBidAmt = x.FromBidAmt, ////// ToBidAmt = x.ToBidAmt, ////// IncrementAmt = x.IncrementAmt ////// }), ////// Total = increments.Count() ////// }; ////// return Json(gridModel); //////} ////////Make sure sale session being added is within boundaries of sale from-to dates. Leave this as a server call in ////////case of concurrent access and held browser. TODO: determine if should move to browser for speed //////public JsonResult CheckSessionSaleDates(int AUSaleID, DateTime SessionStartDateTime, DateTime SessionEndDateTime) //////{ ////// //condition for user check ////// if (AUSaleID == 0) ////// throw new ArgumentNullException("AUSaleID"); ////// var sale = _saleRepo.GetById(AUSaleID); ////// if (sale == null) ////// { ////// throw new ArgumentException("AUSaleID not found"); ////// } ////// if (SessionStartDateTime < sale.SaleStartDateTime || SessionEndDateTime > sale.SaleEndDateTime) ////// { ////// return Json("BAD", JsonRequestBehavior.AllowGet); ////// } ////// return Json("GOOD", JsonRequestBehavior.AllowGet); //////} /////////TODO: DON'T THINK THIS IS USED //////[HttpPost] //////public ActionResult ListXSessions(int saleID) //////{ ////// var sessions = _saleRepo.GetById(saleID).AUSessionRecords.OrderBy(x => x.SessionStartDateTime); ////// //var consignments = _consignmentService.GetAllConsignments( ////// // consignorId: consignorID, ////// // consignmentId: 0, ////// // desc: null, ////// // pageIndex: 0, ////// // pageSize: 500); ////// var gridModel = new DataSourceResult ////// { ////// Data = sessions.Select(x => new ////// { ////// AUSaleID = x.AUSaleID, ////// AUSessionID = x.AUSessionID, ////// SessionStartDateTime = x.SessionStartDateTime, ////// SessionEndDateTime = x.SessionEndDateTime, ////// }), ////// Total = sessions.Count(n => n.AUSessionID > 0) //see http://stackoverflow.com/questions/3853010/get-item-count-of-a-list-using-linq ////// }; ////// return Json(gridModel); //////} //////public ActionResult ManageConsignments() //////{ ////// //return View(); ////// AUConsignmentList listsearch = new AUConsignmentList(); ////// //if (consignorID != 0) { listsearch.searchAUConsignorID = consignorID;} ////// return View("~/Views/AUConsignor/ManageConsignments.cshtml", listsearch); //not hit first time?? //////} //////[HttpPost] //////public ActionResult ListConsignments(DataSourceRequest command, AUConsignmentList model) //////{ ////// int consignmentid = 0; ////// //string firstname = "Test"; ////// //string lastname = ""; ////// int consignorid = model.searchAUConsignorID; ////// string desc = model.searchDesc; ////// var consignments = _consignmentService.GetAllConsignments( ////// consignorId: consignorid, ////// consignmentId: consignmentid, ////// desc: desc, ////// pageIndex: 0, ////// pageSize: 500); ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize); ////// //TODO: THIS WILL NEED TO BE CHANGED WHEN YOU IMPLEMENT MORE THAN ONE CONSIGNOR PER CONSIGNMENT ////// var gridModel = new DataSourceResult ////// { ////// Data = consignments.Select(x => new ////// { ////// Id = x.Id, ////// AUConsignorID = x.AUConsignorRecords.First().AUConsignorID, //TODO: make this a "primary" consignor select or coalesce all consignors ////// AUConsignmentID = x.AUConsignmentID, ////// ConsignmentDate = x.ConsignmentDate, ////// ConsignmentDesc = x.ConsignmentDesc ////// }), ////// Total = consignments.TotalCount ////// }; ////// return Json(gridModel); //////} ////////list lots //////public ActionResult LotIndex() //////{ ////// return RedirectToAction("ListLots"); //////} ////////copied from C:\Users\Nicholas\Documents\My Documents\NopCommerce\Presentation\Nop.Web\Administration\Controllers\ProductController.cs //////public ActionResult ListLots() //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// var model = new AULotList(); ////// //a vendor should have access only to his products. Set the indicator in the model ////// model.IsLoggedInAsVendor = _workContext.CurrentVendor != null; ////// //categories ////// model.AvailableCategories.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// var categories = _categoryService.GetAllCategories(showHidden: true); ////// foreach (var c in categories) ////// model.AvailableCategories.Add(new SelectListItem { Text = c.GetFormattedBreadCrumb(categories), Value = c.Id.ToString() }); ////// //NJM: Sales ////// model.AvailableSales.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// var sales = _consignorService.GetAllSales( ////// saleId: 0, ////// saleNbr: null, ////// saleTitle: null, ////// pageIndex: 0, ////// pageSize: 2147483647); ////// foreach (var c in sales) ////// model.AvailableSales.Add(new SelectListItem { Text = c.AUSaleNbr, Value = c.AUSaleID.ToString() }); ////// //stores ////// model.AvailableStores.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// foreach (var s in _storeService.GetAllStores()) ////// model.AvailableStores.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); ////// //warehouses ////// model.AvailableWarehouses.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// foreach (var wh in _shippingService.GetAllWarehouses()) ////// model.AvailableWarehouses.Add(new SelectListItem { Text = wh.Name, Value = wh.Id.ToString() }); ////// //product types ////// //NJM: Note ToSelectList is an extension method in Nop.Web.Framework ////// model.AvailableProductTypes = ProductType.SimpleProduct.ToSelectList(false).ToList(); ////// model.AvailableProductTypes.Insert(0, new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// //"published" property ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.All"), Value = "0" }); ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.PublishedOnly"), Value = "1" }); ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.UnpublishedOnly"), Value = "2" }); ////// return View("~/Views/AUConsignor/ManageLots.cshtml", model); ////// //return View("List.cshtml", model); //////} //////[HttpPost, ActionName("ListLots")] //////[FormValueRequired("go-to-product-by-sku")] //////public ActionResult GoToSku(AULotList model) //////{ ////// throw new NotImplementedException(); //need way to edit lot ////// //Console.Write("hit the button"); ////// //return new NullJsonResult(); //////} //////[HttpPost, ActionName("ListLots")] //////[FormValueRequired("exportexcel-all")] //////public ActionResult ExportExcelAll(AULotList model) //////{ ////// //throw new NotImplementedException("exportexcel-all button not implemented yet"); //need way to edit lot ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// ////a vendor should have access only to his products ////// //if (_workContext.CurrentVendor != null) ////// //{ ////// // model.SearchVendorId = _workContext.CurrentVendor.Id; ////// //} ////// var categoryIds = new List<int> { model.SearchCategoryId }; ////// //include subcategories ////// if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0) ////// categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId)); ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// bool? overridePublished = null; ////// if (model.SearchPublishedId == 1) ////// overridePublished = true; ////// else if (model.SearchPublishedId == 2) ////// overridePublished = false; ////// //var products = _productService.SearchProducts( ////// // categoryIds: categoryIds, ////// // manufacturerId: model.SearchManufacturerId, ////// // storeId: model.SearchStoreId, ////// // vendorId: model.SearchVendorId, ////// // warehouseId: model.SearchWarehouseId, ////// // productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, ////// // keywords: model.SearchProductName, ////// // showHidden: true, ////// // overridePublished: overridePublished ////// //); ////// var products = _consignorService.GetAllLots( ////// categoryIds: categoryIds, ////// saleId: model.SearchSaleId, ////// storeId: model.SearchStoreId, ////// warehouseId: model.SearchWarehouseId, ////// productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, ////// keywords: model.SearchProductName, ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize, ////// showHidden: true, ////// overridePublished: overridePublished ////// ); ////// try ////// { ////// byte[] bytes; ////// using (var stream = new MemoryStream()) ////// { ////// //_exportManager.ExportProductsToXlsx(stream, products); ////// _collectibleexportService.ExportPhilatelicProductsToXlsx(stream, products); ////// bytes = stream.ToArray(); ////// } ////// return File(bytes, "text/xls", "products.xlsx"); ////// } ////// catch (Exception exc) ////// { ////// ErrorNotification(exc); ////// return RedirectToAction("ListLots"); ////// } //////} //////[HttpPost] //////public ActionResult ExportExcelSelected(string selectedIds) //////{ ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// var products = new List<AUCombLotProc>(); ////// if (selectedIds != null) ////// { ////// var ids = selectedIds ////// .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) ////// .Select(x => Convert.ToInt32(x)) ////// .ToArray(); ////// products.AddRange(_consignorService.GetAllLots(productIds: ids)); ////// } ////// //a vendor should have access only to his products ////// if (_workContext.CurrentVendor != null) ////// { ////// products = products.Where(p => p.VendorId == _workContext.CurrentVendor.Id).ToList(); ////// } ////// byte[] bytes = null; ////// using (var stream = new MemoryStream()) ////// { ////// //_exportManager.ExportProductsToXlsx(stream, products); ////// _collectibleexportService.ExportPhilatelicProductsToXlsx(stream, products); ////// bytes = stream.ToArray(); ////// } ////// return File(bytes, "text/xls", "products.xlsx"); //////} //////[HttpPost, ActionName("ListLots")] //////[FormValueRequired("download-catalog-pdf")] //////public ActionResult DownloadCatalogAsPdf(AULotList model) //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// //return AccessDeniedView(); ////// ////a vendor should have access only to his products ////// //if (_workContext.CurrentVendor != null) ////// //{ ////// // model.SearchVendorId = _workContext.CurrentVendor.Id; ////// //} ////// var categoryIds = new List<int> { model.SearchCategoryId }; ////// //include subcategories ////// if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0) ////// categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId)); ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// bool? overridePublished = null; ////// if (model.SearchPublishedId == 1) ////// overridePublished = true; ////// else if (model.SearchPublishedId == 2) ////// overridePublished = false; ////// //this will not conside exclude sale, as it general use for Manage Lots ////// var products = _consignorService.GetAllLots( ////// categoryIds: categoryIds, ////// saleId: model.SearchSaleId, ////// storeId: model.SearchStoreId, ////// warehouseId: model.SearchWarehouseId, ////// productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, ////// keywords: model.SearchProductName, ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize, ////// showHidden: true, ////// overridePublished: overridePublished ////// ); ////// try ////// { ////// byte[] bytes; ////// using (var stream = new MemoryStream()) ////// { ////// _philatelicpdfService.PrintProductsToPdf(stream, products); ////// bytes = stream.ToArray(); ////// } ////// return File(bytes, "application/pdf", "pdfcatalog.pdf"); ////// } ////// catch (Exception exc) ////// { ////// ErrorNotification(exc); ////// return RedirectToAction("ListLots"); ////// } //////} //////[HttpPost] //////public ActionResult LotList(DataSourceRequest command, AULotList model) //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// //TODO: add in vendor logic for consignors to see their lots. See C:\Users\Nicholas\Documents\My Documents\NopCommerce\Presentation\Nop.Web\Administration\Controllers\ProductController.cs ProductList() ////// var categoryIds = new List<int> { model.SearchCategoryId }; ////// //include subcategories ////// if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0) ////// categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId)); ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// bool? overridePublished = null; ////// if (model.SearchPublishedId == 1) ////// overridePublished = true; ////// else if (model.SearchPublishedId == 2) ////// overridePublished = false; ////// //this will not conside exclude sale, as it general use for Manage Lots ////// var lots = _consignorService.GetAllLots( ////// categoryIds: categoryIds, ////// saleId: model.SearchSaleId, ////// storeId: model.SearchStoreId, ////// warehouseId: model.SearchWarehouseId, ////// productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, ////// keywords: model.SearchProductName, ////// pageIndex: command.Page - 1, ////// pageSize: command.PageSize, ////// showHidden: true, ////// overridePublished: overridePublished ////// ); ////// //int productid = 0; ////// //string firstname = "Test"; ////// //string lastname = ""; ////// //int productId = model.searchProductID; ////// //string searchname = model.searchName; ////// //%%%%%%%%%%%start cleaning here ////// //var lots = _consignorService.GetAllLots( ////// // //productId: productId, ////// // //searchname: searchname, ////// // pageIndex: 0, ////// // pageSize: 500); ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize); ////// //TODO: THIS WILL NEED TO BE CHANGED WHEN YOU IMPLEMENT MORE THAN ONE CONSIGNOR PER CONSIGNMENT ////// //%%%%%%%%%%lots is food - something wrong with the view ////// //var gridModel = new DataSourceResult ////// //{ ////// // Data = lots.Select(x => new ////// // { ////// // Id = x.Id, ////// // ProductID = x.ProductID, ////// // Name = x.Name, ////// // ShortDescription = x.ShortDescription, ////// // LotNbr = x.LotNbr, ////// // AUSaleID = x.AUSaleID, ////// // AUSaleNbr = x.AUSaleNbr, ////// // SaleTitle = x.SaleTitle ////// // }), ////// // Total = lots.TotalCount ////// //}; ////// var gridModel = new DataSourceResult(); ////// gridModel.Data = lots.Select(x => ////// { ////// var lotsModel = x.ToModel(); //ToModel uses EF mapper and is implemented as an Extension. Map definition is in Infrastructure\AutomapperStartupTask ////// lotsModel.Id = x.Id; ////// lotsModel.ProductID = x.ProductID; ////// lotsModel.AULotID = x.AULotID; ////// lotsModel.Name = x.Name; ////// lotsModel.ShortDescription = x.ShortDescription; ////// lotsModel.SKU = x.SKU; ////// lotsModel.LotNbr = x.LotNbr; ////// lotsModel.IsLotSold = x.IsLotSold; ////// lotsModel.AUSaleID = x.AUSaleID; ////// lotsModel.SaleIsActive = x.SaleIsActive; ////// lotsModel.AUSaleNbr = x.AUSaleNbr; ////// lotsModel.SaleTitle = x.SaleTitle; ////// //little hack here: ////// //ensure that product full descriptions are not returned ////// //otherwise, we can get the following error if products have too long descriptions: ////// //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. " ////// //also it improves performance ////// //-->productModel.FullDescription = ""; ////// //picture ////// var defaultProductPicture = _pictureService.GetPicturesByProductId(x.ProductID, 1).FirstOrDefault(); ////// lotsModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true); ////// //product type ////// //productModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext); ////// //friendly stock qantity ////// //if a simple product AND "manage inventory" is "Track inventory", then display ////// //if (x.ProductType == ProductType.SimpleProduct && x.ManageInventoryMethod == ManageInventoryMethod.ManageStock) ////// // productModel.StockQuantityStr = x.GetTotalStockQuantity().ToString(); ////// return lotsModel; ////// }); ////// gridModel.Total = lots.TotalCount; ////// return Json(gridModel); //////} //////[HttpPost] //////public ActionResult ListSaleLots(DataSourceRequest command, AULotList model,int excludeSaleId, bool excludeSale) //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// //bool? overridePublished = false; //show published and unpublished lots associated to the sale the sale ////// //should not happen ////// if (model.SearchSaleId == 0 && excludeSaleId != 0 && excludeSale == false ) ////// { ////// model.SearchSaleId = excludeSaleId; ////// } ////// //TODO: only show lots in the store ////// var lots = _consignorService.GetAllLots( ////// saleId: model.SearchSaleId, ////// pageIndex: command.Page - 1, ////// pageSize: command.PageSize, ////// showHidden: true, ////// excludeSale: excludeSale, ////// excludeSaleId: excludeSaleId ////// ); ////// //overridePublished: overridePublished, ////// //var lots = _consignorService.GetAllLots( ////// // categoryIds: categoryIds, ////// // saleId: model.SearchSaleId, ////// // storeId: model.SearchStoreId, ////// // warehouseId: model.SearchWarehouseId, ////// // productType: model.SearchProductTypeId > 0 ? (AUProductType?)model.SearchProductTypeId : null, ////// // keywords: model.SearchProductName, ////// // pageIndex: command.Page - 1, ////// // pageSize: command.PageSize, ////// // showHidden: true, ////// // overridePublished: overridePublished ////// //); ////// var gridModel = new DataSourceResult(); ////// gridModel.Data = lots.Select(x => ////// { ////// var lotsModel = x.ToModel(); //ToModel uses EF mapper and is implemented as an Extension. Map definition is in Infrastructure\AutomapperStartupTask ////// lotsModel.Id = x.Id; ////// lotsModel.ProductID = x.ProductID; ////// lotsModel.AULotID = x.AULotID; ////// lotsModel.Name = x.Name; ////// lotsModel.ShortDescription = x.ShortDescription; ////// lotsModel.SKU = x.SKU; ////// lotsModel.LotNbr = x.LotNbr; ////// lotsModel.IsLotSold = x.IsLotSold; ////// lotsModel.AUSaleID = x.AUSaleID; ////// lotsModel.AUSaleNbr = x.AUSaleNbr; ////// lotsModel.SaleTitle = x.SaleTitle; ////// //little hack here: ////// //ensure that product full descriptions are not returned ////// //otherwise, we can get the following error if products have too long descriptions: ////// //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. " ////// //also it improves performance ////// //-->productModel.FullDescription = ""; ////// //picture ////// var defaultProductPicture = _pictureService.GetPicturesByProductId(x.ProductID, 1).FirstOrDefault(); ////// lotsModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true); ////// //product type ////// //productModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext); ////// //friendly stock qantity ////// //if a simple product AND "manage inventory" is "Track inventory", then display ////// //if (x.ProductType == ProductType.SimpleProduct && x.ManageInventoryMethod == ManageInventoryMethod.ManageStock) ////// // productModel.StockQuantityStr = x.GetTotalStockQuantity().ToString(); ////// return lotsModel; ////// }); ////// gridModel.Total = lots.TotalCount; ////// return Json(gridModel); //////} //////public ActionResult SaleProductAddPopup(int saleId) //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// var model = new AULotList(); //using same search model as ManageLots ////// //a vendor should have access only to his products. Set the indicator in the model ////// model.IsLoggedInAsVendor = _workContext.CurrentVendor != null; ////// model.SaleId = saleId; ////// //categories ////// model.AvailableCategories.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// var categories = _categoryService.GetAllCategories(showHidden: true); ////// foreach (var c in categories) ////// model.AvailableCategories.Add(new SelectListItem { Text = c.GetFormattedBreadCrumb(categories), Value = c.Id.ToString() }); ////// //NJM: Sales ////// model.AvailableSales.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// var sales = _consignorService.GetAllSales( ////// saleId: saleId, ////// saleNbr: null, ////// saleTitle: null, ////// excludeSale: true, ////// pageIndex: 0, ////// pageSize: 2147483647); ////// foreach (var c in sales) ////// model.AvailableSales.Add(new SelectListItem { Text = c.AUSaleNbr, Value = c.AUSaleID.ToString() }); ////// //stores ////// model.AvailableStores.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// foreach (var s in _storeService.GetAllStores()) ////// model.AvailableStores.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); ////// //warehouses ////// model.AvailableWarehouses.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// foreach (var wh in _shippingService.GetAllWarehouses()) ////// model.AvailableWarehouses.Add(new SelectListItem { Text = wh.Name, Value = wh.Id.ToString() }); ////// //product types ////// //NJM: Note ToSelectList is an extension method in Nop.Web.Framework ////// model.AvailableProductTypes = ProductType.SimpleProduct.ToSelectList(false).ToList(); ////// model.AvailableProductTypes.Insert(0, new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// //"published" property ////// //0 - all (according to "ShowHidden" parameter) ////// //1 - published only ////// //2 - unpublished only ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.All"), Value = "0" }); ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.PublishedOnly"), Value = "1" }); ////// model.AvailablePublishedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Catalog.Products.List.SearchPublished.UnpublishedOnly"), Value = "2" }); ////// return View("~/Views/AUConsignor/ManageSaleLotsPopup.cshtml", model); //////} ////// /// <summary> ////// /// WARNING - THIS CODE IS CURRENTLY NOT EXECUTED AS WE DO NOT ALLOW "ORPHAN" CONSIGNOR RECORDS. TODO: REMOVE THIS IF FULL TESTING REVEALS NOT NEEDED - ////// /// CURRENTLY FAILING BECAUSE MODEL IS SHOWN TO BE INVALID WHEN NON-ZERO VALIDATION (ANNOTATION) HIT FOR AUCONSIGNORRECORD ////// /// </summary> ////// /// <param name="consignorId"></param> ////// /// <returns></returns> //////// [HttpPost] ////// public ActionResult ConsignorCustomerDisassociate(int consignorId) ////// { ////// //TODO: Implement permissions ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// var consignor = _consignorService.GetConsignorById(consignorId); ////// if (consignor == null) ////// { ////// ErrorNotification("A major error occurred -consignor id sent to ConsignorCustomerDisassociate null. Please contact System Support"); ////// return RedirectToAction("ManageConsignors"); ////// } ////// consignor.CustomerID = 0; ////// _consignorRepo.Update(consignor); ////// //_cacheManager.Clear(); ////// SuccessNotification("Consignor disassociated from customer! Please associate to another customer asap"); ////// return View("~/Views/AUConsignor/CreateUpdateConsignor.cshtml", consignor); //not hit first time?? ////// } //////public ActionResult ConsignorCustomerSelectPopup(int consignorId) //////{ ////// //TODO: Permissions to associate Customer to Consignor ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// var model = new AUCustomerList(); //using same search model as ManageLots ////// //TODO: a vendor should not be able to see the consignor info or set the customer. Add and Set the indicator in the model ////// model.IsLoggedInAsVendor = _workContext.CurrentVendor != null; ////// //TODO: POPULATE WITH PHONEENABLED, ////// model.PhoneEnabled = true; ////// model.ZipPostalCodeEnabled = true; ////// model.CompanyEnabled = true; ////// model.AUConsignorId = consignorId; ////// return View("~/Views/AUConsignor/ConsignorCustomerSelectPopup.cshtml", model); //////} //////[HttpPost] //////public ActionResult ConsignorCustomerSelectPopup(string selectedIds, int consignorId, string btnIdToRefresh, string frmIdToRefresh, AUCustomerList model) //////{ ////// //TODO: Implement permissions ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// var consignor = _consignorService.GetConsignorById(consignorId); ////// if (consignor == null || selectedIds == null) ////// { ////// ErrorNotification("A major error occurred -consignor id or selected ids from ConsignorCustomerSelectPopup null. Please contact System Support"); ////// return RedirectToAction("ManageConsignors"); ////// } ////// //TODO: Finish this - Need to get the lot info to ensure not already sold and unpublished ////// var ids = selectedIds ////// .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) ////// .Select(x => Convert.ToInt32(x)) ////// .ToArray(); ////// var customer = _consignorService.GetCustomerById(ids[0]); ////// if (customer == null) ////// { ////// ErrorNotification("A major error occurred - customer not found using vendor id from ConsignorCustomerSelectPopup null. Please contact System Support"); ////// return RedirectToAction("ManageConsignors"); ////// } ////// consignor.CustomerID = customer.Id; ////// _consignorRepo.Update(consignor); ////// SuccessNotification("Customer associated to Consignor!!"); //seems to be nop admin convention ////// ViewBag.RefreshPage = true; ////// ViewBag.btnId = btnIdToRefresh; ////// ViewBag.formId = frmIdToRefresh; ////// return View("~/Views/AUConsignor/ConsignorCustomerSelectPopup.cshtml", model); ////// //return RedirectToAction("ListLots"); //TODO FIX THIS //////} ////////Popup the sale selection popup window to copy increments from //////public ActionResult SaleIncrementCopyPopup(int saleId) //////{ ////// if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// return View("~/Administration/Views/Security/AccessDenied.cshtml"); ////// var model = new AUSaleList(); //using same search model as ManageSales ////// //a vendor should have access only to his products. Set the indicator in the model ////// //model.IsLoggedInAsVendor = _workContext.CurrentVendor != null; ////// model.SaleId = saleId; ////// //Populate Sales ////// //don't allow select all model.AvailableSales.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); ////// var sales = _consignorService.GetAllSales( ////// saleId: saleId, ////// saleNbr: null, ////// saleTitle: null, ////// excludeSale: true, ////// pageIndex: 0, ////// pageSize: 2147483647); ////// foreach (var c in sales) ////// model.AvailableSales.Add(new SelectListItem { Text = c.SaleTitle, Value = c.AUSaleID.ToString() }); ////// return View("~/Views/AUConsignor/SaleIncrementCopyPopup.cshtml", model); //////} //////[HttpPost] //////public ActionResult SaleProductAddPopup(string selectedIds, int saleId, string btnIdToRefresh, string frmIdToRefresh, AULotList model) //////{ ////// //TODO: Implement permissions ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// var sale = _consignorService.GetSaleById(saleId); ////// if (sale == null) ////// { ////// ErrorNotification("A major error occurred -sale id from SaleProductAddPopup not found. Please contact System Support"); ////// return RedirectToAction("ManageSales"); ////// } ////// //TODO: Finish this - Need to get the lot info to ensure not already sold and unpublished ////// var lots = new List<AULotRecord>(); ////// if (selectedIds != null) ////// { ////// lots.AddRange(_consignorService.GetLotsByPids(selectedIds)); ////// } ////// foreach (var l in lots) ////// { ////// var sl = l.AUSaleRecords.FirstOrDefault(x => x.AUSaleID == sale.AUSaleID); ////// if (sl == null) //Sale exists but the junction AUSaleLot record doesn't ////// { ////// var saleLot = new AUSaleLotRecord ////// { ////// AUSaleID = sale.AUSaleID, ////// AULotID = l.AULotID, ////// LotNbr = 0, ////// SaleIsActive = sale.SaleIsActive, //pull this indicator from the Sale record - don't load from spreadsheet ////// DisplayOrder = 0 ////// }; ////// _consignorService.InsertSaleLot(saleLot); ////// } ////// //else //Sale exists and the junction AUSaleLot record does as well, so update it ////// //{ ////// // sl.AUSaleID = sale.AUSaleID; ////// // sl.AULotID = lot.AULotID; ////// // sl.LotNbr = LotNbr; ////// // sl.SaleIsActive = sale.SaleIsActive; ////// // sl.DisplayOrder = DisplayOrder; ////// // _consignorService.UpdateSaleLot(sl); ////// //} ////// } ////// ////a vendor should have access only to his products ////// //if (_workContext.CurrentVendor != null) ////// //{ ////// // products = products.Where(p => p.VendorId == _workContext.CurrentVendor.Id).ToList(); ////// //} ////// //_consignorService.PublishSelectedProducts(products); ////// SuccessNotification("Lots were associated to sale!!"); //seems to be nop admin convention ////// ViewBag.RefreshPage = true; ////// ViewBag.btnId = btnIdToRefresh; ////// ViewBag.formId = frmIdToRefresh; ////// return View("~/Views/AUConsignor/ManageSaleLotsPopup.cshtml", model); ////// //return RedirectToAction("ListLots"); //TODO FIX THIS //////} //////[HttpPost] //////public ActionResult CopySaleIncementsToSale(int selectedSaleId, int saleId, string btnIdToRefresh, string frmIdToRefresh, AUSaleList model) //////{ ////// //TODO: Implement permissions ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// var salefrom = _consignorService.GetSaleById(selectedSaleId); ////// if (salefrom == null) ////// { ////// ErrorNotification("A major error occurred -sale from id from CopySaleIncementsToSale popup not found. Please contact System Support"); ////// return RedirectToAction("ManageSales"); //TODO FIX THIS to alert majorerror ////// } ////// var saleto = _consignorService.GetSaleById(saleId); //TODO: why using service to get this record. ////// if (saleto == null) ////// { ////// ErrorNotification("A major error occurred -saleto id from CopySaleIncementsToSale popup not found. Please contact System Support"); ////// return RedirectToAction("ManageSales"); //TODO FIX THIS to alert majorerror ////// } ////// //changed so not walking the sale ////// var increments = saleto.AUIncrementRecords; ////// // consignor = _consignorRepo.GetById(ConsignorId); ////// //doesn't work - eats itself so second iteration fails ////// //foreach (var i in increments) ////// //{ ////// // var inc = _incrementRepo.GetById(i.AUIncrementID); ////// // _incrementRepo.Delete(inc); ////// //} ////// while (1 == 1) ////// { ////// var inc = increments.FirstOrDefault(); ////// if (inc != null) ////// { ////// _incrementRepo.Delete(inc); //these hit db right away ////// } ////// else ////// { ////// break; ////// } ////// } ////// //saleto.AUIncrementRecords.Clear(); ////// //_saleRepo.Update(saleto); ////// foreach (var incf in salefrom.AUIncrementRecords) ////// { ////// var newinc = new AUIncrementRecord(); ////// var sale = _saleRepo.GetById(saleto.AUSaleID); ////// newinc.AUSaleID = saleto.AUSaleID; //change forein key to new sale; ////// newinc.CreatedBy = "Test created by"; ////// //newinc.createdon ////// newinc.FromBidAmt = incf.FromBidAmt; ////// newinc.ToBidAmt = incf.ToBidAmt; ////// newinc.IncrementAmt = incf.IncrementAmt; ////// newinc.CreatedBy = "Test"; ////// newinc.UpdatedBy = "Test"; ////// newinc.CreatedOnDT = System.DateTime.UtcNow; ////// newinc.UpdatedOnDT = System.DateTime.UtcNow; ////// saleto.AUIncrementRecords.Add(newinc); ////// // saleto.AUIncrementRecords.Add(newinc); ////// // _saleRepo.Update(saleto); ////// // _incrementRepo.Insert(newinc); No Work - not null key??? ////// } ////// _saleRepo.Update(saleto); //record add above does not hit db until this ////// ////a vendor should have access only to his products ////// //if (_workContext.CurrentVendor != null) ////// //{ ////// // products = products.Where(p => p.VendorId == _workContext.CurrentVendor.Id).ToList(); ////// //} ////// //_consignorService.PublishSelectedProducts(products); ////// SuccessNotification("Increments were associated to sale!!"); //seems to be nop admin convention ////// ViewBag.RefreshPage = true; ////// ViewBag.btnId = btnIdToRefresh; //button to click (btnRefreshIncrements) ////// ViewBag.formId = frmIdToRefresh; //form to open (sale-form) ////// return View("~/Views/AUConsignor/SaleIncrementCopyPopup.cshtml", model); ////// //return RedirectToAction("ListLots"); //TODO FIX THIS //////} ////////[HttpPost] grid is not posting ////////the grid passes in fields in the row schema as well as the form model ////////the grid schema can containmore fields than are displayed in the columns ////////AULotID comes from the schema ////////AUSaleID comes from the model //////public ActionResult RemoveLotFromSale(int AULotID, AUSaleRecord model) //////{ ////// //TODO: AUTHORIZE ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) ////// // return AccessDeniedView(); ////// _consignorService.DeleteSaleLotByLotId(AULotID, model.AUSaleID); ////// //if (productCategory == null) ////// // throw new ArgumentException("No product category mapping found with the specified id"); ////// ////var categoryId = productCategory.CategoryId; ////// //_categoryService.DeleteProductCategory(productCategory); ////// return new NullJsonResult(); //////} //////public ActionResult DeleteFees(string btnIdToRefresh, string frmIdToRefresh, AUFeesRecord model) //////{ ////// //TODO: AUTHORIZE ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) ////// // return AccessDeniedView(); ////// var fee = _feesRepo.GetById(model.AUFeesID); ////// if (fee != null) //should not happen once you start hiding the inherit button on an inherited fee ////// { ////// _feesRepo.Delete(fee); ////// ViewBag.RefreshPage = true; ////// ViewBag.btnId = btnIdToRefresh; ////// ViewBag.formId = frmIdToRefresh; ////// } ////// return new NullJsonResult(); //////} //////public ActionResult InheritFees(AUFeesRecord model) //////{ ////// //TODO: AUTHORIZE ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) ////// // return AccessDeniedView(); ////// var fee = _feesRepo.GetById(model.AUFeesID); ////// _feesRepo.Delete(fee); ////// return new NullJsonResult(); //////} //////[HttpPost] //////public ActionResult CreateUpdateFees(AUFeesRecord model) //////{ ////// //TODO: Implement permissions across all actions ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) ////// // return AccessDeniedView(); ////// //var productCategory = _categoryService.GetProductCategoryById(model.Id); ////// //if (productCategory == null) ////// // throw new ArgumentException("No product category mapping found with the specified id"); ////// string feetype = ""; ////// var fee = new AUFeesRecord(); ////// if (model.AUFeesID > 0) ////// { ////// fee = _feesRepo.GetById(model.AUFeesID); //TODO: push into service ////// } ////// else ////// { ////// //Make sure you don't carry the Inherited indicator (I) into the database ////// feetype = model.AUEntityType; ////// if (model.AUEntityType == "AUConsignment(I)") ////// { ////// feetype = "AUConsignment"; ////// } ////// else if (model.AUEntityType == "AULot(I)") ////// { ////// feetype = "AULot"; ////// } ////// fee.AUEntityType = feetype; ////// fee.AUEntityID = model.AUEntityID; ////// //Hack - force in the Order here for displaying ////// if (feetype == "AUConsignor") ////// { ////// fee.DisplayOrder = 0; ////// } ////// else if (feetype == "AUConsignment") ////// { ////// fee.DisplayOrder = 2; ////// } ////// else if (feetype == "AULot") ////// { ////// fee.DisplayOrder = 3; ////// } ////// } ////// fee.CommissionCanExceedReserveInd = model.CommissionCanExceedReserveInd; ////// fee.ExpertisingFeeAmt = model.ExpertisingFeeAmt; ////// fee.FixedFeeAmt = model.FixedFeeAmt; ////// fee.InsuranceSoldPct = model.InsuranceSoldPct; ////// fee.InsuranceUnsoldPct = model.InsuranceUnsoldPct; ////// fee.InterestOnAdvancePct = model.InterestOnAdvancePct; ////// fee.MinCommissionMailSoldAmt = model.MinCommissionMailSoldAmt; ////// fee.MinCommissionMailUnsoldAmt = model.MinCommissionMailUnsoldAmt; ////// fee.MinCommissionPublicSoldAmt = model.MinCommissionPublicSoldAmt; ////// fee.MinCommissionPublicUnsoldAmt = model.MinCommissionPublicUnsoldAmt; ////// fee.MinimumConsignorTotalFeeAmt = model.MinimumConsignorTotalFeeAmt; ////// fee.MiscFeeAmt = model.MiscFeeAmt; ////// fee.SoldPct = model.SoldPct; ////// fee.UnsoldPct = model.UnsoldPct; ////// if (model.AUFeesID > 0) ////// { ////// _feesRepo.Update(fee); //TODO: push into service ////// } ////// else ////// { ////// _feesRepo.Insert(fee); ////// } ////// return new NullJsonResult(); //////} //////// [HttpPost] grid is not posting so signature can't be post ////////form passes fields in the grid row schema as well as the form model ////////the grid schema can contain more fields than are displayed in the columns ////////AULotID comes from the schema ////////AUSaleID comes from the model //////public ActionResult DeleteSaleIncrement(int AUIncrementID) //////{ ////// //TODO: AUTHORIZE ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) ////// // return AccessDeniedView(); ////// _consignorService.DeleteIncrementById(AUIncrementID); ////// //if (productCategory == null) ////// // throw new ArgumentException("No product category mapping found with the specified id"); ////// ////var categoryId = productCategory.CategoryId; ////// //_categoryService.DeleteProductCategory(productCategory); ////// return new NullJsonResult(); //////} //////public ActionResult UpdateSaleIncrement(AUIncrementRecord increment) //////{ ////// //TODO: AUTHORIZE ////// //if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) ////// // return AccessDeniedView(); ////// _incrementRepo.Update(increment); ////// return new NullJsonResult(); //////} //////public ActionResult ManageConsignors() //////{ ////// //%%%%%%%%%%%%%%%%%%% ////// //var listModel = new AUConsignorList ////// //{ ////// // //UsernamesEnabled = _customerSettings.UsernamesEnabled, ////// // //DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled, ////// // //CompanyEnabled = _customerSettings.CompanyEnabled, ////// // //PhoneEnabled = _customerSettings.PhoneEnabled, ////// // //ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled, ////// // //AvailableCustomerRoles = _customerService.GetAllCustomerRoles(true).Select(cr => cr.ToModel()).ToList(), ////// // //SearchCustomerRoleIds = defaultRoleIds, ////// //}; ////// //return View(listModel); ////// //return View(); ////// return View("~/Views/AUConsignor/ManageConsignors.cshtml"); //not hit first time?? //////} //public ActionResult CustomerList(DataSourceRequest command, CustomerListModel model, // [ModelBinder(typeof(CommaSeparatedModelBinder))] int[] searchCustomerRoleIds) //////[HttpPost] ////////************************************************************************************************************************************* //////// you had to pass in AUConsignorList model and populate it with the additionaldata function //////// in the cshtml to get the entered search data. ToTest: do you need DataSourceRequest?? Note, when just doing a total list, //////// you didn;t need to pass in anything //////public ActionResult ListConsignors(DataSourceRequest command, AUConsignorList model) //////{ ////// //********************************Original*******See Consignments for M-M ********************************************************* ////// //var consignors = _consignorRepo.Table.ToList(); ////// //var gridModel = new DataSourceResult ////// //{ ////// // Data = consignors.Select(x => new ////// // { ////// // AUConsignorID = x.AUConsignorID, ////// // FirstName = x.FirstName, ////// // MiddleName = x.MiddleName, ////// // LastName = x.LastName, ////// // CreateDate = x.CreateDate, ////// // BuyerFee = x.BuyerFee, ////// // SellerFee = x.SellerFee, ////// // }), ////// // Total = consignors.Count() ////// //}; ////// //*****************************Original******************************************************************* ////// int consignorid = 0; ////// string email = ""; ////// //string firstname = "Test"; ////// string lastname = ""; ////// string fn = model.searchFirstName; ////// var consignors = _consignorService.GetAllConsignors( ////// consignorId: consignorid, ////// WEmail: email, ////// firstName: model.searchFirstName, ////// lastName: lastname, ////// pageIndex: 0, ////// pageSize: 500); ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize); ////// var gridModel = new DataSourceResult ////// { ////// Data = consignors.Select(x => new ////// { ////// Id = x.Id, ////// AUConsignorID = x.AUConsignorID, ////// CustomerID = x.CustomerID, ////// FirstName = x.FirstName, ////// MiddleName = x.MiddleName, ////// LastName = x.LastName ////// }), ////// Total = consignors.TotalCount ////// }; ////// return Json(gridModel); //////} //////public ActionResult ManageSales() //////{ ////// //return View(); ////// return View("~/Views/AUConsignor/ManageSales.cshtml"); //not hit first time?? //////} //////public ActionResult ListSales(DataSourceRequest command, AUSaleList model) //////{ ////// var sales = _consignorService.GetAllSales( ////// saleId: model.searchAUSaleID, ////// saleNbr: model.searchSaleNbr, ////// saleTitle: model.searchSaleTitle, ////// pageIndex: 0, ////// pageSize: 500); ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize); ////// var gridModel = new DataSourceResult ////// { ////// Data = sales.Select(x => new ////// { ////// AUSaleID = x.AUSaleID, ////// SaleStoreID = x.SaleStoreID, ////// AUSaleNbr = x.AUSaleNbr, ////// SaleTitle = x.SaleTitle, ////// SaleDesc = x.SaleDesc, ////// // SaleStartDateTime = x.SaleStartDateTime, ////// // SaleEndDateTime = x.SaleEndDateTime, ////// SaleStartDateTime = _dateTimeHelper.ConvertToUserTime(x.SaleStartDateTime, DateTimeKind.Local), ////// SaleEndDateTime = _dateTimeHelper.ConvertToUserTime(x.SaleEndDateTime, DateTimeKind.Local), ////// }), ////// Total = sales.TotalCount ////// }; ////// return Json(gridModel); //////} //////public ActionResult ListUnassignedConsignors(DataSourceRequest command, AUCustomerList model) //////{ ////// int roleId = _consignorService.GetIdForRole("Consignors"); ////// int[] roleIds = new int[1]; ////// //Note: roleId may be 0 if Role was not found ////// roleIds[0] = roleId; ////// var vendors = _consignorService.GetUnassignedConsignorCustomers( ////// vendorId: model.SearchVendorId, ////// customerRoleIds: roleIds, ////// email: model.SearchEmail, ////// username: model.SearchUsername, ////// firstName: model.SearchFirstName, ////// lastName: model.SearchLastName, ////// company: model.SearchCompany, ////// phone: model.SearchPhone, ////// zipPostalCode: model.SearchZipPostalCode, ////// pageIndex: 0, ////// pageSize: 500); ////// //pageIndex: command.Page - 1, ////// //pageSize: command.PageSize); ////// //TODO: Add address, phone info to this result set (use nav property = select home address) ////// var gridModel = new DataSourceResult ////// { ////// Data = vendors.Select(x => new ////// { ////// Id = x.Id, ////// VendorId = x.VendorId, ////// CustomerGuid = x.CustomerGuid, ////// Firstname = (x.Addresses.Count() != 0) ? x.Addresses.First().FirstName : "No Address", ////// Lastname = (x.Addresses.Count() != 0) ? x.Addresses.First().LastName : "No Address", ////// Address1 = (x.Addresses.Count() != 0) ? x.Addresses.First().Address1 : "No Address", ////// Address2 = (x.Addresses.Count() != 0) ? x.Addresses.First().Address2 : "No Address", ////// City = (x.Addresses.Count() != 0) ? x.Addresses.First().City : "No Address", ////// ZipPostalCode = (x.Addresses.Count() != 0) ? x.Addresses.First().ZipPostalCode : "No Address", ////// Username = x.Username, ////// Company = (x.Addresses.Count() != 0) ? x.Addresses.First().Company : "No Address", ////// Phone = (x.Addresses.Count() != 0) ? x.Addresses.First().PhoneNumber : "No Address", ////// Email = x.Email, ////// AdminComment = x.AdminComment, ////// HasShoppingCartItems = x.HasShoppingCartItems, ////// Active = x.Active, ////// CreatedOnUtc = x.CreatedOnUtc, ////// LastLoginDateUtc = x.LastLoginDateUtc, ////// LastActivityDateUtc = x.LastActivityDateUtc ////// }), ////// Total = vendors.TotalCount ////// }; ////// return Json(gridModel); //////} //TODO: what is this DECORATION from Web CatalogController.cs // [NopHttpsRequirement(SslRequirement.No)] //WARNING!!! This is for the search page breadcrumb only! //TODO: what is this DECORATION from Web CatalogController.cs // [NopHttpsRequirement(SslRequirement.No)] public ActionResult Category(int categoryId, int? saleId, string children, string allChildren, CatalogPagingFilteringModel command) { int inSaleId = saleId.GetValueOrDefault(); //NJM: make it 0 if it's null. will be null coming off the Catalog breadcrumb bool manageCategoriesBySale = true; //TODO: placeholder to determine type of store and if manage categories by sale var category = new Category(); if (categoryId != 0) //NJM: may pass as zero if trying to present category page for sale only- off sale navigator or sale breadcrumb { category = _categoryService.GetCategoryById(categoryId); if (category == null || category.Deleted) return InvokeHttp404(); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a category before publishing if (!category.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) return InvokeHttp404(); //ACL (access control list) if (!_aclService.Authorize(category)) return InvokeHttp404(); //Store mapping if (!_storeMappingService.Authorize(category)) return InvokeHttp404(); } else { //NJM: TODO Stuff page info for now until you add to AUSale (like Category) category.AllowCustomersToSelectPageSize = true; category.PageSizeOptions = "6,3,9"; category.PageSize = 6; } //TODO: come back to this to save the last page to continue shopping ////////'Continue shopping' URL //////_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, ////// SystemCustomerAttributeNames.LastContinueShoppingPage, ////// _webHelper.GetThisPageUrl(false), ////// _storeContext.CurrentStore.Id); var model = category.ToAUModel(); //NJM: this maps Category to AUCategory but does not populate nested classes if (inSaleId != 0) //NJM: coming off sale navigator or breadcrumb, so get the sale title { var sale = _saleRepo.GetById(inSaleId); if (sale == null) { throw new NopException("SaleId not found for category " + saleId); } model.SaleId = inSaleId; //this is needed to allow hyperlink to specify sale constraint model.SaleTitle = sale.SaleTitle; //this is needed for the breadcrumb } //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, category.AllowCustomersToSelectPageSize, category.PageSizeOptions, category.PageSize); //price ranges //TODO: insert *estimate* in here for filtering? model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, category.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //******************************************************************************************************************* //* The category breadcrumb s/b ok because it looks at the hierarchy above the current node, which is stable //* regardless if a lot is associated //************************************************************************************************************** //category breadcrumb if (_catalogSettings.CategoryBreadcrumbEnabled) { model.DisplayCategoryBreadcrumb = true; string breadcrumbCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_BREADCRUMB_KEY, categoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id); //%%%get the breadcrumb here model.CategoryBreadcrumb = _cacheManager.Get(breadcrumbCacheKey, () => category .GetCategoryBreadCrumb(_categoryService, _aclService, _storeMappingService) .Select(catBr => new AUCategoryModel { Id = catBr.Id, SaleId = inSaleId, Name = catBr.GetLocalized(x => x.Name), SeName = catBr.GetSeName() }) .ToList() ); } //******************************************************************************************************************* //* Subcategories need modification because you only want to show subs that have a lot associated for this sale if sale provided //* this will affect what shows in the main panel when you click the parent node, and also affects child categores passed in the url to //* this action from the breadcrumb and navigator //************************************************************************************************************** //TODO deteermine if store wants to manage categories by sale. if so, use special stored procedure, otherwise use standard nop //logic to show raw category tree. use temporary variable for interim to control flow if (manageCategoriesBySale) { string subCategoriesCacheKey = string.Format(AUModelCacheEventConsumer.SALE_CATEGORY_SUBCATEGORIES_KEY, inSaleId, categoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); model.SubCategories = _cacheManager.Get(subCategoriesCacheKey, () => _ausaleService.GetSaleCategoriesByParentCategoryId(inSaleId, categoryId) .Select(x => { var subCatModel = new AUCategoryModel.SubCategoryModel { Id = x.Id, Name = x.GetLocalized(y => y.Name), SeName = x.GetSeName(), }; //prepare picture model int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var picture = _pictureService.GetPictureById(x.PictureId); var pictureModel = new PictureModel { FullSizeImageUrl = _pictureService.GetPictureUrl(picture), ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatModel.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatModel.Name) }; return pictureModel; }); return subCatModel; }) .ToList() ); } else //sale id is not present so get the raw hierarchy based on the category id passed in - original nop logic { string subCategoriesCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_SUBCATEGORIES_KEY, categoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); model.SubCategories = _cacheManager.Get(subCategoriesCacheKey, () => _categoryService.GetAllCategoriesByParentCategoryId(categoryId) .Select(x => { var subCatModel = new CategoryModel.SubCategoryModel { Id = x.Id, Name = x.GetLocalized(y => y.Name), SeName = x.GetSeName(), }; //prepare picture model //TODO: refactor to define only once (see above) int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var picture = _pictureService.GetPictureById(x.PictureId); var pictureModel = new PictureModel { FullSizeImageUrl = _pictureService.GetPictureUrl(picture), ImageUrl = _pictureService.GetPictureUrl(picture, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatModel.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatModel.Name) }; return pictureModel; }); return subCatModel.ToAUSubCatModel(); //NJM converting CategoryModel.SubCategoryModel to AUCategoryModel.SubCategoryModel }) .ToList() ); } //featured products //TODO - maybe want only featured products for the sales?? if (categoryId != 0) //may pass as zero if trying to present category page for sale only. For now don't show sale level featured products { if (!_catalogSettings.IgnoreFeaturedProducts) { //We cache a value indicating whether we have featured products IPagedList<Product> featuredProducts = null; string cacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY, categoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id); var hasFeaturedProductsCache = _cacheManager.Get<bool?>(cacheKey); if (!hasFeaturedProductsCache.HasValue) { //no value in the cache yet //let's load products and cache the result (true/false) featuredProducts = _productService.SearchProducts( categoryIds: new List<int> { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); hasFeaturedProductsCache = featuredProducts.TotalCount > 0; _cacheManager.Set(cacheKey, hasFeaturedProductsCache, 60); } if (hasFeaturedProductsCache.Value && featuredProducts == null) { //cache indicates that the category has featured products //let's load them featuredProducts = _productService.SearchProducts( categoryIds: new List<int> { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); } if (featuredProducts != null) { model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } } } //Gets ALL (raw) subcategories t the category passed in. If sale is provided, stored proc will only show lots in this sale in these categories var categoryIds = new List<int>(); categoryIds.Add(category.Id); if (_catalogSettings.ShowProductsFromSubcategories) { //original--> categoryIds.AddRange(GetChildCategoryIds(category.Id)); } IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList<int> filterableSpecificationAttributeOptionIds; var lots = _consignorService.GetAllLots2( out filterableSpecificationAttributeOptionIds, true, categoryIds: categoryIds, saleId: inSaleId, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin: minPriceConverted, priceMax: maxPriceConverted, filteredSpecs: alreadyFilteredSpecOptionIds, //orderBy: (ProductSortingEnum)command.OrderBy ---> not working? //TODO: fix ordering (enum issue?) //warehouseId: model.SearchWarehouseId, //productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, //keywords: model.SearchProductName, //pageIndex: command.PageNumber - 1, //pageSize: command.PageSize, showHidden: false, overridePublished: true ).Select(x => x.ToProduct()).ToList(); //NJM: Important! Notice embedded "ToProduct mapping to get from AUCombLotProc to Product //this is where you need to change to insert the bidding info int totalRecords = lots.Count; int pageIndex = command.PageNumber - 1; int pageSize = command.PageSize; //int totalRecords = (pTotalRecords.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecords.Value) : 0; //var products = new PagedList<Product>(lots, pageIndex, pageSize, totalRecords); //NJM: need to cast lots List to IPagedList so can be used in model.PagingFilteringContext.LoadPagedList(products); var products = new PagedList<Product>(lots, pageIndex, pageSize, totalRecords); //var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, // categoryIds: categoryIds, // storeId: _storeContext.CurrentStore.Id, // visibleIndividuallyOnly: true, // featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, // priceMin: minPriceConverted, // priceMax: maxPriceConverted, // filteredSpecs: alreadyFilteredSpecOptionIds, // orderBy: (ProductSortingEnum)command.OrderBy, // pageIndex: command.PageNumber - 1, // pageSize: command.PageSize); //&&&&&&&&&&&&&this function should return AU model.Products = PrepareProductOverviewModels(products).ToList(); //IPagedList<Product> products model.PagingFilteringContext.LoadPagedList(products); //specs model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId); if (template == null) template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault(); if (template == null) throw new Exception("No default template could be loaded"); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewCategory", _localizationService.GetResource("ActivityLog.PublicStore.ViewCategory"), category.Name); return View(templateViewPath, model); }
public ActionResult Manufacturer(int manufacturerId, CatalogPagingFilteringModel command) { var manufacturer = _manufacturerService.GetManufacturerById(manufacturerId); if (manufacturer == null || manufacturer.Deleted) return InvokeHttp404(); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a manufacturer before publishing if (!manufacturer.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageManufacturers)) return InvokeHttp404(); //ACL (access control list) if (!_aclService.Authorize(manufacturer)) return InvokeHttp404(); //Store mapping if (!_storeMappingService.Authorize(manufacturer)) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (command.PageNumber <= 0) command.PageNumber = 1; var model = manufacturer.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Manufacturers.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Manufacturers.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (manufacturer.AllowCustomersToSelectPageSize && manufacturer.PageSizeOptions != null) { var pageSizes = manufacturer.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (manufacturer page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = manufacturer.PageSize; } if (command.PageSize <= 0) command.PageSize = manufacturer.PageSize; //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(manufacturer.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, manufacturer.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //featured products if (!_catalogSettings.IgnoreFeaturedProducts) { IPagedList<Product> featuredProducts = null; //We cache whether we have featured products var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles .Where(cr => cr.Active).Select(cr => cr.Id).ToList(); string cacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_HAS_FEATURED_PRODUCTS_KEY, manufacturerId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var hasFeaturedProductsCache = _cacheManager.Get<bool?>(cacheKey); if (!hasFeaturedProductsCache.HasValue) { featuredProducts = _productService.SearchProducts( manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); hasFeaturedProductsCache = featuredProducts.TotalCount > 0; _cacheManager.Set(cacheKey, hasFeaturedProductsCache, 60); } if (hasFeaturedProductsCache.Value && featuredProducts == null) { featuredProducts = _productService.SearchProducts( manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); } if (featuredProducts != null) { model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } } //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, manufacturerId: manufacturer.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin: minPriceConverted, priceMax: maxPriceConverted, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; //template var templateCacheKey = string.Format(ModelCacheEventConsumer.MANUFACTURER_TEMPLATE_MODEL_KEY, manufacturer.ManufacturerTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _manufacturerTemplateService.GetManufacturerTemplateById(manufacturer.ManufacturerTemplateId); if (template == null) template = _manufacturerTemplateService.GetAllManufacturerTemplates().FirstOrDefault(); if (template == null) throw new Exception("No default template could be loaded"); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewManufacturer", _localizationService.GetResource("ActivityLog.PublicStore.ViewManufacturer"), manufacturer.Name); return View(templateViewPath, model); }
public ActionResult HomepageVenderProducts(int? productThumbPictureSize, CatalogPagingFilteringModel command) { //IList<int> filterableSpecificationAttributeOptionIds; //var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, // vendorId: vendor.Id, // storeId: _storeContext.CurrentStore.Id, // visibleIndividuallyOnly: true, // orderBy: (ProductSortingEnum)command.OrderBy, // pageIndex: command.PageNumber - 1, // pageSize: command.PageSize); //var models = PrepareProductOverviewModels(products).ToList(); var model = new List<VendorModel>(); var vendors = _vendorService.GetAllVendors(); foreach (var vendor in vendors.Where(v => v.ShowOnHomePage)) { var vendorModel = new VendorModel { Id = vendor.Id, Name = vendor.GetLocalized(x => x.Name), Description = vendor.GetLocalized(x => x.Description), MetaKeywords = vendor.GetLocalized(x => x.MetaKeywords), MetaDescription = vendor.GetLocalized(x => x.MetaDescription), MetaTitle = vendor.GetLocalized(x => x.MetaTitle), SeName = vendor.GetSeName(), AllowCustomersToContactVendors = _vendorSettings.AllowCustomersToContactVendors }; PrepareSortingOptions(vendorModel.PagingFilteringContext, command); //view mode PrepareViewModes(vendorModel.PagingFilteringContext, command); //page size PreparePageSizeOptions(vendorModel.PagingFilteringContext, command, vendor.AllowCustomersToSelectPageSize, vendor.PageSizeOptions, vendor.PageSize); IList<int> filterableSpecificationAttributeOptionIds; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, vendorId: vendor.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); vendorModel.Products = PrepareProductOverviewModels(products).ToList(); model.Add(vendorModel); } return PartialView(model); }
public ProductsByTagModel() { Products = new List<ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); }
public ActionResult ProductsByTag(int productTagId, CatalogPagingFilteringModel command) { var productTag = _productTagService.GetProductTagById(productTagId); if (productTag == null) return InvokeHttp404(); var model = new ProductsByTagModel() { Id = productTag.Id, TagName = productTag.GetLocalized(y => y.Name) }; //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, _catalogSettings.ProductsByTagAllowCustomersToSelectPageSize, _catalogSettings.ProductsByTagPageSizeOptions, _catalogSettings.ProductsByTagPageSize); //products var products = _productService.SearchProducts( storeId: _storeContext.CurrentStore.Id, productTagId: productTag.Id, visibleIndividuallyOnly: true, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); return View(model); }
public ProductsByTagModel() { Products = new List <ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); }
public ActionResult Search(SearchModel model, CatalogPagingFilteringModel command) { //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (model == null) model = new SearchModel(); if (model.Q == null) model.Q = ""; model.Q = model.Q.Trim(); //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, _catalogSettings.SearchPageAllowCustomersToSelectPageSize, _catalogSettings.SearchPagePageSizeOptions, _catalogSettings.SearchPageProductsPerPage); var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles .Where(cr => cr.Active).Select(cr => cr.Id).ToList(); string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY, _workContext.WorkingLanguage.Id, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var categories = _cacheManager.Get(cacheKey, () => { var categoriesModel = new List<SearchModel.CategoryModel>(); //all categories foreach (var c in _categoryService.GetAllCategories()) { //generate full category name (breadcrumb) string categoryBreadcrumb= ""; var breadcrumb = c.GetCategoryBreadCrumb(_categoryService, _aclService, _storeMappingService); for (int i = 0; i <= breadcrumb.Count - 1; i++) { categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name); if (i != breadcrumb.Count - 1) categoryBreadcrumb += " >> "; } categoriesModel.Add(new SearchModel.CategoryModel() { Id = c.Id, Breadcrumb = categoryBreadcrumb }); } return categoriesModel; }); if (categories.Count > 0) { //first empty entry model.AvailableCategories.Add(new SelectListItem() { Value = "0", Text = _localizationService.GetResource("Common.All") }); //all other categories foreach (var c in categories) { model.AvailableCategories.Add(new SelectListItem() { Value = c.Id.ToString(), Text = c.Breadcrumb, Selected = model.Cid == c.Id }); } } var manufacturers = _manufacturerService.GetAllManufacturers(); if (manufacturers.Count > 0) { model.AvailableManufacturers.Add(new SelectListItem() { Value = "0", Text = _localizationService.GetResource("Common.All") }); foreach (var m in manufacturers) model.AvailableManufacturers.Add(new SelectListItem() { Value = m.Id.ToString(), Text = m.GetLocalized(x => x.Name), Selected = model.Mid == m.Id }); } IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1); // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load) if (Request.Params["Q"] != null) { if (model.Q.Length < _catalogSettings.ProductSearchTermMinimumLength) { model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength); } else { var categoryIds = new List<int>(); int manufacturerId = 0; decimal? minPriceConverted = null; decimal? maxPriceConverted = null; bool searchInDescriptions = false; if (model.As) { //advanced search var categoryId = model.Cid; if (categoryId > 0) { categoryIds.Add(categoryId); if (model.Isc) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(categoryId)); } } manufacturerId = model.Mid; //min price if (!string.IsNullOrEmpty(model.Pf)) { decimal minPrice = decimal.Zero; if (decimal.TryParse(model.Pf, out minPrice)) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency); } //max price if (!string.IsNullOrEmpty(model.Pt)) { decimal maxPrice = decimal.Zero; if (decimal.TryParse(model.Pt, out maxPrice)) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency); } searchInDescriptions = model.Sid; } //var searchInProductTags = false; var searchInProductTags = searchInDescriptions; //products products = _productService.SearchProducts( categoryIds: categoryIds, manufacturerId: manufacturerId, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, priceMin: minPriceConverted, priceMax: maxPriceConverted, keywords:model.Q, searchDescriptions: searchInDescriptions, searchSku: searchInDescriptions, searchProductTags: searchInProductTags, languageId: _workContext.WorkingLanguage.Id, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.NoResults = !model.Products.Any(); //search term statistics if (!String.IsNullOrEmpty(model.Q)) { var searchTerm = _searchTermService.GetSearchTermByKeyword(model.Q, _storeContext.CurrentStore.Id); if (searchTerm != null) { searchTerm.Count++; _searchTermService.UpdateSearchTerm(searchTerm); } else { searchTerm = new SearchTerm() { Keyword = model.Q, StoreId = _storeContext.CurrentStore.Id, Count = 1 }; _searchTermService.InsertSearchTerm(searchTerm); } } //event _eventPublisher.Publish(new ProductSearchEvent() { SearchTerm = model.Q, SearchInDescriptions = searchInDescriptions, CategoryIds = categoryIds, ManufacturerId = manufacturerId, WorkingLanguageId = _workContext.WorkingLanguage.Id }); } } model.PagingFilteringContext.LoadPagedList(products); return View(model); }
public AuthorModel() { PictureModel = new PictureModel(); Products = new List <ProductOverviewModel>(); PagingFilteringContext = new CatalogPagingFilteringModel(); }
public ActionResult Category(int categoryId, CatalogPagingFilteringModel command) { var category = _categoryService.GetCategoryById(categoryId); if (category == null || category.Deleted) return InvokeHttp404(); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a category before publishing if (!category.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageCategories)) return InvokeHttp404(); //ACL (access control list) if (!_aclService.Authorize(category)) return InvokeHttp404(); //Store mapping if (!_storeMappingService.Authorize(category)) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (command.PageNumber <= 0) command.PageNumber = 1; var model = category.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (category.AllowCustomersToSelectPageSize && category.PageSizeOptions != null) { var pageSizes = category.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (category page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = category.PageSize; } if (command.PageSize <= 0) command.PageSize = category.PageSize; //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, category.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //category breadcrumb model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled; if (model.DisplayCategoryBreadcrumb) { foreach (var catBr in category.GetCategoryBreadCrumb(_categoryService, _aclService, _storeMappingService)) { model.CategoryBreadcrumb.Add(new CategoryModel() { Id = catBr.Id, Name = catBr.GetLocalized(x => x.Name), SeName = catBr.GetSeName() }); } } var customerRolesIds = _workContext.CurrentCustomer.CustomerRoles .Where(cr => cr.Active).Select(cr => cr.Id).ToList(); //subcategories //We cache whether we have subcategories IList<Category> subcategories = null; string hasSubcategoriesCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_HAS_SUBCATEGORIES_KEY, categoryId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var hasSubcategoriesCache = _cacheManager.Get<bool?>(hasSubcategoriesCacheKey); if (!hasSubcategoriesCache.HasValue) { subcategories = _categoryService.GetAllCategoriesByParentCategoryId(categoryId); hasSubcategoriesCache = subcategories.Count > 0; _cacheManager.Set(hasSubcategoriesCacheKey, hasSubcategoriesCache, 60); } if (hasSubcategoriesCache.Value && subcategories == null) { subcategories = _categoryService.GetAllCategoriesByParentCategoryId(categoryId); } if (subcategories != null) { model.SubCategories = subcategories .Select(x => { var subCatName = x.GetLocalized(y => y.Name); var subCatModel = new CategoryModel.SubCategoryModel() { Id = x.Id, Name = subCatName, SeName = x.GetSeName(), }; //prepare picture model int pictureSize = _mediaSettings.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var pictureModel = new PictureModel() { FullSizeImageUrl = _pictureService.GetPictureUrl(x.PictureId), ImageUrl = _pictureService.GetPictureUrl(x.PictureId, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatName), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatName) }; return pictureModel; }); return subCatModel; }) .ToList(); } //featured products if (!_catalogSettings.IgnoreFeaturedProducts) { //We cache whether we have featured products IPagedList<Product> featuredProducts = null; string cacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_HAS_FEATURED_PRODUCTS_KEY, categoryId, string.Join(",", customerRolesIds), _storeContext.CurrentStore.Id); var hasFeaturedProductsCache = _cacheManager.Get<bool?>(cacheKey); if (!hasFeaturedProductsCache.HasValue) { featuredProducts = _productService.SearchProducts( categoryIds: new List<int>() { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); hasFeaturedProductsCache = featuredProducts.TotalCount > 0; _cacheManager.Set(cacheKey, hasFeaturedProductsCache, 60); } if (hasFeaturedProductsCache.Value && featuredProducts == null) { featuredProducts = _productService.SearchProducts( categoryIds: new List<int>() { category.Id }, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts: true); } if (featuredProducts != null) { model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } } var categoryIds = new List<int>(); categoryIds.Add(category.Id); if (_catalogSettings.ShowProductsFromSubcategories) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(category.Id)); } //products IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, categoryIds: categoryIds, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, featuredProducts:_catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, priceMin:minPriceConverted, priceMax:maxPriceConverted, filteredSpecs: alreadyFilteredSpecOptionIds, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; //specs model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId); if (template == null) template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault(); if (template == null) throw new Exception("No default template could be loaded"); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicStore.ViewCategory", _localizationService.GetResource("ActivityLog.PublicStore.ViewCategory"), category.Name); return View(templateViewPath, model); }
public ActionResult Vendor(int vendorId, CatalogPagingFilteringModel command) { var vendor = _vendorService.GetVendorById(vendorId); if (vendor == null || vendor.Deleted) return RedirectToRoute("HomePage"); //Check whether the current user has a "Manage catalog" permission //It allows him to preview a vendor before publishing if (!vendor.Published && !_permissionService.Authorize(StandardPermissionProvider.ManageCatalog)) return RedirectToRoute("HomePage"); //ACL (access control list) if (!_aclService.Authorize(vendor)) return RedirectToRoute("HomePage"); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false)); if (command.PageNumber <= 0) command.PageNumber = 1; var model = vendor.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Vendors.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Vendors.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (vendor.AllowCustomersToSelectPageSize && vendor.PageSizeOptions != null) { var pageSizes = vendor.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (vendor page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } else { //customer is not allowed to select a page size command.PageSize = vendor.PageSize; } if (command.PageSize <= 0) command.PageSize = vendor.PageSize; //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(vendor.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, vendor.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //featured products if (!_catalogSettings.IgnoreFeaturedProducts && _vendorService.GetTotalNumberOfFeaturedProducts(vendorId) > 0) { //We use the fast GetTotalNumberOfFeaturedProducts before invoking of the slow SearchProducts //to ensure that we have at least one featured product IList<int> filterableSpecificationAttributeOptionIdsFeatured = null; var featuredProducts = _productService.SearchProducts(0,0, vendor.Id, true, null, null, 0, null, false, false, _workContext.WorkingLanguage.Id, null, ProductSortingEnum.Position, 0, int.MaxValue, false, out filterableSpecificationAttributeOptionIdsFeatured); model.FeaturedProducts = PrepareProductOverviewModels(featuredProducts).ToList(); } //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(0,0, vendor.Id, _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, minPriceConverted, maxPriceConverted, 0, string.Empty, false, false, _workContext.WorkingLanguage.Id, null, (ProductSortingEnum)command.OrderBy, command.PageNumber - 1, command.PageSize, false, out filterableSpecificationAttributeOptionIds); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; ////Branches var branches = vendor.Branches.OrderBy(b => b.DisplayOrder).ToList(); model.Branches = branches.Select(x => x.ToModel()).ToList(); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.VENDOR_TEMPLATE_MODEL_KEY, vendor.VendorTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _vendorTemplateService.GetVendorTemplateById(vendor.VendorTemplateId); if (template == null) template = _vendorTemplateService.GetAllVendorTemplates().FirstOrDefault(); return template.ViewPath; }); //activity log _customerActivityService.InsertActivity("PublicVendor.ViewVendor", _localizationService.GetResource("ActivityLog.PublicVendor.ViewVendor"), vendor.Name); return View(templateViewPath, model); }
public ActionResult Category(int categoryId, CatalogPagingFilteringModel command) { var category = _categoryService.GetCategoryById(categoryId); if (category == null || category.Deleted || !category.Published) return RedirectToAction("Index", "Home"); //'Continue shopping' URL _customerService.SaveCustomerAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false)); if (command.PageNumber <= 0) command.PageNumber = 1; var model = category.ToModel(); //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (category.AllowCustomersToSelectPageSize && category.PageSizeOptions != null) { var pageSizes = category.PageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default (category page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } if (command.PageSize <= 0) command.PageSize = category.PageSize; //price ranges model.PagingFilteringContext.PriceRangeFilter.LoadPriceRangeFilters(category.PriceRanges, _webHelper, _priceFormatter); var selectedPriceRange = model.PagingFilteringContext.PriceRangeFilter.GetSelectedPriceRange(_webHelper, category.PriceRanges); decimal? minPriceConverted = null; decimal? maxPriceConverted = null; if (selectedPriceRange != null) { if (selectedPriceRange.From.HasValue) minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.From.Value, _workContext.WorkingCurrency); if (selectedPriceRange.To.HasValue) maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(selectedPriceRange.To.Value, _workContext.WorkingCurrency); } //category breadcrumb model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled; if (model.DisplayCategoryBreadcrumb) { foreach (var catBr in GetCategoryBreadCrumb(category)) { model.CategoryBreadcrumb.Add(new CategoryModel() { Id = catBr.Id, Name = catBr.GetLocalized(x => x.Name), SeName = catBr.GetSeName() }); } } //subcategories model.SubCategories = _categoryService .GetAllCategoriesByParentCategoryId(categoryId) .Select(x => { var subCatName = x.GetLocalized(y => y.Name); var subCatModel = new CategoryModel.SubCategoryModel() { Id = x.Id, Name = subCatName, SeName = x.GetSeName(), }; //prepare picture model int pictureSize = _mediaSetting.CategoryThumbPictureSize; var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured()); subCatModel.PictureModel = _cacheManager.Get(categoryPictureCacheKey, () => { var pictureModel = new PictureModel() { FullSizeImageUrl = _pictureService.GetPictureUrl(x.PictureId), ImageUrl = _pictureService.GetPictureUrl(x.PictureId, pictureSize), Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), subCatName), AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), subCatName) }; return pictureModel; }); return subCatModel; }) .ToList(); //featured products //Question: should we use '_catalogSettings.ShowProductsFromSubcategories' setting for displaying featured products? if (!_catalogSettings.IgnoreFeaturedProducts && _categoryService.GetTotalNumberOfFeaturedProducts(categoryId) > 0) { //We use the fast GetTotalNumberOfFeaturedProducts before invoking of the slow SearchProducts //to ensure that we have at least one featured product IList<int> filterableSpecificationAttributeOptionIdsFeatured = null; var featuredProducts = _productService.SearchProducts(category.Id, 0, true, null, null, 0, null, false, _workContext.WorkingLanguage.Id, null, ProductSortingEnum.Position, 0, int.MaxValue, false, out filterableSpecificationAttributeOptionIdsFeatured); model.FeaturedProducts = featuredProducts.Select(x => PrepareProductOverviewModel(x)).ToList(); } var categoryIds = new List<int>(); categoryIds.Add(category.Id); if (_catalogSettings.ShowProductsFromSubcategories) { //include subcategories categoryIds.AddRange(GetChildCategoryIds(category.Id)); } //products IList<int> alreadyFilteredSpecOptionIds = model.PagingFilteringContext.SpecificationFilter.GetAlreadyFilteredSpecOptionIds(_webHelper); IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(categoryIds, 0, _catalogSettings.IncludeFeaturedProductsInNormalLists ? null : (bool?)false, minPriceConverted, maxPriceConverted, 0, string.Empty, false, _workContext.WorkingLanguage.Id, alreadyFilteredSpecOptionIds, (ProductSortingEnum)command.OrderBy, command.PageNumber - 1, command.PageSize, true, out filterableSpecificationAttributeOptionIds); model.Products = products.Select(x => PrepareProductOverviewModel(x)).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; //specs model.PagingFilteringContext.SpecificationFilter.PrepareSpecsFilters(alreadyFilteredSpecOptionIds, filterableSpecificationAttributeOptionIds, _specificationAttributeService, _webHelper, _workContext); //template var templateCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_TEMPLATE_MODEL_KEY, category.CategoryTemplateId); var templateViewPath = _cacheManager.Get(templateCacheKey, () => { var template = _categoryTemplateService.GetCategoryTemplateById(category.CategoryTemplateId); if (template == null) template = _categoryTemplateService.GetAllCategoryTemplates().FirstOrDefault(); return template.ViewPath; }); return View(templateViewPath, model); }
public ActionResult ProductsByTag(int productTagId, CatalogPagingFilteringModel command) { var productTag = _productTagService.GetProductById(productTagId); if (productTag == null) return RedirectToAction("Index", "Home"); if (command.PageNumber <= 0) command.PageNumber = 1; var model = new ProductsByTagModel() { TagName = productTag.Name }; //sorting model.PagingFilteringContext.AllowProductSorting = _catalogSettings.AllowProductSorting; if (model.PagingFilteringContext.AllowProductSorting) { foreach (ProductSortingEnum enumValue in Enum.GetValues(typeof(ProductSortingEnum))) { var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null); var sortValue = enumValue.GetLocalizedEnum(_localizationService, _workContext); model.PagingFilteringContext.AvailableSortOptions.Add(new SelectListItem() { Text = sortValue, Value = sortUrl, Selected = enumValue == (ProductSortingEnum)command.OrderBy }); } } //view mode model.PagingFilteringContext.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging; var viewMode = !string.IsNullOrEmpty(command.ViewMode) ? command.ViewMode : _catalogSettings.DefaultViewMode; if (model.PagingFilteringContext.AllowProductViewModeChanging) { var currentPageUrl = _webHelper.GetThisPageUrl(true); //grid model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.Grid"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=grid", null), Selected = viewMode == "grid" }); //list model.PagingFilteringContext.AvailableViewModes.Add(new SelectListItem() { Text = _localizationService.GetResource("Categories.ViewMode.List"), Value = _webHelper.ModifyQueryString(currentPageUrl, "viewmode=list", null), Selected = viewMode == "list" }); } //page size model.PagingFilteringContext.AllowCustomersToSelectPageSize = false; if (_catalogSettings.ProductsByTagAllowCustomersToSelectPageSize && _catalogSettings.ProductsByTagPageSizeOptions != null) { var pageSizes = _catalogSettings.ProductsByTagPageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (pageSizes.Any()) { // get the first page size entry to use as the default ('products by tag' page load) or if customer enters invalid value via query string if (command.PageSize <= 0 || !pageSizes.Contains(command.PageSize.ToString())) { int temp = 0; if (int.TryParse(pageSizes.FirstOrDefault(), out temp)) { if (temp > 0) { command.PageSize = temp; } } } var currentPageUrl = _webHelper.GetThisPageUrl(true); var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null); sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber"); foreach (var pageSize in pageSizes) { int temp = 0; if (!int.TryParse(pageSize, out temp)) { continue; } if (temp <= 0) { continue; } model.PagingFilteringContext.PageSizeOptions.Add(new SelectListItem() { Text = pageSize, Value = String.Format(sortUrl, pageSize), Selected = pageSize.Equals(command.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase) }); } if (model.PagingFilteringContext.PageSizeOptions.Any()) { model.PagingFilteringContext.PageSizeOptions = model.PagingFilteringContext.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList(); model.PagingFilteringContext.AllowCustomersToSelectPageSize = true; if (command.PageSize <= 0) { command.PageSize = int.Parse(model.PagingFilteringContext.PageSizeOptions.FirstOrDefault().Text); } } } } if (command.PageSize <= 0) command.PageSize = _catalogSettings.ProductsByTagPageSize; //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(0, 0, false, null, null, productTag.Id, string.Empty, false, _workContext.WorkingLanguage.Id, null, (ProductSortingEnum)command.OrderBy, command.PageNumber - 1, command.PageSize, false, out filterableSpecificationAttributeOptionIds); model.Products = products.Select(x => PrepareProductOverviewModel(x)).ToList(); model.PagingFilteringContext.LoadPagedList(products); model.PagingFilteringContext.ViewMode = viewMode; return View(model); }
public ActionResult Vendor(int vendorId, CatalogPagingFilteringModel command) { var vendor = _vendorService.GetVendorById(vendorId); if (vendor == null || vendor.Deleted || !vendor.Active) return InvokeHttp404(); //Vendor is active? if (!vendor.Active) return InvokeHttp404(); //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastContinueShoppingPage, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); var model = new VendorModel() { Id = vendor.Id, Name = vendor.GetLocalized(x => x.Name), Description = vendor.GetLocalized(x => x.Description), MetaKeywords = vendor.GetLocalized(x => x.MetaKeywords), MetaDescription = vendor.GetLocalized(x => x.MetaDescription), MetaTitle = vendor.GetLocalized(x => x.MetaTitle), SeName = vendor.GetSeName(), }; //sorting PrepareSortingOptions(model.PagingFilteringContext, command); //view mode PrepareViewModes(model.PagingFilteringContext, command); //page size PreparePageSizeOptions(model.PagingFilteringContext, command, vendor.AllowCustomersToSelectPageSize, vendor.PageSizeOptions, vendor.PageSize); //products IList<int> filterableSpecificationAttributeOptionIds = null; var products = _productService.SearchProducts(out filterableSpecificationAttributeOptionIds, true, vendorId: vendor.Id, storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true, orderBy: (ProductSortingEnum)command.OrderBy, pageIndex: command.PageNumber - 1, pageSize: command.PageSize); model.Products = PrepareProductOverviewModels(products).ToList(); model.PagingFilteringContext.LoadPagedList(products); return View(model); }