Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Improvements/code (#575)
Krzysztof Pajak47159fd9f401
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.csindex b40e73808..bf7e9bfe5 100644--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs@@ -73,11 +73,11 @@ public class ApiAuthenticationService : IApiAuthenticationServiceif (!authResult.Succeeded)return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);- var email = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;+ var email = authResult.Principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;if (email is null){//guest- var id = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;+ var id = authResult.Principal.Claims.FirstOrDefault(x => x.Type == "Guid")?.Value;if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));}elsediff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.csindex 5b64908e2..b3d1be489 100644--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs@@ -141,47 +141,58 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceif (!authenticateResult.Succeeded)return null;- Customer customer = null;+ var customer = await RetrieveCustomer(authenticateResult.Principal);+ if (customer == null || !await IsValidCustomer(customer, authenticateResult.Principal))+ return null;++ return customer;+ }++ private async Task<Customer> RetrieveCustomer(ClaimsPrincipal principal)+ {if (_customerSettings.UsernamesEnabled){- //get customer by username if exists- var usernameClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name- && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer,- StringComparison.InvariantCultureIgnoreCase));- if (usernameClaim != null)- customer = await _customerService.GetCustomerByUsername(usernameClaim.Value);+ var username = principal.FindFirst(claim =>+ claim.Type == ClaimTypes.Name &&+ claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase))+ ?.Value;++ if (!string.IsNullOrEmpty(username))+ return await _customerService.GetCustomerByUsername(username);}else{- //get customer by email- var emailClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email- && claim.Issuer.Equals(- _securityConfig.CookieClaimsIssuer,- StringComparison- .InvariantCultureIgnoreCase));- if (emailClaim != null)- customer = await _customerService.GetCustomerByEmail(emailClaim.Value);+ var email = principal.FindFirst(claim =>+ claim.Type == ClaimTypes.Email &&+ claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase))+ ?.Value;++ if (!string.IsNullOrEmpty(email))+ return await _customerService.GetCustomerByEmail(email);}- if (customer != null)+ return null;+ }++ private async Task<bool> IsValidCustomer(Customer customer, ClaimsPrincipal principal)+ {+ var passwordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);+ if (!string.IsNullOrEmpty(passwordToken)){- var passwordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);- if (!string.IsNullOrEmpty(passwordToken))- {- var tokenClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.UserData- && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer,- StringComparison.InvariantCultureIgnoreCase));- if (tokenClaim == null || tokenClaim.Value != passwordToken) customer = null;- }+ var tokenClaim = principal+ .FindFirst(claim =>+ claim.Type == ClaimTypes.UserData &&+ claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase));++ if (tokenClaim == null || tokenClaim.Value != passwordToken)+ return false;}- //Check if the found customer is available- if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))- return null;+ if (!customer.Active || customer.Deleted || !await _groupService.IsRegistered(customer))+ return false;- return customer;+ return true;}-/// <summary>/// Get customer cookie/// </summary>diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.csindex e909c5d1a..b10fb42f2 100644--- a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs@@ -4,7 +4,6 @@ using Grand.Domain.Directory;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.SharedKernel;using MediatR;namespace Grand.Business.Catalog.Services.Directory;@@ -93,8 +92,8 @@ public class MeasureService : IMeasureServicereturn await _cacheBase.GetAsync(key, async () =>{var query = from md in _measureDimensionRepository.Table- orderby md.DisplayOrder- select md;+ orderby md.DisplayOrder+ select md;return await Task.FromResult(query.ToList());});}@@ -162,7 +161,7 @@ public class MeasureService : IMeasureServiceArgumentNullException.ThrowIfNull(targetMeasureDimension);var result = value;- if (result != 0 && sourceMeasureDimension.Id != targetMeasureDimension.Id)+ if (sourceMeasureDimension.Id != targetMeasureDimension.Id){result = await ConvertToPrimaryMeasureDimension(result, sourceMeasureDimension);result = await ConvertFromPrimaryMeasureDimension(result, targetMeasureDimension);@@ -186,11 +185,8 @@ public class MeasureService : IMeasureServicevar result = value;var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);- if (result == 0 || sourceMeasureDimension.Id == baseDimensionIn.Id) return result;- var exchangeRatio = sourceMeasureDimension.Ratio;- if (exchangeRatio == 0)- throw new GrandException($"Exchange ratio not set for dimension [{sourceMeasureDimension.Name}]");- result /= exchangeRatio;+ if (sourceMeasureDimension.Id == baseDimensionIn.Id) return result;+ result /= sourceMeasureDimension.Ratio;return result;}@@ -207,11 +203,8 @@ public class MeasureService : IMeasureServicevar result = value;var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId);- if (result == 0 || targetMeasureDimension.Id == baseDimensionIn.Id) return result;- var exchangeRatio = targetMeasureDimension.Ratio;- if (exchangeRatio == 0)- throw new GrandException($"Exchange ratio not set for dimension [{targetMeasureDimension.Name}]");- result *= exchangeRatio;+ if (targetMeasureDimension.Id == baseDimensionIn.Id) return result;+ result *= targetMeasureDimension.Ratio;return result;}@@ -255,8 +248,8 @@ public class MeasureService : IMeasureServicereturn await _cacheBase.GetAsync(key, async () =>{var query = from mw in _measureWeightRepository.Table- orderby mw.DisplayOrder- select mw;+ orderby mw.DisplayOrder+ select mw;return await Task.FromResult(query.ToList());});}@@ -324,7 +317,7 @@ public class MeasureService : IMeasureServiceArgumentNullException.ThrowIfNull(targetMeasureWeight);var result = value;- if (result != 0 && sourceMeasureWeight.Id != targetMeasureWeight.Id)+ if (sourceMeasureWeight.Id != targetMeasureWeight.Id){result = await ConvertToPrimaryMeasureWeight(result, sourceMeasureWeight);result = await ConvertFromPrimaryMeasureWeight(result, targetMeasureWeight);@@ -347,11 +340,8 @@ public class MeasureService : IMeasureServicevar result = value;var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);- if (result == 0 || sourceMeasureWeight.Id == baseWeightIn.Id) return result;- var exchangeRatio = sourceMeasureWeight.Ratio;- if (exchangeRatio == 0)- throw new GrandException($"Exchange ratio not set for weight [{sourceMeasureWeight.Name}]");- result /= exchangeRatio;+ if (sourceMeasureWeight.Id == baseWeightIn.Id) return result;+ result /= sourceMeasureWeight.Ratio;return result;}@@ -368,11 +358,8 @@ public class MeasureService : IMeasureServicevar result = value;var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId);- if (result == 0 || targetMeasureWeight.Id == baseWeightIn.Id) return result;- var exchangeRatio = targetMeasureWeight.Ratio;- if (exchangeRatio == 0)- throw new GrandException($"Exchange ratio not set for weight [{targetMeasureWeight.Name}]");- result *= exchangeRatio;+ if (targetMeasureWeight.Id == baseWeightIn.Id) return result;+ result *= targetMeasureWeight.Ratio;return result;}@@ -402,8 +389,8 @@ public class MeasureService : IMeasureServicereturn await _cacheBase.GetAsync(key, async () =>{var query = from md in _measureUnitRepository.Table- orderby md.DisplayOrder- select md;+ orderby md.DisplayOrder+ select md;return await Task.FromResult(query.ToList());});}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.csindex 90799591a..b87ccb310 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs@@ -222,9 +222,9 @@ public class ProductAttributeFormatter : IProductAttributeFormatter//attributes with valuesif (product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id) != null){- var attributeValue = product.ProductAttributeMappings- .FirstOrDefault(x => x.Id == attributes[i].Id).ProductAttributeValues- .FirstOrDefault(x => x.Id == valueStr);+ var attributeMapping = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attributes[i].Id);+ var attributeValue = attributeMapping?.ProductAttributeValues.FirstOrDefault(x => x.Id == valueStr);+if (attributeValue != null){formattedAttribute =diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.csindex e8b059dbe..e707c362a 100644--- a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs@@ -32,7 +32,7 @@ public class VatService : IVatService//PL 111 1111 111 or PL 1111111111//more advanced regex - http://codeigniter.com/wiki/European_Vat_Checker- var r = new Regex(@"^(\w{2})(.*)");+ var r = new Regex(@"^(\w{2})(.*)", RegexOptions.Compiled, TimeSpan.FromSeconds(1));var match = r.Match(fullVatNumber);if (!match.Success)return (VatNumberStatus.Invalid, name, address, null);@@ -42,7 +42,6 @@ public class VatService : IVatServicereturn await GetVatNumberStatus(twoLetterIsoCode, vatNumber);}-/// <summary>/// Gets VAT Number status/// </summary>diff --git a/src/Business/Grand.Business.Cms/Services/CookiePreference.cs b/src/Business/Grand.Business.Cms/Services/CookiePreference.csindex 6fd57ee7e..b2b5ff84c 100644--- a/src/Business/Grand.Business.Cms/Services/CookiePreference.cs+++ b/src/Business/Grand.Business.Cms/Services/CookiePreference.cs@@ -25,7 +25,7 @@ public class CookiePreference : ICookiePreference{var result = default(bool?);var savedCookiesConsent = customer.GetUserFieldFromEntity<Dictionary<string, bool>>(SystemCustomerFieldNames.ConsentCookies, store.Id);- if (savedCookiesConsent == null) return null;+ if (savedCookiesConsent == null) return Task.FromResult<bool?>(null);if (savedCookiesConsent.TryGetValue(cookieSystemName, out var value))result = value;diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.csindex 04192f52c..0e320a855 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs@@ -222,11 +222,9 @@ public class CustomerService : ICustomerService/// </summary>/// <param name="email">Email</param>/// <returns>Customer</returns>- public virtual async Task<Customer> GetCustomerByEmail(string email)+ public virtual Task<Customer> GetCustomerByEmail(string email){- return string.IsNullOrWhiteSpace(email)- ? null- : await _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant());+ return string.IsNullOrWhiteSpace(email) ? Task.FromResult<Customer>(null) : _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant());}/// <summary>@@ -237,7 +235,7 @@ public class CustomerService : ICustomerServicepublic virtual Task<Customer> GetCustomerBySystemName(string systemName){if (string.IsNullOrWhiteSpace(systemName))- return null;+ return Task.FromResult<Customer>(null);var key = string.Format(CacheKey.CUSTOMER_BY_SYSTEMNAME_BY_KEY, systemName);@@ -249,12 +247,12 @@ public class CustomerService : ICustomerService/// </summary>/// <param name="username">Username</param>/// <returns>Customer</returns>- public virtual async Task<Customer> GetCustomerByUsername(string username)+ public virtual Task<Customer> GetCustomerByUsername(string username){if (string.IsNullOrWhiteSpace(username))- return null;+ return Task.FromResult<Customer>(null);- return await _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant());+ return _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant());}/// <summary>diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.csindex e1485eb10..210207adf 100644--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs@@ -275,16 +275,18 @@ public class PictureService : IPictureServiceusing (var mutex = new Mutex(false, thumbFileName)){mutex.WaitOne();- using (var image = SKBitmap.Decode(filePath))+ try{+ using var image = SKBitmap.Decode(filePath);var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);if (pictureBinary != null)await SaveThumb(thumbFileName, pictureBinary);}-- mutex.ReleaseMutex();+ finally+ {+ mutex.ReleaseMutex();+ }}-var url = GetThumbUrl(thumbFileName, storeLocation);return url;}@@ -354,8 +356,14 @@ public class PictureService : IPictureServiceusing var mutex = new Mutex(false, thumbFileName);mutex.WaitOne();- await SaveThumb(thumbFileName, pictureBinary);- mutex.ReleaseMutex();+ try+ {+ await SaveThumb(thumbFileName, pictureBinary);+ }+ finally+ {+ mutex.ReleaseMutex();+ }}else{@@ -372,22 +380,28 @@ public class PictureService : IPictureServiceusing var mutex = new Mutex(false, thumbFileName);mutex.WaitOne();- if (pictureBinary != null)- try- {- using var image = SKBitmap.Decode(pictureBinary);- var resizedBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);- if (resizedBinary != null)- pictureBinary = resizedBinary;- }- catch+ try+ {+ if (pictureBinary != null){- // ignored+ try+ {+ using var image = SKBitmap.Decode(pictureBinary);+ var resizedBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);+ if (resizedBinary != null)+ pictureBinary = resizedBinary;+ }+ catch+ {+ // ignored+ }}-- await SaveThumb(thumbFileName, pictureBinary);-- mutex.ReleaseMutex();+ await SaveThumb(thumbFileName, pictureBinary);+ }+ finally+ {+ mutex.ReleaseMutex();+ }}return GetThumbUrl(thumbFileName, storeLocation);diff --git a/src/Core/Grand.Infrastructure/GrandVersion.cs b/src/Core/Grand.Infrastructure/GrandVersion.csindex 266c74139..e4895c17f 100644--- a/src/Core/Grand.Infrastructure/GrandVersion.cs+++ b/src/Core/Grand.Infrastructure/GrandVersion.cs@@ -49,7 +49,7 @@ public static class GrandVersionif (assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) is notAssemblyInformationalVersionAttribute infoVersionAttribute) return "0";var fullVersion = infoVersionAttribute.InformationalVersion;- var match = Regex.Match(fullVersion, @"(\d+)\.(\d+)\.(\d+)(?:-([^\+]+))?");+ var match = Regex.Match(fullVersion, @"(\d+)\.(\d+)\.(\d+)(?:-([^\+]+))?", RegexOptions.Compiled, TimeSpan.FromSeconds(1));if (!match.Success) return "0";var patch = match.Groups[3].Value;var suffix = match.Groups[4].Value;diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManager.csindex f3bde103e..a8c5fc585 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs@@ -333,7 +333,7 @@ public static class PluginManagerprivate static bool Matches(string fullName, string pattern){- return Regex.IsMatch(fullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);+ return Regex.IsMatch(fullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromSeconds(1));}private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder,diff --git a/src/Web/Grand.Web.Admin/Extensions/AllowedFileExtensions.cs b/src/Core/Grand.SharedKernel/Extensions/AllowedFileExtensions.cssimilarity index 57%rename from src/Web/Grand.Web.Admin/Extensions/AllowedFileExtensions.csrename to src/Core/Grand.SharedKernel/Extensions/AllowedFileExtensions.csindex d0b0f77d7..ccd740693 100644--- a/src/Web/Grand.Web.Admin/Extensions/AllowedFileExtensions.cs+++ b/src/Core/Grand.SharedKernel/Extensions/AllowedFileExtensions.cs@@ -1,4 +1,4 @@-namespace Grand.Web.Admin.Extensions;+namespace Grand.SharedKernel.Extensions;public static class FileExtensions{@@ -8,4 +8,8 @@ public static class FileExtensionsreturn new List<string> { ".gif", ".jpg", ".jpeg", ".png", ".bmp", ".webp" };return allowedFileTypes.Split(',').Select(x => x.Trim().ToLowerInvariant()).ToList();}+ public static bool IsAllowedMediaFileType(this IEnumerable<string> allowedFileTypes, string fileExtension)+ {+ return allowedFileTypes.Any(ft => ft.Equals(fileExtension, StringComparison.OrdinalIgnoreCase));+ }}\ No newline at end of filediff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.csindex f546cbc5e..ae6bb487d 100644--- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs+++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs@@ -41,7 +41,7 @@ public static class CommonHelperemail = email.Trim();var result = Regex.IsMatch(email,"^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$",- RegexOptions.IgnoreCase);+ RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));return result;}diff --git a/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs b/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Common/GetSitemapXMLCommandHandler.csindex 41ed745bf..b950a5ffd 100644--- a/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs+++ b/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Common/GetSitemapXMLCommandHandler.cs@@ -354,7 +354,7 @@ public class GetSitemapXmlCommandHandler : IRequestHandler<GetSitemapXmlCommand,{if (str == null)return null;- str = Regex.Replace(str, @"[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]", "", RegexOptions.Compiled);+ str = Regex.Replace(str, @"[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]", "", RegexOptions.Compiled, TimeSpan.FromSeconds(1));if (string.IsNullOrEmpty(str))return null;diff --git a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.csindex 48cd0c96e..5520072d0 100644--- a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs+++ b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs@@ -78,9 +78,7 @@ public class CountryStateZipTaxProvider : ITaxProvidervar taxCategoryId = calculateTaxRequest.TaxCategoryId;var countryId = calculateTaxRequest.Address.CountryId;var stateProvinceId = calculateTaxRequest.Address.StateProvinceId;- var zip = calculateTaxRequest.Address.ZipPostalCode ?? string.Empty;-- zip = zip.Trim();+ var zip = calculateTaxRequest.Address.ZipPostalCode?.Trim() ?? string.Empty;var existingRates = allTaxRates.Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId).ToList();@@ -102,14 +100,15 @@ public class CountryStateZipTaxProvider : ITaxProviderstring.IsNullOrEmpty(taxRate.StateProvinceId)));//filter by zip- var matchedByZip = matchedByStateProvince.Where(taxRate =>- (string.IsNullOrEmpty(zip) && string.IsNullOrEmpty(taxRate.Zip)) ||- zip.Equals(taxRate.Zip, StringComparison.OrdinalIgnoreCase)).ToList();- if (!matchedByZip.Any())- matchedByZip.AddRange(matchedByStateProvince.Where(taxRate => string.IsNullOrWhiteSpace(taxRate.Zip)));-- if (matchedByZip.Any())- result.TaxRate = matchedByZip[0].Percentage;+ if(!string.IsNullOrEmpty(zip))+ {+ var matchedByZip = matchedByStateProvince.Where(taxRate => zip.Equals(taxRate.Zip, StringComparison.OrdinalIgnoreCase)).ToList();+ if (matchedByZip.Any())+ {+ result.TaxRate = matchedByZip[0].Percentage;+ return result;+ }+ }return result;}diff --git a/src/Plugins/Theme.Modern/Content/script/app.js b/src/Plugins/Theme.Modern/Content/script/app.jsindex 553b71458..82a12dae0 100644--- a/src/Plugins/Theme.Modern/Content/script/app.js+++ b/src/Plugins/Theme.Modern/Content/script/app.js@@ -568,7 +568,7 @@ var vm = new Vue({var formData = new FormData();var imagefile = e;var url = imagefile.getAttribute('data-url');- formData.append("image", qqfile.files[0]);+ formData.append("file", e.files[0]);axios.post(url, formData, {headers: {'Content-Type': 'multipart/form-data'diff --git a/src/Tests/Grand.Web.Common.Tests/Binders/DataSourceRequestFilterBinderTests.cs b/src/Tests/Grand.Web.Common.Tests/Binders/DataSourceRequestFilterBinderTests.csnew file mode 100644index 000000000..cfb43353d--- /dev/null+++ b/src/Tests/Grand.Web.Common.Tests/Binders/DataSourceRequestFilterBinderTests.cs@@ -0,0 +1,67 @@+using Grand.Web.Common.Binders;+using Grand.Web.Common.DataSource;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc.ModelBinding;+using Microsoft.Extensions.Primitives;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using System.Globalization;++namespace Grand.Web.Common.Tests.Binders;++[TestClass]+public class DataSourceRequestFilterBinderTests+{+ [TestMethod]+ public async Task BindModelAsync_BindsCorrectValues()+ {+ // Arrange+ var queryParams = new Dictionary<string, StringValues>+ {+ { "filter[logic]", "and" },+ { "filter[filters][0][field]", "Name" },+ { "filter[filters][0][operator]", "startswith" },+ { "filter[filters][0][value]", "hello" },+ { "filter[filters][0][ignoreCase]", "true" }+ };++ var queryCollection = new QueryCollection(queryParams);+ var httpContext = new DefaultHttpContext();+ httpContext.Request.Query = queryCollection;++ var modelMetadataProvider = new EmptyModelMetadataProvider();+ var metadata = modelMetadataProvider.GetMetadataForType(typeof(DataSourceRequestFilter));++ var valueProvider = new QueryStringValueProvider(+ BindingSource.Query,+ queryCollection,+ CultureInfo.InvariantCulture);++ var bindingContext = new DefaultModelBindingContext {+ ModelMetadata = metadata,+ ModelName = "filter",+ ValueProvider = valueProvider,+ ActionContext = new Microsoft.AspNetCore.Mvc.ActionContext {+ HttpContext = httpContext+ }+ };++ var binder = new DataSourceRequestFilterBinder();++ // Act+ await binder.BindModelAsync(bindingContext);++ // Assert+ Assert.IsTrue(bindingContext.Result.IsModelSet);+ var result = bindingContext.Result.Model as DataSourceRequestFilter;+ Assert.IsNotNull(result);+ Assert.AreEqual("and", result.Logic);+ Assert.IsNotNull(result.Filters);+ Assert.AreEqual(1, result.Filters.Count);++ var filter = result.Filters.First();+ Assert.AreEqual("Name", filter.Field);+ Assert.AreEqual("startswith", filter.Operator);+ Assert.AreEqual("hello", filter.Value);+ Assert.IsTrue(filter.IgnoreCase);+ }+}diff --git a/src/Web/Grand.SharedUIResources/Grand.SharedUIResources.csproj b/src/Web/Grand.SharedUIResources/Grand.SharedUIResources.csprojindex 71ef9af67..555687d7f 100644--- a/src/Web/Grand.SharedUIResources/Grand.SharedUIResources.csproj+++ b/src/Web/Grand.SharedUIResources/Grand.SharedUIResources.csproj@@ -1,10 +1,14 @@-<Project Sdk="Microsoft.NET.Sdk.Razor">+<Project Sdk="Microsoft.NET.Sdk.Razor"><Import Project="..\..\Build\Grand.Common.props" /><PropertyGroup>+ <AddRazorSupportForMvc>true</AddRazorSupportForMvc><CompressionEnabled>false</CompressionEnabled></PropertyGroup><ItemGroup><Folder Include="wwwroot\" /></ItemGroup>-+ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ <ProjectReference Include="..\Grand.Web.Common\Grand.Web.Common.csproj" />+ </ItemGroup></Project>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Brand.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Brand.cshtmlsimilarity index 86%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Brand.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Brand.cshtmlindex e70551340..e4361a86a 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Brand.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Brand.cshtml@@ -1,5 +1,7 @@@model string-+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}@Html.TextBoxFor(model => model, new { @class = "col-md-12", style = "width: 100%;" })<script>@@ -11,7 +13,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("Brand", "Search", new { area = Constants.AreaAdmin, brandId = Model }))"+ url: "@Html.Raw(Url.Action("Brand", "Search", new { area, brandId = Model }))"}},schema: {diff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Category.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Category.cshtmlsimilarity index 85%rename from src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Category.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Category.cshtmlindex 8a8aa02a9..220318c87 100644--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Category.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Category.cshtml@@ -1,5 +1,7 @@@model string-+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}@Html.TextBoxFor(model => model, new { @class = "col-md-8", style = "width: 100%;" })<script>@@ -11,7 +13,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("Category", "Search", new { area = Constants.AreaVendor, categoryId = Model }))"+ url: "@Html.Raw(Url.Action("Category", "Search", new { area, categoryId = Model }))"}},schema: {diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Codemirror.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Codemirror.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Codemirror.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Codemirror.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Collection.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Collection.cshtmlsimilarity index 85%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Collection.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Collection.cshtmlindex 290103629..0e052b4f1 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Collection.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Collection.cshtml@@ -1,5 +1,7 @@@model string-+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}@Html.TextBoxFor(model => model, new { @class = "col-md-8", style = "width: 100%;" })<script>@@ -11,7 +13,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("Collection", "Search", new { area = Constants.AreaAdmin, collectionId = Model }))"+ url: "@Html.Raw(Url.Action("Collection", "Search", new { area, collectionId = Model }))"}},schema: {diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/CustomerGroups.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/CustomerGroups.cshtmlsimilarity index 91%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/CustomerGroups.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/CustomerGroups.cshtmlindex 0763f05d1..951873208 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/CustomerGroups.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/CustomerGroups.cshtml@@ -2,6 +2,7 @@@model string[]@inject AccessControlConfig AccessControlConfig;@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();var warnings = true;if (ViewData["DisableIgnoreAclWarnings"] != null){@@ -22,7 +23,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("CustomerGroup", "Search", new { area = Constants.AreaAdmin, customerGroups = Model }))"+ url: "@Html.Raw(Url.Action("CustomerGroup", "Search", new { area, customerGroups = Model }))"}},schema: {diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Date.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Date.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Date.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Date.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateNullable.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateNullable.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateNullable.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateNullable.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateTime.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateTime.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateTime.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateTime.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateTimeNullable.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateTimeNullable.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DateTimeNullable.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DateTimeNullable.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Decimal.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Decimal.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Decimal.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Decimal.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DecimalN4.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DecimalN4.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DecimalN4.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DecimalN4.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DecimalNullable.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DecimalNullable.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DecimalNullable.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DecimalNullable.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Double.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Double.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Double.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Double.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DoubleN4.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DoubleN4.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DoubleN4.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DoubleN4.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DoubleNullable.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DoubleNullable.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/DoubleNullable.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/DoubleNullable.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Download.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Download.cshtmlsimilarity index 69%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Download.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Download.cshtmlindex 94d28f420..83e95bcc8 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Download.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Download.cshtml@@ -1,11 +1,11 @@@using Grand.Business.Core.Interfaces.Storage-@using Constants = Grand.SharedUIResources.Constants+@using Grand.SharedKernel.Extensions@model string@inject IDownloadService downloadService@{- <link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css"/>- <script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>-+ <link rel="stylesheet" type="text/css" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css" />+ <script asp-location="Footer" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>+ var area = ViewContext.RouteData.Values["area"]?.ToString();var randomNumber = CommonHelper.GenerateRandomInteger();var clientId = "download" + randomNumber;var download = await downloadService.GetDownloadById(Model);@@ -23,7 +23,7 @@$.ajax({cache: false,type: "POST",- url: "@(Url.Action("SaveDownloadUrl", "Download", new { area = Grand.Web.Admin.Extensions.Constants.AreaAdmin }))",+ url: "@(Url.Action("SaveDownloadUrl", "Download", new { area }))",data: { "downloadUrl": downloadUrl, DownloadType: '@ViewData["DownloadType"]', ReferenceId: '@ViewData["ReferenceId"]' },success: function (data) {if (data.success) {@@ -107,47 +107,20 @@<div>@*fine uploader container*@<div id="@clientId"></div>- <script type="text/template" id="@(clientId)-qq-template">- <div class="qq-uploader-selector qq-uploader">- <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>- <span>@Loc["Common.FileUploader.DropFiles"]</span>- </div>- <div class="qq-upload-button-selector btn yellow">- <div>@Loc["Common.FileUploader.Upload"]</div>- </div>- <span class="qq-drop-processing-selector qq-drop-processing">- <span>@Loc["Common.FileUploader.Processing"]</span>- <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>- </span>- <ul class="qq-upload-list-selector qq-upload-list">- <li>- <div class="qq-progress-bar-container-selector">- <div class="qq-progress-bar-selector qq-progress-bar"></div>- </div>- <span class="qq-upload-spinner-selector qq-upload-spinner"></span>- <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>- <span class="qq-upload-file-selector qq-upload-file"></span>- <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">- <span class="qq-upload-size-selector qq-upload-size"></span>- <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>- <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>- <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>- <span class="qq-upload-status-text-selector qq-upload-status-text"></span>- </li>- </ul>- </div>- </script>-+ <div id="@(clientId)-qq-template" style="display: none;">+ <partial name="Partials/QqUploader" />+ </div><script>$(document).ready(function () {$("#@clientId").fineUploader({request: {- endpoint: '@(Url.Action("AsyncUpload", "Download", new { area = Grand.Web.Admin.Extensions.Constants.AreaAdmin }))',+ endpoint: '@(Url.Action("AsyncUpload", "Download", new { area }))',params: {DownloadType: '@ViewData["DownloadType"]',ReferenceId: '@ViewData["ReferenceId"]'- }+ },+ inputName: "file"},template: "@(clientId)-qq-template",multiple: false@@ -171,7 +144,7 @@<div id="@(clientId + "downloadurl")">@if (download != null){- <a href="@(Url.Action("DownloadFile", "Download", new { downloadGuid = download.DownloadGuid, area = Grand.Web.Admin.Extensions.Constants.AreaAdmin }))" class="btn purple">@Loc["Admin.Download.DownloadUploadedFile"]</a>+ <a href="@(Url.Action("DownloadFile", "Download", new { downloadGuid = download.DownloadGuid, area }))" class="btn purple">@Loc["Admin.Download.DownloadUploadedFile"]</a>}</div><div>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Editor.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Editor.cshtmlsimilarity index 96%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Editor.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Editor.cshtmlindex d354f9375..23e0c29cb 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Editor.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Editor.cshtml@@ -1,6 +1,7 @@@using Grand.Business.Core.Interfaces.Common.Security@using Grand.Domain.Permissions-@using Constants = Grand.SharedUIResources.Constants+@using Grand.SharedKernel.Extensions+@model string@inject IPermissionService permissionService@{@@ -17,7 +18,7 @@function elfinderDialog@(random)(context) { // <------------------ +contextvar fm = $('<div/>').dialogelfinder({url: '@Url.Action("Connector", "ElFinder")',- baseUrl: '@(Constants.WwwRoot)/administration/elfinder/',+ baseUrl: '@(Grand.SharedUIResources.Constants.WwwRoot)/administration/elfinder/',lang: 'en',width: 840,height: 450,diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Int32.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Int32.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Int32.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Int32.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Int32Nullable.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Int32Nullable.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Int32Nullable.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Int32Nullable.cshtmldiff --git a/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/MultiPicture.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/MultiPicture.cshtmlnew file mode 100644index 000000000..4eb6ca580--- /dev/null+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/MultiPicture.cshtml@@ -0,0 +1,53 @@+@using Grand.SharedKernel.Extensions+@model string+@{+ var random = CommonHelper.GenerateRandomInteger();+ var clientId = "multipicture" + random;++ var reference = ViewData["Reference"];+ var objectId = ViewData["ObjectId"];+ var endpoint = ViewData["Endpoint"];+ var click = ViewData["Click"];+}++<partial name="Partials/FineUploader" />++<div id="@clientId"></div>++<div id="@(clientId + "image")">+</div>++<div id="@(clientId)-qq-template" style="display: none;">+ <partial name="Partials/QqUploader" />+</div>+++<script>+ $(document).ready(function() {++ $("#@(clientId)").fineUploader({+ request: {+ endpoint: '@endpoint',+ params: {+ Reference: '@reference',+ ObjectId: '@objectId'+ },+ inputName: "files"+ },+ template: "@(clientId)-qq-template",+ multiple: true,+ validation: {+ itemLimit: 10,+ acceptFiles: 'image/*',+ }+ }).on("complete", function(event, id, name, responseJSON, xhr) {+ if (responseJSON.success) {+ $("#@click").click();+ }+ else {+ $('.qq-upload-status-message').text(responseJSON.message);+ }+ });++ });+</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/MultiSelect.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/MultiSelect.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/MultiSelect.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/MultiSelect.cshtmldiff --git a/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Picture.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Picture.cshtmlnew file mode 100644index 000000000..178cc460d--- /dev/null+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Picture.cshtml@@ -0,0 +1,73 @@+@using Grand.Business.Core.Interfaces.Storage+@using Grand.SharedKernel.Extensions+@model string+@inject IPictureService pictureService+@{+ var random = CommonHelper.GenerateRandomInteger();+ var clientId = "picture" + random;+ var picture = await pictureService.GetPictureById(Model);+ var targetPictureSize = 100;+ var area = ViewContext.RouteData.Values["area"]?.ToString();+ var altText = picture?.AltAttribute ?? "";+}++<partial name="Partials/FineUploader" />++<div id="@(clientId + "value")">+ <input asp-for="@Model" type="hidden"/>+</div>+<div id="@(clientId + "image")">+ <img alt="@altText" src="@(await pictureService.GetPictureUrl(Model, targetPictureSize))" />+</div>+@if (picture != null)+{+ <span id="@(clientId + "remove")" class="btn red btn-outline margin-top-10">@Loc["Admin.Picture.RemovePicture"]</span>+}+else+{+ <span id="@(clientId + "remove")" class="btn red btn-outline" style="display:none;">@Loc["Admin.Picture.RemovePicture"]</span>+}+<br/>+<div id="@clientId"></div>++<div id="@(clientId)-qq-template" style="display: none;">+ <partial name="Partials/QqUploader" />+</div>++<script>+ $(document).ready(function() {++ $("#@(clientId)").fineUploader({+ request: {+ endpoint: '@(Url.Action("AsyncUpload", "Picture", new { area }))',+ params: {+ Reference: '@ViewData["Reference"]',+ ObjectId: '@ViewData["ObjectId"]'+ },+ inputName: "file"+ },+ template: "@(clientId)-qq-template",+ multiple: false,+ validation: {+ itemLimit: 5,+ acceptFiles: 'image/*',+ }+ }).on("complete", function(event, id, name, responseJSON, xhr) {+ if (responseJSON.success) {+ $("#@(clientId + "image")").html("<img src='" + responseJSON.imageUrl + "' width='100' >");+ $("#@(clientId + "value") input").val(responseJSON.pictureId);+ $("#@(clientId + "remove")").show();+ }+ else {+ $('.qq-upload-status-message').text(responseJSON.message);+ }+ });++ $("#@(clientId + "remove")").click(function(e) {+ $("#@(clientId + "image")").html("<img src='@await pictureService.GetDefaultPictureUrl(targetPictureSize)' width='100' >");+ $("#@(clientId + "value") input").val('');+ $(".qq-upload-list").empty();+ $(this).hide();+ });+ });+</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Stores.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Stores.cshtmlsimilarity index 92%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Stores.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Stores.cshtmlindex 05cce6b56..d26c39631 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Stores.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Stores.cshtml@@ -2,6 +2,7 @@@model string[]@inject AccessControlConfig AccessControlConfig@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();var warnings = true;if (ViewData["DisableIgnoreStoreWarnings"] != null){@@ -23,7 +24,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("Stores", "Search", new { area = Constants.AreaAdmin, stores = Model }))"+ url: "@Html.Raw(Url.Action("Stores", "Search", new { area, stores = Model }))"}},schema: {diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Time.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Time.cshtmlsimilarity index 100%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Time.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Time.cshtmldiff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Vendor.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Vendor.cshtmlsimilarity index 85%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Vendor.cshtmlrename to src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Vendor.cshtmlindex 6998d3b44..86b7b8521 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Vendor.cshtml+++ b/src/Web/Grand.SharedUIResources/Views/Shared/EditorTemplates/Vendor.cshtml@@ -1,5 +1,7 @@@model string-+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}@Html.TextBoxFor(model => model, new { @class = "col-md-12", style = "width: 100%;" })<script>@@ -11,7 +13,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("Vendor", "Search", new { area = Constants.AreaAdmin, vendorId = Model }))"+ url: "@Html.Raw(Url.Action("Vendor", "Search", new { area, vendorId = Model }))"}},schema: {diff --git a/src/Web/Grand.SharedUIResources/Views/Shared/Partials/FineUploader.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/Partials/FineUploader.cshtmlnew file mode 100644index 000000000..14f5edc8e--- /dev/null+++ b/src/Web/Grand.SharedUIResources/Views/Shared/Partials/FineUploader.cshtml@@ -0,0 +1,2 @@+<link rel="stylesheet" type="text/css" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css" />+<script asp-location="Footer" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>\ No newline at end of filediff --git a/src/Web/Grand.SharedUIResources/Views/Shared/Partials/QqUploader.cshtml b/src/Web/Grand.SharedUIResources/Views/Shared/Partials/QqUploader.cshtmlnew file mode 100644index 000000000..4995aea69--- /dev/null+++ b/src/Web/Grand.SharedUIResources/Views/Shared/Partials/QqUploader.cshtml@@ -0,0 +1,29 @@+<div class="qq-uploader-selector qq-uploader">+ <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>+ <span>@Loc["Common.FileUploader.DropFiles"]</span>+ </div>+ <div class="qq-upload-button-selector qq-upload-button btn yellow" style="margin: 10px 0px 10px 0px;">+ <div>@Loc["Common.FileUploader.Upload"]</div>+ </div>+ <span class="qq-drop-processing-selector qq-drop-processing">+ <span>@Loc["Common.FileUploader.Processing"]</span>+ <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>+ </span>+ <ul class="qq-upload-list-selector qq-upload-list">+ <li>+ <div class="qq-progress-bar-container-selector">+ <div class="qq-progress-bar-selector qq-progress-bar"></div>+ </div>+ <span class="qq-upload-spinner-selector qq-upload-spinner"></span>+ <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>+ <span class="qq-upload-file-selector qq-upload-file"></span>+ <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">+ <span class="qq-upload-size-selector qq-upload-size"></span>+ <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>+ <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>+ <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>+ <span class="qq-upload-status-text-selector qq-upload-status-text"></span>+ <span class="qq-upload-status-message"></span>+ </li>+ </ul>+</div>\ No newline at end of filediff --git a/src/Web/Grand.SharedUIResources/Views/_ViewImports.cshtml b/src/Web/Grand.SharedUIResources/Views/_ViewImports.cshtmlnew file mode 100644index 000000000..16729dbd3--- /dev/null+++ b/src/Web/Grand.SharedUIResources/Views/_ViewImports.cshtml@@ -0,0 +1,10 @@+@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers+@addTagHelper *, Grand.Web.Common++@using System.Globalization+@using Microsoft.AspNetCore.Http.Extensions+@using Microsoft.AspNetCore.Mvc.ViewFeatures+@using System.Text++@using Grand.Web.Common.Localization+@inject LocService Loc\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Address.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Address.cshtmlindex 09bb7683e..43881fcb6 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Address.cshtml+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Address.cshtml@@ -209,7 +209,7 @@<div class="form-group"><admin-label asp-for="AddressType"/><div class="col-md-9 col-sm-9">- <select asp-for="AddressType" asp-items="EnumTranslationService.ToSelectList(AddressType.Any, false).ToList()" class="form-control custom-select"></select>+ <select asp-for="AddressType" asp-items="EnumTranslationService.ToSelectList(AddressType.Any, false)" class="form-control custom-select"></select><span asp-validation-for="AddressType"></span></div></div>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Category.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Category.cshtmldeleted file mode 100644index f30708da6..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Category.cshtml+++ /dev/null@@ -1,26 +0,0 @@-@model string-[email protected](model => model, new { @class = "col-md-8", style = "width: 100%;" })--<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDropDownList({- autobind: false,- optionLabel: "Select category...",- filter: "startswith",- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("Category", "Search", new { area = Constants.AreaAdmin, categoryId = Model }))"- }- },- schema: {- data: "Data"- },- serverFiltering: true- },- dataTextField: "Name",- dataValueField: "Id",- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/MultiPicture.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/MultiPicture.cshtmldeleted file mode 100644index df9b46e8b..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/MultiPicture.cshtml+++ /dev/null@@ -1,78 +0,0 @@-@using Constants = Grand.SharedUIResources.Constants-@model string-@{- var random = CommonHelper.GenerateRandomInteger();- var clientId = "multipicture" + random;-- var reference = ViewData["Reference"];- var objectId = ViewData["ObjectId"];- var endpoint = ViewData["Endpoint"];- var click = ViewData["Click"];-}-<link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css"/>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>--<div id="@clientId"></div>--<div id="@(clientId + "image")">-</div>-<script type="text/template" id="@(clientId)-qq-template">- <div class="qq-uploader-selector qq-uploader">- <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>- <span>@Loc["Common.FileUploader.DropFiles"]</span>- </div>- <div class="qq-upload-button-selector qq-upload-button btn yellow" style="margin: 10px 0px 10px 0px;">- <div>@Loc["Common.FileUploader.Upload"]</div>- </div>- <span class="qq-drop-processing-selector qq-drop-processing">- <span>@Loc["Common.FileUploader.Processing"]</span>- <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>- </span>- <ul class="qq-upload-list-selector qq-upload-list">- <li>- <div class="qq-progress-bar-container-selector">- <div class="qq-progress-bar-selector qq-progress-bar"></div>- </div>- <span class="qq-upload-spinner-selector qq-upload-spinner"></span>- <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>- <span class="qq-upload-file-selector qq-upload-file"></span>- <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">- <span class="qq-upload-size-selector qq-upload-size"></span>- <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>- <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>- <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>- <span class="qq-upload-status-text-selector qq-upload-status-text"></span>- <span class="qq-upload-status-message"></span>- </li>- </ul>- </div>-</script>--<script>- $(document).ready(function() {-- $("#@(clientId)").fineUploader({- request: {- endpoint: '@endpoint',- params: {- Reference: '@reference',- ObjectId: '@objectId'- }- },- template: "@(clientId)-qq-template",- multiple: true,- validation: {- itemLimit: 10,- acceptFiles: 'image/*',- }- }).on("complete", function(event, id, name, responseJSON, xhr) {- if (responseJSON.success) {- $("#@click").click();- }- else {- $('.qq-upload-status-message').text(responseJSON.message);- }- });-- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Picture.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Picture.cshtmldeleted file mode 100644index 86e03dffb..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/EditorTemplates/Picture.cshtml+++ /dev/null@@ -1,96 +0,0 @@-@using Grand.Business.Core.Interfaces.Storage-@using Constants = Grand.SharedUIResources.Constants-@model string-@inject IPictureService pictureService-@{- var random = CommonHelper.GenerateRandomInteger();- var clientId = "picture" + random;- var picture = await pictureService.GetPictureById(Model);- var targetPictureSize = 100;-}-<link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css"/>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>-<div id="@(clientId + "value")">- <input asp-for="@Model" type="hidden"/>-</div>-<div id="@(clientId + "image")">- <img src="@(await pictureService.GetPictureUrl(Model, targetPictureSize))"/>-</div>-@if (picture != null)-{- <span id="@(clientId + "remove")" class="btn red btn-outline margin-top-10">@Loc["Admin.Picture.RemovePicture"]</span>-}-else-{- <span id="@(clientId + "remove")" class="btn red btn-outline" style="display:none;">@Loc["Admin.Picture.RemovePicture"]</span>-}-<br/>-<div id="@clientId"></div>-<script type="text/template" id="@(clientId)-qq-template">- <div class="qq-uploader-selector qq-uploader">- <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>- <span>@Loc["Common.FileUploader.DropFiles"]</span>- </div>- <div class="qq-upload-button-selector qq-upload-button btn yellow" style="margin: 10px 0px 10px 0px;">- <div>@Loc["Common.FileUploader.Upload"]</div>- </div>- <span class="qq-drop-processing-selector qq-drop-processing">- <span>@Loc["Common.FileUploader.Processing"]</span>- <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>- </span>- <ul class="qq-upload-list-selector qq-upload-list">- <li>- <div class="qq-progress-bar-container-selector">- <div class="qq-progress-bar-selector qq-progress-bar"></div>- </div>- <span class="qq-upload-spinner-selector qq-upload-spinner"></span>- <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>- <span class="qq-upload-file-selector qq-upload-file"></span>- <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">- <span class="qq-upload-size-selector qq-upload-size"></span>- <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>- <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>- <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>- <span class="qq-upload-status-text-selector qq-upload-status-text"></span>- <span class="qq-upload-status-message"></span>- </li>- </ul>- </div>-</script>--<script>- $(document).ready(function() {-- $("#@(clientId)").fineUploader({- request: {- endpoint: '@(Url.Action("AsyncUpload", "Picture", new { area = Grand.Web.Admin.Extensions.Constants.AreaAdmin }))',- params: {- Reference: '@ViewData["Reference"]',- ObjectId: '@ViewData["ObjectId"]'- }- },- template: "@(clientId)-qq-template",- multiple: false,- validation: {- itemLimit: 5,- acceptFiles: 'image/*',- }- }).on("complete", function(event, id, name, responseJSON, xhr) {- if (responseJSON.success) {- $("#@(clientId + "image")").html("<img src='" + responseJSON.imageUrl + "' width='100' >");- $("#@(clientId + "value") input").val(responseJSON.pictureId);- $("#@(clientId + "remove")").show();- }- else {- $('.qq-upload-status-message').text(responseJSON.message);- }- });-- $("#@(clientId + "remove")").click(function(e) {- $("#@(clientId + "image")").html("<img src='@await pictureService.GetDefaultPictureUrl(targetPictureSize)' width='100' >");- $("#@(clientId + "value") input").val('');- $(".qq-upload-list").empty();- $(this).hide();- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs b/src/Web/Grand.Web.Admin/Controllers/DownloadController.csindex acd62df08..b29b4703a 100644--- a/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs@@ -6,6 +6,7 @@ using Grand.Web.Admin.Extensions;using Grand.Web.Common.Extensions;using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Http;namespace Grand.Web.Admin.Controllers;@@ -67,33 +68,17 @@ public class DownloadController : BaseAdminController[HttpPost]//do not validate request token (XSRF)[IgnoreAntiforgeryToken]- public virtual async Task<IActionResult> AsyncUpload(DownloadType downloadType = DownloadType.None,+ public virtual async Task<IActionResult> AsyncUpload(IFormFile file, DownloadType downloadType = DownloadType.None,string referenceId = ""){- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)+ if (file == null)return Json(new {success = false,message = "No file uploaded",downloadGuid = Guid.Empty});- var fileBinary = httpPostedFile.GetDownloadBits();-- var qqFileNameParameter = "qqfilename";- var fileName = httpPostedFile.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();-- fileName = Path.GetFileName(fileName);-- var contentType = httpPostedFile.ContentType;-- var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-+ var fileBinary = file.GetDownloadBits();var download = new Download {DownloadGuid = Guid.NewGuid(),@@ -101,9 +86,9 @@ public class DownloadController : BaseAdminControllerUseDownloadUrl = false,DownloadUrl = "",DownloadBinary = fileBinary,- ContentType = contentType,- Filename = Path.GetFileNameWithoutExtension(fileName),- Extension = fileExtension,+ ContentType = file.ContentType,+ Filename = Path.GetFileNameWithoutExtension(file.FileName),+ Extension = Path.GetExtension(file.FileName),DownloadType = downloadType,ReferenceId = referenceId};diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderController.csindex 8e621fc6e..ec867c382 100644--- a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs@@ -534,11 +534,9 @@ public class OrderController(return RedirectToAction("Edit", "Order", new { id });}- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == model.OrderItemId);- if (orderItem == null)- throw new ArgumentException("No order item found with the specified id");+ var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == model.OrderItemId) ?? throw new ArgumentException("No order item found with the specified id");+ var itemModel = model.Items.FirstOrDefault(x => x.Id == model.OrderItemId) ?? throw new ArgumentException("No order item model found with the specified id");- var itemModel = model.Items.FirstOrDefault(x => x.Id == model.OrderItemId);if (itemModel.Quantity == 0 || (orderItem.OpenQty != orderItem.Quantity && orderItem.IsShipEnabled)){Error("You can't change quantity");diff --git a/src/Web/Grand.Web.Admin/Controllers/PictureController.cs b/src/Web/Grand.Web.Admin/Controllers/PictureController.csindex 32620989c..d5c991705 100644--- a/src/Web/Grand.Web.Admin/Controllers/PictureController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PictureController.cs@@ -3,11 +3,12 @@ using Grand.Business.Core.Interfaces.Storage;using Grand.Domain.Permissions;using Grand.Domain.Common;using Grand.Domain.Media;-using Grand.Web.Admin.Extensions;using Grand.Web.Common.Extensions;using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.StaticFiles;+using Microsoft.AspNetCore.Http;+using Grand.SharedKernel.Extensions;namespace Grand.Web.Admin.Controllers;@@ -34,11 +35,9 @@ public class PictureController : BaseAdminController[HttpPost][IgnoreAntiforgeryToken]- public virtual async Task<IActionResult> AsyncUpload(Reference reference = Reference.None, string objectId = "")+ public virtual async Task<IActionResult> AsyncUpload(IFormFile file, Reference reference = Reference.None, string objectId = ""){- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)+ if (file == null)return Json(new {success = false,message = "No file uploaded",@@ -51,20 +50,9 @@ public class PictureController : BaseAdminControllerdownloadGuid = Guid.Empty});- var qqFileNameParameter = "qqfilename";- var fileName = httpPostedFile.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();- //remove path (passed in IE)- fileName = Path.GetFileName(fileName);-- var contentType = httpPostedFile.ContentType;-- var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-- if (!FileExtensions.GetAllowedMediaFileTypes(_mediaSettings.AllowedFileTypes).Contains(fileExtension))+ var fileName = Path.GetFileName(file.FileName);+ var contentType = file.ContentType;+ if (!FileExtensions.GetAllowedMediaFileTypes(_mediaSettings.AllowedFileTypes).IsAllowedMediaFileType(Path.GetExtension(fileName)))return Json(new {success = false,pictureId = "",@@ -73,7 +61,7 @@ public class PictureController : BaseAdminControllerif (string.IsNullOrEmpty(contentType))_ = new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);- var fileBinary = httpPostedFile.GetDownloadBits();+ var fileBinary = file.GetDownloadBits();var picture =await _pictureService.InsertPicture(fileBinary, contentType, null, reference: reference,objectId: objectId);@@ -88,34 +76,20 @@ public class PictureController : BaseAdminController[HttpPost][IgnoreAntiforgeryToken]- public virtual async Task<IActionResult> AsyncLogoUpload()+ public virtual async Task<IActionResult> AsyncLogoUpload(IFormFile file){if (!await _permissionService.Authorize(StandardPermission.ManageSettings))return Content("Access denied");- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)+ if (file == null)return Json(new {success = false,message = "No file uploaded"});-- var qqFileNameParameter = "qqfilename";- var fileName = httpPostedFile.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();-- fileName = Path.GetFileName(fileName);-- var contentType = httpPostedFile.ContentType;-- var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-- if (!FileExtensions.GetAllowedMediaFileTypes(_mediaSettings.AllowedFileTypes).Contains(fileExtension))+ var fileName = Path.GetFileName(file.FileName);+ var contentType = file.ContentType;+ if (!FileExtensions.GetAllowedMediaFileTypes(_mediaSettings.AllowedFileTypes).IsAllowedMediaFileType(Path.GetExtension(fileName)))return Json(new {success = false,message = "File no allowed"@@ -139,7 +113,7 @@ public class PictureController : BaseAdminControllerawait using (var stream = new FileStream(_mediaFileStore.Combine(filepath.PhysicalPath, fileName),FileMode.OpenOrCreate)){- await httpPostedFile.CopyToAsync(stream);+ await file.CopyToAsync(stream);}return Json(new {@@ -168,7 +142,7 @@ public class PictureController : BaseAdminControllerawait using (var stream = new FileStream(_mediaFileStore.Combine(filepath.PhysicalPath, fileName),FileMode.OpenOrCreate)){- await httpPostedFile.CopyToAsync(stream);+ await file.CopyToAsync(stream);}return Json(new {diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.csindex 148cf1b5b..5352359ca 100644--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs@@ -62,12 +62,14 @@ public class PluginController(if (string.IsNullOrEmpty(path))throw new ArgumentNullException(path);- //find more info about directory deletion- //and why we use this approach at https://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true+ // Ensure the path is within the PluginsPath+ if (!path.StartsWith(PluginsPath, StringComparison.Ordinal))+ throw new UnauthorizedAccessException("Attempt to delete a directory outside of the plugins path.");- foreach (var directory in Directory.GetDirectories(path)) DeleteDirectory(directory);+ foreach (var directory in Directory.GetDirectories(path))+ DeleteDirectory(directory);- if (Directory.Exists(path) && path.StartsWith(PluginsPath, StringComparison.Ordinal))+ if (Directory.Exists(path))Directory.Delete(path, true);}diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductController.csindex 85b6f30e0..ecb4a9353 100644--- a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs@@ -26,6 +26,7 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.StaticFiles;using Grand.Web.Common.Helpers;+using Grand.SharedKernel.Extensions;namespace Grand.Web.Admin.Controllers;@@ -1118,7 +1119,9 @@ public class ProductController : BaseAdminController[HttpPost][IgnoreAntiforgeryToken]- public async Task<IActionResult> ProductPictureAdd(Reference reference, string objectId,+ public async Task<IActionResult> ProductPictureAdd(+ IFormFileCollection files,+ Reference reference, string objectId,[FromServices] IPictureService pictureService,[FromServices] MediaSettings mediaSettings){@@ -1134,9 +1137,7 @@ public class ProductController : BaseAdminControllermessage = "Please save form before upload new pictures"});- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFiles = form.Files.ToList();- if (!httpPostedFiles.Any())+ if (!files.Any())return Json(new {success = false,message = "No files uploaded"@@ -1151,24 +1152,15 @@ public class ProductController : BaseAdminController});var values = new List<(string pictureUrl, string pictureId)>();- foreach (var file in httpPostedFiles)+ foreach (var file in files){- var qqFileNameParameter = "qqfilename";var fileName = file.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();-- fileName = Path.GetFileName(fileName);-var contentType = file.ContentType;var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-if (string.IsNullOrEmpty(contentType))_ = new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);- if (FileExtensions.GetAllowedMediaFileTypes(mediaSettings.AllowedFileTypes).Contains(fileExtension))+ if (FileExtensions.GetAllowedMediaFileTypes(mediaSettings.AllowedFileTypes).IsAllowedMediaFileType(fileExtension)){var fileBinary = file.GetDownloadBits();//insert picturediff --git a/src/Web/Grand.Web.Admin/Controllers/SearchController.cs b/src/Web/Grand.Web.Admin/Controllers/SearchController.csindex f8bee08f9..e8dabb6f4 100644--- a/src/Web/Grand.Web.Admin/Controllers/SearchController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/SearchController.cs@@ -10,15 +10,12 @@ using Grand.Business.Core.Interfaces.Common.Stores;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain;using Grand.Domain.Admin;-using Grand.Domain.Catalog;using Grand.Domain.Customers;-using Grand.Domain.Stores;-using Grand.Domain.Vendors;using Grand.Infrastructure;using Grand.Web.Admin.Extensions;-using Grand.Web.Admin.Models.Common;using Grand.Web.Admin.Models.Settings;using Grand.Web.Common.DataSource;+using Grand.Web.Common.Helpers;using Microsoft.AspNetCore.Mvc;namespace Grand.Web.Admin.Controllers;@@ -83,7 +80,8 @@ public class SearchController : BaseAdminControllervar products = (await _productService.SearchProducts(keywords: searchTerm,pageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden: true)).products;foreach (var product in products)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = product.Name,link = Url.Content($"~/{Constants.AreaAdmin}/Product/Edit/") + product.Id,source = _translationService.GetResource("Admin.Catalog.Products")@@ -96,7 +94,8 @@ public class SearchController : BaseAdminControllerpageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden:await _groupService.IsAdmin(_contextAccessor.WorkContext.CurrentCustomer));foreach (var category in categories)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = category.Name,link = Url.Content($"~/{Constants.AreaAdmin}/Category/Edit/") + category.Id,source = _translationService.GetResource("Admin.Catalog.Categories")@@ -108,7 +107,8 @@ public class SearchController : BaseAdminControllervar collections = await _collectionService.GetAllCollections(searchTerm,pageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden: true);foreach (var collection in collections)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = collection.Name,link = Url.Content($"~/{Constants.AreaAdmin}/Collection/Edit/") + collection.Id,source = _translationService.GetResource("Admin.Catalog.Collections")@@ -121,7 +121,8 @@ public class SearchController : BaseAdminController(x.SystemName != null && x.SystemName.ToLower().Contains(searchTerm.ToLower())) ||(x.Title != null && x.Title.ToLower().Contains(searchTerm.ToLower())));foreach (var page in pages)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = page.SystemName,link = Url.Content($"~/{Constants.AreaAdmin}/Page/Edit/") + page.Id,source = _translationService.GetResource("Admin.Content.Pages")@@ -133,7 +134,8 @@ public class SearchController : BaseAdminControllervar news = await _newsService.GetAllNews(newsTitle: searchTerm,pageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden: true);foreach (var signleNews in news)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = signleNews.Title,link = Url.Content($"~/{Constants.AreaAdmin}/News/Edit/") + signleNews.Id,source = _translationService.GetResource("Admin.Content.News")@@ -145,7 +147,8 @@ public class SearchController : BaseAdminControllervar blogPosts = await _blogService.GetAllBlogPosts(blogPostName: searchTerm,pageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden: true);foreach (var blogPost in blogPosts)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = blogPost.Title,link = Url.Content($"~/{Constants.AreaAdmin}/Blog/Edit/") + blogPost.Id,source = _translationService.GetResource("Admin.Content.Blog")@@ -164,7 +167,8 @@ public class SearchController : BaseAdminControllervar combined = customersByEmail.Union(customersByUsername).GroupBy(x => x.Email).Select(x => x.First());foreach (var customer in combined)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = customer.Email,link = Url.Content($"~/{Constants.AreaAdmin}/Customer/Edit/") + customer.Id,source = _translationService.GetResource("Admin.Customers")@@ -184,7 +188,8 @@ public class SearchController : BaseAdminControllerelseformatted += menuItem.grandParent + " > " + menuItem.parent;- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {menuItem.title,menuItem.link,source = formatted@@ -199,7 +204,8 @@ public class SearchController : BaseAdminController{var order = await _orderService.GetOrderByNumber(orderNumber);if (order != null)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = order.OrderNumber,link = Url.Content($"~/{Constants.AreaAdmin}/Order/Edit/") + order.Id,source = _translationService.GetResource("Admin.Orders")@@ -208,7 +214,8 @@ public class SearchController : BaseAdminControllervar orders = await _orderService.GetOrdersByCode(searchTerm);foreach (var order in orders)- result.Add(new Tuple<object, int>(new {+ result.Add(new Tuple<object, int>(new+ {title = order.Code,link = Url.Content($"~/{Constants.AreaAdmin}/Order/Edit/") + order.Id,source = _translationService.GetResource("Admin.Orders")@@ -221,227 +228,81 @@ public class SearchController : BaseAdminController[HttpGet]- public async Task<IActionResult> Category(string categoryId)+ public async Task<IActionResult> Category(string categoryId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Category> categories)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(categoryId))- {- var currentCategory = await _categoryService.GetCategoryById(categoryId);- if (currentCategory != null)- model.Add(new SearchModel {- Id = currentCategory.Id,- Name = await _categoryService.GetFormattedBreadCrumb(currentCategory)- });- }-- foreach (var item in categories)- if (item.Id != categoryId)- model.Add(new SearchModel {- Id = item.Id,- Name = await _categoryService.GetFormattedBreadCrumb(item)- });- return model;- }-- var storeId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;-var categories = await _categoryService.GetAllCategories(- storeId: storeId,- categoryName: value,- pageSize: _adminSearchSettings.CategorySizeLimit);- var gridModel = new DataSourceResult {- Data = await PrepareModel(categories)- };+ parentId: null,+ categoryName: model.GetNameFilterValue(),+ storeId: "",+ pageIndex: 0,+ pageSize: _adminSearchSettings.CategorySizeLimit,+ showHidden: false+ );++ var gridModel = await DataSourceResultHelper.GetSearchResult(categoryId, categories, async category => await _categoryService.GetFormattedBreadCrumb(category));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Collection(string collectionId)+ public async Task<IActionResult> Collection(string collectionId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Collection> collections)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(collectionId))- {- var currentCollection = await _collectionService.GetCollectionById(collectionId);- if (currentCollection != null)- model.Add(new SearchModel {- Id = currentCollection.Id,- Name = currentCollection.Name- });- }-- foreach (var item in collections)- if (item.Id != collectionId)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- return model;- }-- var storeId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;-var collections = await _collectionService.GetAllCollections(- storeId: storeId,- collectionName: value,- pageSize: _adminSearchSettings.CollectionSizeLimit);-- var gridModel = new DataSourceResult {- Data = await PrepareModel(collections)- };+ collectionName: model.GetNameFilterValue(),+ storeId: "",+ pageIndex: 0,+ pageSize: _adminSearchSettings.CollectionSizeLimit,+ showHidden: false+ );++ var gridModel = await DataSourceResultHelper.GetSearchResult(collectionId, collections, collection => Task.FromResult(collection.Name));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> CustomerGroup(string[] customerGroups)+ public async Task<IActionResult> CustomerGroup(string customerGroupId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<CustomerGroup> groups)- {- var model = new List<SearchModel>();- if (customerGroups != null && customerGroups.Any())- {- var currentGroups = await _groupService.GetAllByIds(customerGroups);- foreach (var item in currentGroups)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- }-- foreach (var item in groups)- if (model.FirstOrDefault(x => x.Id == item.Id) == null)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- return model;- }-var groups = await _groupService.GetAllCustomerGroups(- value,+ model.GetNameFilterValue(),pageSize: _adminSearchSettings.CustomerGroupSizeLimit);- var gridModel = new DataSourceResult {- Data = await PrepareModel(groups)- };+ var gridModel = await DataSourceResultHelper.GetSearchResult(customerGroupId, groups, store => Task.FromResult(store.Name));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Stores(string[] stores)+ public async Task<IActionResult> Stores(string storeId, DataSourceRequestFilter model){- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Store> groups)- {- var model = new List<SearchModel>();- if (stores != null && stores.Any())- foreach (var item in stores)- {- var currentStore = await _storeService.GetStoreById(item);- if (currentStore != null)- model.Add(new SearchModel {- Id = currentStore.Id,- Name = currentStore.Name- });- }-- foreach (var item in groups)- if (model.FirstOrDefault(x => x.Id == item.Id) == null)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- return model;- }+ var stores = await _storeService.GetAllStores();+ var staffStoreId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;+ if (!string.IsNullOrEmpty(staffStoreId))+ stores = stores.Where(x => x.Id == staffStoreId).ToList();- var groups = await _storeService.GetAllStores();- var storeId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;- if (!string.IsNullOrEmpty(storeId))- groups = groups.Where(x => x.Id == storeId).ToList();+ if (model.GetNameFilterValue() != null)+ stores = stores.Where(x => x.Name.Contains(model.GetNameFilterValue(), StringComparison.InvariantCultureIgnoreCase)).ToList();- var gridModel = new DataSourceResult {- Data = await PrepareModel(groups)- };+ var gridModel = await DataSourceResultHelper.GetSearchResult(storeId, stores, store => Task.FromResult(store.Name));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Vendor(string vendorId)+ public async Task<IActionResult> Vendor(string vendorId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Vendor> vendors)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(vendorId))- {- var vendor = await _vendorService.GetVendorById(vendorId);- if (vendor != null)- model.Add(new SearchModel {- Id = vendor.Id,- Name = vendor.Name- });- }-- foreach (var item in vendors)- if (item.Id != vendorId)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- return model;- }-var vendors = await _vendorService.GetAllVendors(- value,+ model.GetNameFilterValue(),pageSize: _adminSearchSettings.VendorSizeLimit, showHidden: true);- var gridModel = new DataSourceResult {- Data = await PrepareModel(vendors)- };++ var gridModel = await DataSourceResultHelper.GetSearchResult(vendorId, vendors, vendor => Task.FromResult(vendor.Name));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Brand(string brandId)+ public async Task<IActionResult> Brand(string brandId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Brand> brands)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(brandId))- {- var currentBrand = await _brandService.GetBrandById(brandId);- if (currentBrand != null)- model.Add(new SearchModel {- Id = currentBrand.Id,- Name = currentBrand.Name- });- }-- foreach (var item in brands)- if (item.Id != brandId)- model.Add(new SearchModel {- Id = item.Id,- Name = item.Name- });- return model;- }-var brands = await _brandService.GetAllBrands(- value,+ model.GetNameFilterValue(),pageSize: _adminSearchSettings.BrandSizeLimit);- var gridModel = new DataSourceResult {- Data = await PrepareModel(brands)- };++ var gridModel = await DataSourceResultHelper.GetSearchResult(brandId, brands, brand => Task.FromResult(brand.Name));return Json(gridModel);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Models/Common/SearchModel.cs b/src/Web/Grand.Web.Admin/Models/Common/SearchModel.csdeleted file mode 100644index fc1739ddd..000000000--- a/src/Web/Grand.Web.Admin/Models/Common/SearchModel.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace Grand.Web.Admin.Models.Common;--public class SearchModel-{- public string Id { get; set; }- public string Name { get; set; }-}\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs b/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.csindex 403270b1c..e8031f407 100644--- a/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs@@ -112,7 +112,8 @@ public class AffiliateViewModelService : IAffiliateViewModelServicevar states = !string.IsNullOrEmpty(model.Address.CountryId)? (await _countryService.GetCountryById(model.Address.CountryId))?.StateProvinces: new List<StateProvince>();- if (states.Count > 0)++ if (states?.Count > 0)foreach (var s in states)model.Address.AvailableStates.Add(new SelectListItem {Text = s.Name, Value = s.Id,diff --git a/src/Web/Grand.Web.Admin/Services/MerchandiseReturnViewModelService.cs b/src/Web/Grand.Web.Admin/Services/MerchandiseReturnViewModelService.csindex c20bc83cc..e525490b2 100644--- a/src/Web/Grand.Web.Admin/Services/MerchandiseReturnViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/MerchandiseReturnViewModelService.cs@@ -174,7 +174,8 @@ public class MerchandiseReturnViewModelService(var states = !string.IsNullOrEmpty(model.CountryId)? (await countryService.GetCountryById(model.CountryId))?.StateProvinces: new List<StateProvince>();- if (states.Count > 0)++ if (states?.Count > 0)foreach (var s in states)model.AvailableStates.Add(new SelectListItem{ Text = s.Name, Value = s.Id, Selected = s.Id == model.StateProvinceId });diff --git a/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs b/src/Web/Grand.Web.Admin/Services/VendorViewModelService.csindex 4438c2369..37490c56a 100644--- a/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs@@ -113,7 +113,7 @@ public class VendorViewModelService(var states = !string.IsNullOrEmpty(model.Address.CountryId)? (await countryService.GetCountryById(model.Address.CountryId))?.StateProvinces: new List<StateProvince>();- if (states.Count > 0)+ if (states?.Count > 0)foreach (var s in states)model.Address.AvailableStates.Add(new SelectListItem {Text = s.Name, Value = s.Id, Selected = vendor != null && s.Id == vendor.Address.StateProvinceIddiff --git a/src/Web/Grand.Web.Admin/Validators/Affiliate/AffiliateDeleteValidator.cs b/src/Web/Grand.Web.Admin/Validators/Affiliate/AffiliateDeleteValidator.csindex b2f25d211..42eeb50b2 100644--- a/src/Web/Grand.Web.Admin/Validators/Affiliate/AffiliateDeleteValidator.cs+++ b/src/Web/Grand.Web.Admin/Validators/Affiliate/AffiliateDeleteValidator.cs@@ -20,7 +20,10 @@ public class AffiliateDeleteValidator : BaseGrandValidator<AffiliateDeleteModel>{var affiliate = await affiliateService.GetAffiliateById(x.Id);if (affiliate == null)+ {context.AddFailure("No affiliate found with the specified id");+ return;+ }var customers = new GetCustomerQuery {AffiliateId = affiliate.Id,diff --git a/src/Web/Grand.Web.Admin/Validators/Common/LoginValidator.cs b/src/Web/Grand.Web.Admin/Validators/Common/LoginValidator.csindex 23816bba9..f599397ec 100644--- a/src/Web/Grand.Web.Admin/Validators/Common/LoginValidator.cs+++ b/src/Web/Grand.Web.Admin/Validators/Common/LoginValidator.cs@@ -65,7 +65,7 @@ public class LoginValidator : BaseGrandValidator<LoginModel>translationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));break;case { CannotLoginUntilDateUtc: not null }- when customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:+ when customer!.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:context.AddFailure(translationService.GetResource("Account.Login.WrongCredentials.LockedOut"));break;case not null:diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.csindex ca1ae983f..a52f9eb5c 100644--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs@@ -79,15 +79,13 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>RuleFor(x => x).Custom((x, context) =>{- if (!string.IsNullOrEmpty(x.Password))- if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))- {- var passwordRegex = new Regex(customerSettings.PasswordRegularExpression);- if (!passwordRegex.Match(x.Password).Success)- context.AddFailure(translationService.GetResource("Account.Fields.Password.Validation"));- }-- if (string.IsNullOrWhiteSpace(x.Username) & customerSettings.UsernamesEnabled)+ if (!string.IsNullOrEmpty(x.Password) && !string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))+ {+ var passwordRegex = new Regex(customerSettings.PasswordRegularExpression, RegexOptions.Compiled, TimeSpan.FromSeconds(1));+ if (!passwordRegex.Match(x.Password).Success)+ context.AddFailure(translationService.GetResource("Account.Fields.Password.Validation"));+ }+ if (string.IsNullOrWhiteSpace(x.Username) && customerSettings.UsernamesEnabled)context.AddFailure("The username cannot be empty");});diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.csindex afa1d98f9..0b01f8dac 100644--- a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs+++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs@@ -26,7 +26,7 @@ public class CustomAttributesBinder : IModelBinderprivate static string GetKey(string key){- var regex = new Regex("\\[(?<Value>\\w+)\\]");+ var regex = new Regex("\\[(?<Value>\\w+)\\]", RegexOptions.Compiled, TimeSpan.FromSeconds(1));string value = null;var match = regex.Match(key);if (match.Success) value = match.Groups["Value"].Value;diff --git a/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.cs b/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.csnew file mode 100644index 000000000..063c484aa--- /dev/null+++ b/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.cs@@ -0,0 +1,50 @@+using Grand.Web.Common.DataSource;+using Microsoft.AspNetCore.Mvc.ModelBinding;+using static Grand.Web.Common.DataSource.DataSourceRequestFilter;++namespace Grand.Web.Common.Binders;++public class DataSourceRequestFilterBinder : IModelBinder+{+ public Task BindModelAsync(ModelBindingContext bindingContext)+ {+ if (bindingContext == null)+ throw new ArgumentNullException(nameof(bindingContext));++ var query = bindingContext.HttpContext.Request.Query;+ var model = new DataSourceRequestFilter();++ if (query.ContainsKey("filter[logic]"))+ model.Logic = query["filter[logic]"].FirstOrDefault();++ var filters = new List<FilterDescriptor>();+ var index = 0;+ while (true)+ {+ var fieldKey = $"filter[filters][{index}][field]";+ if (!query.ContainsKey(fieldKey))+ break;++ var operKey = $"filter[filters][{index}][operator]";+ var valueKey = $"filter[filters][{index}][value]";+ var ignoreCaseKey = $"filter[filters][{index}][ignoreCase]";++ var field = query[fieldKey].FirstOrDefault();+ var oper = query.ContainsKey(operKey) ? query[operKey].FirstOrDefault() : null;+ var value = query.ContainsKey(valueKey) ? query[valueKey].FirstOrDefault() : null;+ var ignoreCase = query.ContainsKey(ignoreCaseKey) && bool.TryParse(query[ignoreCaseKey].FirstOrDefault(), out var ic) && ic;++ filters.Add(new FilterDescriptor {+ Field = field,+ Operator = oper,+ Value = value,+ IgnoreCase = ignoreCase+ });+ index++;+ }+ model.Filters = filters;++ bindingContext.Result = ModelBindingResult.Success(model);+ return Task.CompletedTask;+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs b/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.csnew file mode 100644index 000000000..3bad0593b--- /dev/null+++ b/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs@@ -0,0 +1,27 @@+using Grand.Web.Common.Binders;+using Microsoft.AspNetCore.Mvc;++namespace Grand.Web.Common.DataSource;++[ModelBinder(BinderType = typeof(DataSourceRequestFilterBinder))]+public class DataSourceRequestFilter+{+ public string Logic { get; set; }+ public List<FilterDescriptor> Filters { get; set; }++ public class FilterDescriptor+ {+ public string Field { get; set; }+ public string Operator { get; set; }+ public string Value { get; set; }+ public bool IgnoreCase { get; set; }+ }+}++public static class DataSourceRequestFilterExtensions+{+ public static string GetNameFilterValue(this DataSourceRequestFilter filter)+ {+ return filter.Filters.FirstOrDefault(x => x.Field == "Name")?.Value;+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.csindex a9df12e06..d4c29f38a 100644--- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs@@ -126,7 +126,7 @@ public class LanguageAttribute : TypeFilterAttributeif (!string.IsNullOrEmpty(url)) url = Url.EncodeIllegalCharacters(url);//add language code- url = $"/{language.UniqueSeoCode}/{url.TrimStart('/')}";+ url = $"/{language.UniqueSeoCode}/{url?.TrimStart('/')}";return url;}diff --git a/src/Web/Grand.Web.Common/Helpers/DataSourceResultHelper.cs b/src/Web/Grand.Web.Common/Helpers/DataSourceResultHelper.csnew file mode 100644index 000000000..b727b7fe9--- /dev/null+++ b/src/Web/Grand.Web.Common/Helpers/DataSourceResultHelper.cs@@ -0,0 +1,35 @@+using Grand.Domain;+using Grand.Web.Common.DataSource;++namespace Grand.Web.Common.Helpers;+public static class DataSourceResultHelper+{+ public static async Task<DataSourceResult> GetSearchResult<T>(+ string id, IEnumerable<T> items, Func<T, Task<string>> getName) where T : BaseEntity+ {+ var searchModels = new List<SearchModel>();++ if (!string.IsNullOrEmpty(id))+ {+ var currentItem = items.FirstOrDefault(item => item.Id == id);+ if (currentItem != null)+ {+ searchModels.Add(new SearchModel(currentItem.Id, await getName(currentItem)));+ }+ }++ foreach (var item in items)+ {+ if (item.Id != id)+ {+ searchModels.Add(new SearchModel(item.Id, await getName(item)));+ }+ }++ return new DataSourceResult {+ Data = searchModels,+ Total = searchModels.Count+ };+ }+ private sealed record SearchModel(string Id, string Name);+}diff --git a/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs b/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.csindex 8ba74e4fe..1ab398b32 100644--- a/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs+++ b/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs@@ -21,7 +21,7 @@ public class NoScriptsAttribute : ValidationAttributeprivate static bool ContainsScript(string input){- var scriptRegex = new Regex(Pattern, RegexOptions.IgnoreCase);+ var scriptRegex = new Regex(Pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));return scriptRegex.IsMatch(input);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Brand.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Brand.cshtmldeleted file mode 100644index c14bb165c..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Brand.cshtml+++ /dev/null@@ -1,26 +0,0 @@-@model string-[email protected](model => model, new { @class = "col-md-12", style = "width: 100%;" })--<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDropDownList({- autobind: false,- optionLabel: "Select brand...",- filter: "startswith",- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("Brand", "Search", new { area = Constants.AreaVendor, brandId = Model }))"- }- },- schema: {- data: "Data"- },- serverFiltering: true- },- dataTextField: "Name",- dataValueField: "Id",- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Collection.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Collection.cshtmldeleted file mode 100644index c25197528..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Collection.cshtml+++ /dev/null@@ -1,26 +0,0 @@-@model string-[email protected](model => model, new { @class = "col-md-8", style = "width: 100%;" })--<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDropDownList({- autobind: false,- optionLabel: "Select collection...",- filter: "startswith",- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("Collection", "Search", new { area = Constants.AreaVendor, collectionId = Model }))"- }- },- schema: {- data: "Data"- },- serverFiltering: true- },- dataTextField: "Name",- dataValueField: "Id",- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Date.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Date.cshtmldeleted file mode 100644index 901898509..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Date.cshtml+++ /dev/null@@ -1,9 +0,0 @@-@model DateTime-<input asp-for="@Model"/>-<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDatePicker({- culture: "@CultureInfo.CurrentCulture.Name"- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateNullable.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateNullable.cshtmldeleted file mode 100644index 19a14fe9f..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateNullable.cshtml+++ /dev/null@@ -1,9 +0,0 @@-@model DateTime?-<input asp-for="@Model"/>-<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDatePicker({- culture: "@CultureInfo.CurrentCulture.Name"- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTime.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTime.cshtmldeleted file mode 100644index 912ddec53..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTime.cshtml+++ /dev/null@@ -1,10 +0,0 @@-@model DateTime-<input id="@Html.IdForModel()" name="@Html.NameForModel()" value="@(Model)"/>--<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDateTimePicker({- culture: "@CultureInfo.CurrentCulture.Name"- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTimeNullable.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTimeNullable.cshtmldeleted file mode 100644index dd875ebf1..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DateTimeNullable.cshtml+++ /dev/null@@ -1,9 +0,0 @@-@model DateTime?-<input id="@Html.IdForModel()" name="@Html.NameForModel()" value="@(Model.HasValue ? Model.Value : "")"/>-<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoDateTimePicker({- culture: "@CultureInfo.CurrentCulture.Name"- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Decimal.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Decimal.cshtmldeleted file mode 100644index 18ee418b4..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Decimal.cshtml+++ /dev/null@@ -1,15 +0,0 @@-@model decimal-<input asp-for="@Model"/>-<script>- $(document).ready(function() {- try {- $("#@Html.IdForModel()").rules("remove", 'number');- }- catch {}- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n2',- decimals: 2- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalN4.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalN4.cshtmldeleted file mode 100644index 0c6a3ecf1..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalN4.cshtml+++ /dev/null@@ -1,15 +0,0 @@-@model decimal-<input asp-for="@Model"/>-<script>- $(document).ready(function() {- try {- $("#@Html.IdForModel()").rules("remove", 'number');- }- catch {}- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n4',- decimals: 4- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalNullable.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalNullable.cshtmldeleted file mode 100644index 3d9877a22..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DecimalNullable.cshtml+++ /dev/null@@ -1,15 +0,0 @@-@model decimal?-<input asp-for="@Model"/>-<script>- $(document).ready(function () {- try {- $("#@Html.IdForModel()").rules("remove", 'number');- }- catch {}- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n2',- decimals: 2- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Double.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Double.cshtmldeleted file mode 100644index df4670e48..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Double.cshtml+++ /dev/null@@ -1,15 +0,0 @@-@model double-<input asp-for="@Model"/>-<script>- $(document).ready(function () {- try {- $("#@Html.IdForModel()").rules("remove", 'number');- }- catch {}- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n2',- decimals: 2- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleN4.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleN4.cshtmldeleted file mode 100644index 403a0f09b..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleN4.cshtml+++ /dev/null@@ -1,11 +0,0 @@-@model double-<input asp-for="@Model"/>-<script>- $(document).ready(function() {- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n4',- decimals: 4- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleNullable.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleNullable.cshtmldeleted file mode 100644index f4cfbee15..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/DoubleNullable.cshtml+++ /dev/null@@ -1,11 +0,0 @@-@model double?-<input asp-for="@Model"/>-<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoNumericTextBox({- culture: "@CultureInfo.CurrentCulture.Name",- format: 'n2',- decimals: 2- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32.cshtmldeleted file mode 100644index f21e8f861..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32.cshtml+++ /dev/null@@ -1,11 +0,0 @@-@model int-[email protected](model => model)-<script>- $(document).ready(function() {- $("#@Html.IdForModel()").kendoNumericTextBox({- format: "#",- decimals: 0- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32Nullable.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32Nullable.cshtmldeleted file mode 100644index f5f86f7ec..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Int32Nullable.cshtml+++ /dev/null@@ -1,11 +0,0 @@-@model int?-[email protected](model => model)-<script>- $(document).ready(function() {- $("#@Html.IdForModel()").kendoNumericTextBox({- format: "#",- decimals: 0- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiPicture.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiPicture.cshtmldeleted file mode 100644index df9b46e8b..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiPicture.cshtml+++ /dev/null@@ -1,78 +0,0 @@-@using Constants = Grand.SharedUIResources.Constants-@model string-@{- var random = CommonHelper.GenerateRandomInteger();- var clientId = "multipicture" + random;-- var reference = ViewData["Reference"];- var objectId = ViewData["ObjectId"];- var endpoint = ViewData["Endpoint"];- var click = ViewData["Click"];-}-<link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css"/>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>--<div id="@clientId"></div>--<div id="@(clientId + "image")">-</div>-<script type="text/template" id="@(clientId)-qq-template">- <div class="qq-uploader-selector qq-uploader">- <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>- <span>@Loc["Common.FileUploader.DropFiles"]</span>- </div>- <div class="qq-upload-button-selector qq-upload-button btn yellow" style="margin: 10px 0px 10px 0px;">- <div>@Loc["Common.FileUploader.Upload"]</div>- </div>- <span class="qq-drop-processing-selector qq-drop-processing">- <span>@Loc["Common.FileUploader.Processing"]</span>- <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>- </span>- <ul class="qq-upload-list-selector qq-upload-list">- <li>- <div class="qq-progress-bar-container-selector">- <div class="qq-progress-bar-selector qq-progress-bar"></div>- </div>- <span class="qq-upload-spinner-selector qq-upload-spinner"></span>- <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>- <span class="qq-upload-file-selector qq-upload-file"></span>- <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">- <span class="qq-upload-size-selector qq-upload-size"></span>- <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>- <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>- <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>- <span class="qq-upload-status-text-selector qq-upload-status-text"></span>- <span class="qq-upload-status-message"></span>- </li>- </ul>- </div>-</script>--<script>- $(document).ready(function() {-- $("#@(clientId)").fineUploader({- request: {- endpoint: '@endpoint',- params: {- Reference: '@reference',- ObjectId: '@objectId'- }- },- template: "@(clientId)-qq-template",- multiple: true,- validation: {- itemLimit: 10,- acceptFiles: 'image/*',- }- }).on("complete", function(event, id, name, responseJSON, xhr) {- if (responseJSON.success) {- $("#@click").click();- }- else {- $('.qq-upload-status-message').text(responseJSON.message);- }- });-- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiSelect.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiSelect.cshtmldeleted file mode 100644index f9c056a40..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/MultiSelect.cshtml+++ /dev/null@@ -1,25 +0,0 @@-@model List<string>[email protected](model => model, (IEnumerable<SelectListItem>)ViewData["SelectList"])-<script>- $(document).ready(function() {- $("#@Html.IdForModel()").kendoMultiSelect({- select: function (e) {- var current = this.value();- if (this.dataSource.view()[e.item.index()].value === "0") {- this.value("");- }- else if (current.indexOf("0") !== -1) {- current = $.grep(current, function (value) {- return value !== "0";- });-- this.value(current);- }- },- change: function (e) {- if (this.value().length === 0)- this.value(["0"]);- }- }).data("kendoMultiSelect");- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Picture.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Picture.cshtmldeleted file mode 100644index 54707f0fc..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Picture.cshtml+++ /dev/null@@ -1,96 +0,0 @@-@using Grand.Business.Core.Interfaces.Storage-@using Constants = Grand.SharedUIResources.Constants-@model string-@inject IPictureService pictureService-@{- var random = CommonHelper.GenerateRandomInteger();- var clientId = "picture" + random;- var picture = await pictureService.GetPictureById(Model);- var targetPictureSize = 100;-}-<link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/fineuploader/fineuploader-4.2.2.min.css"/>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/fineuploader/jquery.fineuploader-4.2.2.min.js"></script>-<div id="@(clientId + "value")">- <input asp-for="@Model" type="hidden"/>-</div>-<div id="@(clientId + "image")">- <img src="@(await pictureService.GetPictureUrl(Model, targetPictureSize))"/>-</div>-@if (picture != null)-{- <span id="@(clientId + "remove")" class="btn red btn-outline margin-top-10">@Loc["Vendor.Picture.RemovePicture"]</span>-}-else-{- <span id="@(clientId + "remove")" class="btn red btn-outline" style="display:none;">@Loc["Vendor.Picture.RemovePicture"]</span>-}-<br/>-<div id="@clientId"></div>-<script type="text/template" id="@(clientId)-qq-template">- <div class="qq-uploader-selector qq-uploader">- <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>- <span>@Loc["Common.FileUploader.DropFiles"]</span>- </div>- <div class="qq-upload-button-selector qq-upload-button btn yellow" style="margin: 10px 0px 10px 0px;">- <div>@Loc["Common.FileUploader.Upload"]</div>- </div>- <span class="qq-drop-processing-selector qq-drop-processing">- <span>@Loc["Common.FileUploader.Processing"]</span>- <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>- </span>- <ul class="qq-upload-list-selector qq-upload-list">- <li>- <div class="qq-progress-bar-container-selector">- <div class="qq-progress-bar-selector qq-progress-bar"></div>- </div>- <span class="qq-upload-spinner-selector qq-upload-spinner"></span>- <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>- <span class="qq-upload-file-selector qq-upload-file"></span>- <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">- <span class="qq-upload-size-selector qq-upload-size"></span>- <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@Loc["Common.FileUploader.Cancel"]</a>- <a class="qq-upload-retry-selector qq-upload-retry" href="#">@Loc["Common.FileUploader.Retry"]</a>- <a class="qq-upload-delete-selector qq-upload-delete" href="#">@Loc["Common.FileUploader.Delete"]</a>- <span class="qq-upload-status-text-selector qq-upload-status-text"></span>- <span class="qq-upload-status-message"></span>- </li>- </ul>- </div>-</script>--<script>- $(document).ready(function() {-- $("#@(clientId)").fineUploader({- request: {- endpoint: '@(Url.Action("AsyncUpload", "Picture", new { area = Grand.Web.Vendor.Extensions.Constants.AreaVendor }))',- params: {- Reference: '@ViewData["Reference"]',- ObjectId: '@ViewData["ObjectId"]'- }- },- template: "@(clientId)-qq-template",- multiple: false,- validation: {- itemLimit: 5,- acceptFiles: 'image/*',- }- }).on("complete", function(event, id, name, responseJSON, xhr) {- if (responseJSON.success) {- $("#@(clientId + "image")").html("<img src='" + responseJSON.imageUrl + "' width='100' >");- $("#@(clientId + "value") input").val(responseJSON.pictureId);- $("#@(clientId + "remove")").show();- }- else {- $('.qq-upload-status-message').text(responseJSON.message);- }- });-- $("#@(clientId + "remove")").click(function(e) {- $("#@(clientId + "image")").html("<img src='@await pictureService.GetDefaultPictureUrl(targetPictureSize)' width='100' >");- $("#@(clientId + "value") input").val('');- $(".qq-upload-list").empty();- $(this).hide();- });- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Time.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Time.cshtmldeleted file mode 100644index d8c387f00..000000000--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/EditorTemplates/Time.cshtml+++ /dev/null@@ -1,8 +0,0 @@-@model DateTime-<input id="@Html.IdForModel()" name="@Html.NameForModel()" value="@((Model > DateTime.MinValue ? Model : DateTime.Today).ToString("HH:mm"))"/>-<script>- $(document).ready(function () {- $("#@Html.IdForModel()").kendoTimePicker({ format: "HH:mm" });- });--</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs b/src/Web/Grand.Web.Vendor/Controllers/ProductController.csindex 202d45ab3..ed4438b51 100644--- a/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs+++ b/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs@@ -23,6 +23,8 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.StaticFiles;using Grand.Web.Common.Helpers;+using Microsoft.AspNetCore.Http;+using Grand.SharedKernel.Extensions;namespace Grand.Web.Vendor.Controllers;@@ -1076,7 +1078,9 @@ public class ProductController : BaseVendorController[HttpPost][IgnoreAntiforgeryToken]- public async Task<IActionResult> ProductPictureAdd(Reference reference, string objectId,+ public async Task<IActionResult> ProductPictureAdd(+ IFormFileCollection files,+ Reference reference, string objectId,[FromServices] IPictureService pictureService,[FromServices] MediaSettings mediaSettings){@@ -1092,9 +1096,7 @@ public class ProductController : BaseVendorControllermessage = "Please save form before upload new pictures"});- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFiles = form.Files.ToList();- if (!httpPostedFiles.Any())+ if (!files.Any())return Json(new {success = false,message = "No files uploaded"@@ -1110,24 +1112,16 @@ public class ProductController : BaseVendorController});var values = new List<(string pictureUrl, string pictureId)>();- foreach (var file in httpPostedFiles)+ foreach (var file in files){- var qqFileNameParameter = "qqfilename";- var fileName = file.FileName;- if (string.IsNullOrEmpty(fileName) && form.ContainsKey(qqFileNameParameter))- fileName = form[qqFileNameParameter].ToString();-- fileName = Path.GetFileName(fileName);-+ var fileName = Path.GetFileName(file.FileName);var contentType = file.ContentType;var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();if (string.IsNullOrEmpty(contentType))_ = new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);- if (FileExtensions.GetAllowedMediaFileTypes(mediaSettings.AllowedFileTypes).Contains(fileExtension))+ if (SharedKernel.Extensions.FileExtensions.GetAllowedMediaFileTypes(mediaSettings.AllowedFileTypes).IsAllowedMediaFileType(fileExtension)){var fileBinary = file.GetDownloadBits();//insert picturediff --git a/src/Web/Grand.Web.Vendor/Controllers/SearchController.cs b/src/Web/Grand.Web.Vendor/Controllers/SearchController.csindex 1214d9279..f79d52362 100644--- a/src/Web/Grand.Web.Vendor/Controllers/SearchController.cs+++ b/src/Web/Grand.Web.Vendor/Controllers/SearchController.cs@@ -2,9 +2,8 @@using Grand.Business.Core.Interfaces.Catalog.Categories;using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Domain.Admin;-using Grand.Domain.Catalog;using Grand.Web.Common.DataSource;-using Grand.Web.Vendor.Models.Common;+using Grand.Web.Common.Helpers;using Microsoft.AspNetCore.Mvc;namespace Grand.Web.Vendor.Controllers;@@ -27,105 +26,48 @@ public class SearchController : BaseVendorController}[HttpGet]- public async Task<IActionResult> Category(string categoryId)+ public async Task<IActionResult> Category(string categoryId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Category> categories)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(categoryId))- {- var currentCategory = await _categoryService.GetCategoryById(categoryId);- if (currentCategory != null)- model.Add(new SearchModel {- Id = currentCategory.Id,- Name = await _categoryService.GetFormattedBreadCrumb(currentCategory)- });- }-- foreach (var item in categories)- if (item.Id != categoryId)- model.Add(new SearchModel {- Id = item.Id,- Name = await _categoryService.GetFormattedBreadCrumb(item)- });- return model;- }-var categories = await _categoryService.GetAllCategories(- categoryName: value,- pageSize: _adminSearchSettings.CategorySizeLimit);- var gridModel = new DataSourceResult {- Data = await PrepareModel(categories)- };+ parentId: null,+ categoryName: model.GetNameFilterValue(),+ storeId: "",+ pageIndex: 0,+ pageSize: _adminSearchSettings.CategorySizeLimit,+ showHidden: false+ );++ var gridModel = await DataSourceResultHelper.GetSearchResult(categoryId, categories, async category => await _categoryService.GetFormattedBreadCrumb(category));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Collection(string collectionId)+ public async Task<IActionResult> Collection(string collectionId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Collection> collections)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(collectionId))- {- var currentCollection = await _collectionService.GetCollectionById(collectionId);- if (currentCollection != null)- model.Add(new SearchModel {- Id = currentCollection.Id,- Name = currentCollection.Name- });- }-- model.AddRange(from item in collections- where item.Id != collectionId- select new SearchModel { Id = item.Id, Name = item.Name });- return model;- }-var collections = await _collectionService.GetAllCollections(- value,- pageSize: _adminSearchSettings.CollectionSizeLimit);-- var gridModel = new DataSourceResult {- Data = await PrepareModel(collections)- };+ collectionName: model.GetNameFilterValue(),+ storeId: "",+ pageIndex: 0,+ pageSize: _adminSearchSettings.CollectionSizeLimit,+ showHidden: false+ );++ var gridModel = await DataSourceResultHelper.GetSearchResult(collectionId, collections, collection => Task.FromResult(collection.Name));return Json(gridModel);}[HttpGet]- public async Task<IActionResult> Brand(string brandId)+ public async Task<IActionResult> Brand(string brandId, DataSourceRequestFilter model){- var value = HttpContext.Request.Query["filter[filters][0][value]"].ToString();-- async Task<IList<SearchModel>> PrepareModel(IEnumerable<Brand> brands)- {- var model = new List<SearchModel>();- if (!string.IsNullOrEmpty(brandId))- {- var currentBrand = await _brandService.GetBrandById(brandId);- if (currentBrand != null)- model.Add(new SearchModel {- Id = currentBrand.Id,- Name = currentBrand.Name- });- }-- model.AddRange(from item in brands- where item.Id != brandId- select new SearchModel { Id = item.Id, Name = item.Name });- return model;- }-var brands = await _brandService.GetAllBrands(- value,- pageSize: _adminSearchSettings.BrandSizeLimit);- var gridModel = new DataSourceResult {- Data = await PrepareModel(brands)- };+ brandName: model.GetNameFilterValue(),+ storeId: "",+ pageIndex: 0,+ pageSize: _adminSearchSettings.BrandSizeLimit,+ showHidden: false+ );++ var gridModel = await DataSourceResultHelper.GetSearchResult(brandId, brands, brand => Task.FromResult(brand.Name));return Json(gridModel);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Models/Common/SearchModel.cs b/src/Web/Grand.Web.Vendor/Models/Common/SearchModel.csdeleted file mode 100644index 689f1fa82..000000000--- a/src/Web/Grand.Web.Vendor/Models/Common/SearchModel.cs+++ /dev/null@@ -1,7 +0,0 @@-namespace Grand.Web.Vendor.Models.Common;--public class SearchModel-{- public string Id { get; set; }- public string Name { get; set; }-}\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.csindex 10776fd2a..ed2c4afe8 100644--- a/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs+++ b/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs@@ -75,7 +75,7 @@ public class ShipmentViewModelService : IShipmentViewModelServicevar baseDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId);var baseDimensionIn = baseDimension != null ? baseDimension.Name : "";var order = await _orderService.GetOrderById(shipment.OrderId);-+var model = new ShipmentModel {Id = shipment.Id,ShipmentNumber = shipment.ShipmentNumber,@@ -100,7 +100,7 @@ public class ShipmentViewModelService : IShipmentViewModelServiceif (prepareProducts)foreach (var shipmentItem in shipment.ShipmentItems){- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == shipmentItem.OrderItemId);+ var orderItem = order?.OrderItems.FirstOrDefault(x => x.Id == shipmentItem.OrderItemId);if (orderItem == null)continue;@@ -142,8 +142,7 @@ public class ShipmentViewModelService : IShipmentViewModelServiceif (prepareShipmentEvent && !string.IsNullOrEmpty(shipment.TrackingNumber)){- var srcm = _shippingService.LoadShippingRateCalculationProviderBySystemName(- order.ShippingRateProviderSystemName);+ var srcm = _shippingService.LoadShippingRateCalculationProviderBySystemName(order?.ShippingRateProviderSystemName);if (srcm != null &&srcm.IsShippingRateMethodActive(_shippingProviderSettings)){diff --git a/src/Web/Grand.Web.Vendor/Validators/Common/LoginValidator.cs b/src/Web/Grand.Web.Vendor/Validators/Common/LoginValidator.csindex b08eafa25..b8cf693e4 100644--- a/src/Web/Grand.Web.Vendor/Validators/Common/LoginValidator.cs+++ b/src/Web/Grand.Web.Vendor/Validators/Common/LoginValidator.cs@@ -69,7 +69,7 @@ public class LoginValidator : BaseGrandValidator<LoginModel>translationService.GetResource("Account.Login.WrongPortal.Vendor"));break;case { CannotLoginUntilDateUtc: not null }- when customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:+ when customer!.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:context.AddFailure(translationService.GetResource("Account.Login.WrongCredentials.LockedOut"));break;case not null:diff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.csindex d4d0956e4..d243ce307 100644--- a/src/Web/Grand.Web/Controllers/CommonController.cs+++ b/src/Web/Grand.Web/Controllers/CommonController.cs@@ -151,7 +151,10 @@ public class CommonController : BasePublicControllerstring langCode, string returnUrl = ""){var language = await _languageService.GetLanguageByCode(langCode);- if (!language?.Published ?? false)+ if (language == null)+ return InvokeHttp404();++ if (!language.Published)language = _contextAccessor.WorkContext.WorkingLanguage;//prevent open redirection attackdiff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.csindex 7f303bfc3..9e8c98c22 100644--- a/src/Web/Grand.Web/Controllers/ContactController.cs+++ b/src/Web/Grand.Web/Controllers/ContactController.cs@@ -7,6 +7,7 @@ using Grand.Domain.Media;using Grand.Domain.Stores;using Grand.Infrastructure;using Grand.SharedKernel.Attributes;+using Grand.SharedKernel.Extensions;using Grand.Web.Commands.Models.Contact;using Grand.Web.Common.Controllers;using Grand.Web.Common.Extensions;@@ -116,51 +117,43 @@ public class ContactController : BasePublicController[HttpPost][DenySystemAccount]- public virtual async Task<IActionResult> UploadFileContactAttribute(string attributeId,+ public virtual async Task<IActionResult> UploadFileContactAttribute(string attributeId, IFormFile file,[FromServices] IDownloadService downloadService,[FromServices] IContactAttributeService contactAttributeService){var attribute = await contactAttributeService.GetContactAttributeById(attributeId);if (attribute is not { AttributeControlType: AttributeControlType.FileUpload })- return Json(new {+ return Json(new+ {success = false,downloadGuid = Guid.Empty});- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)- return Json(new {+ if (file == null)+ return Json(new+ {success = false,message = "No file uploaded",downloadGuid = Guid.Empty});- var fileBinary = httpPostedFile.GetDownloadBits();-- var fileName = httpPostedFile.FileName;-- fileName = Path.GetFileName(fileName);-- var contentType = httpPostedFile.ContentType;-+ var fileName = Path.GetFileName(file.FileName);+ var contentType = file.ContentType;var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions)){- var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()- .Split([','], StringSplitOptions.RemoveEmptyEntries)- .ToList();- if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))- return Json(new {+ var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.Split(',', StringSplitOptions.RemoveEmptyEntries);+ if (!allowedFileExtensions.IsAllowedMediaFileType(fileExtension))+ return Json(new+ {success = false,message = _translationService.GetResource("ContactUs.ValidationFileAllowed"),downloadGuid = Guid.Empty});}+ var fileBinary = file.GetDownloadBits();+if (attribute.ValidationFileMaximumSize.HasValue){//compare in bytes@@ -168,7 +161,8 @@ public class ContactController : BasePublicControllerif (fileBinary.Length > maxFileSizeBytes)//when returning JSON the mime-type must be set to text/plain//otherwise some browsers will pop-up a "Save As" dialog.- return Json(new {+ return Json(new+ {success = false,message = string.Format(_translationService.GetResource("ContactUs.MaximumUploadedFileSize"),attribute.ValidationFileMaximumSize.Value),@@ -176,7 +170,8 @@ public class ContactController : BasePublicController});}- var download = new Download {+ var download = new Download+ {DownloadGuid = Guid.NewGuid(),CustomerId = _contextAccessor.WorkContext.CurrentCustomer.Id,UseDownloadUrl = false,@@ -193,7 +188,8 @@ public class ContactController : BasePublicController//when returning JSON the mime-type must be set to text/plain//otherwise some browsers will pop-up a "Save As" dialog.- return Json(new {+ return Json(new+ {success = true,message = _translationService.GetResource("ContactUs.FileUploaded"),downloadUrl = Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }),diff --git a/src/Web/Grand.Web/Controllers/DownloadController.cs b/src/Web/Grand.Web/Controllers/DownloadController.csindex 7901784ff..55a68412b 100644--- a/src/Web/Grand.Web/Controllers/DownloadController.cs+++ b/src/Web/Grand.Web/Controllers/DownloadController.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Marketing.Documents;@@ -178,7 +179,7 @@ public class DownloadController : BasePublicController}return File(memoryStream.ToArray(), "application/zip",- $"{Regex.Replace(product.Name, "[^A-Za-z0-9 _]", "")}.zip");+ $"{Regex.Replace(product.Name, "[^A-Za-z0-9 _]", "", RegexOptions.Compiled, TimeSpan.FromSeconds(1))}.zip");}[HttpGet]@@ -220,13 +221,15 @@ public class DownloadController : BasePublicController}[HttpGet]- public virtual async Task<IActionResult> GetFileUpload(Guid downloadId)+ public virtual async Task<IActionResult> GetFileUpload(Guid downloadId, [FromServices] IGroupService groupService){var download = await _downloadService.GetDownloadByGuid(downloadId);if (download == null)return Content("Download is not available any more.");- if (_contextAccessor.WorkContext.CurrentCustomer == null || download.CustomerId != _contextAccessor.WorkContext.CurrentCustomer.Id)+ if (_contextAccessor.WorkContext.CurrentCustomer == null ||+ (!await groupService.IsAdmin(_contextAccessor.WorkContext.CurrentCustomer)+ && download.CustomerId != _contextAccessor.WorkContext.CurrentCustomer.Id))return Challenge();if (download.UseDownloadUrl)diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.csindex 30b5c3d56..dc45c49b2 100644--- a/src/Web/Grand.Web/Controllers/ProductController.cs+++ b/src/Web/Grand.Web/Controllers/ProductController.cs@@ -26,6 +26,7 @@ using Microsoft.AspNetCore.Mvc;using Grand.SharedKernel.Attributes;using Grand.Web.Models.Orders;using Microsoft.AspNetCore.Http;+using Grand.SharedKernel.Extensions;namespace Grand.Web.Controllers;@@ -384,7 +385,7 @@ public class ProductController : BasePublicController}[HttpPost]- public virtual async Task<IActionResult> UploadFileProductAttribute(string attributeId, string productId,+ public virtual async Task<IActionResult> UploadFileProductAttribute(string attributeId, string productId, IFormFile file,[FromServices] IDownloadService downloadService){var product = await _productService.GetProductById(productId);@@ -399,35 +400,28 @@ public class ProductController : BasePublicControllersuccess = false,downloadGuid = Guid.Empty});- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)++ if (file == null)return Json(new {success = false,message = "No file uploaded",downloadGuid = Guid.Empty});- var fileBinary = httpPostedFile.GetDownloadBits();- var fileName = httpPostedFile.FileName;-- var contentType = httpPostedFile.ContentType;-+ var fileName = file.FileName;+ var contentType = file.ContentType;var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions)){- var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()- .Split([','], StringSplitOptions.RemoveEmptyEntries)- .ToList();- if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))+ var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.Split([','], StringSplitOptions.RemoveEmptyEntries);+ if (!allowedFileExtensions.IsAllowedMediaFileType(fileExtension))return Json(new {success = false,message = _translationService.GetResource("ShoppingCart.ValidationFileAllowed"),downloadGuid = Guid.Empty});}+ var fileBinary = file.GetDownloadBits();if (attribute.ValidationFileMaximumSize.HasValue){diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.csindex e0ac28a04..bd791ddb4 100644--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs@@ -24,6 +24,7 @@ using Grand.Web.Models.ShoppingCart;using MediatR;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;+using Grand.SharedKernel.Extensions;namespace Grand.Web.Controllers;@@ -170,7 +171,7 @@ public class ShoppingCartController : BasePublicController[DenySystemAccount][HttpPost]- public virtual async Task<IActionResult> UploadFileCheckoutAttribute(string attributeId,+ public virtual async Task<IActionResult> UploadFileCheckoutAttribute(string attributeId, IFormFile file,[FromServices] IDownloadService downloadService){var attribute = await _checkoutAttributeService.GetCheckoutAttributeById(attributeId);@@ -180,32 +181,23 @@ public class ShoppingCartController : BasePublicControllerdownloadGuid = Guid.Empty});- var form = await HttpContext.Request.ReadFormAsync();- var httpPostedFile = form.Files.FirstOrDefault();- if (httpPostedFile == null)+ if (file == null)return Json(new {success = false,message = "No file uploaded",downloadGuid = Guid.Empty});- var fileBinary = httpPostedFile.GetDownloadBits();- var fileName = httpPostedFile.FileName;+ var fileName = file.FileName;fileName = Path.GetFileName(fileName);- var contentType = httpPostedFile.ContentType;-+ var contentType = file.ContentType;var fileExtension = Path.GetExtension(fileName);- if (!string.IsNullOrEmpty(fileExtension))- fileExtension = fileExtension.ToLowerInvariant();-if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions)){- var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.ToLowerInvariant()- .Split([','], StringSplitOptions.RemoveEmptyEntries)- .ToList();- if (!allowedFileExtensions.Contains(fileExtension.ToLowerInvariant()))+ var allowedFileExtensions = attribute.ValidationFileAllowedExtensions.Split([','], StringSplitOptions.RemoveEmptyEntries);+ if (!allowedFileExtensions.IsAllowedMediaFileType(fileExtension))return Json(new {success = false,message = _translationService.GetResource("ShoppingCart.ValidationFileAllowed"),@@ -213,6 +205,7 @@ public class ShoppingCartController : BasePublicController});}+ var fileBinary = file.GetDownloadBits();if (attribute.ValidationFileMaximumSize.HasValue){//compare in bytesdiff --git a/src/Web/Grand.Web/Features/Handlers/Common/GetAddressModelHandler.cs b/src/Web/Grand.Web/Features/Handlers/Common/GetAddressModelHandler.csindex ba2ce1d1b..73ae4c831 100644--- a/src/Web/Grand.Web/Features/Handlers/Common/GetAddressModelHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Common/GetAddressModelHandler.cs@@ -124,7 +124,7 @@ public class GetAddressModelHandler : IRequestHandler<GetAddressModel, AddressMo{ Text = _translationService.GetResource("Address.SelectCountry"), Value = "" });foreach (var c in loadCountries())model.AvailableCountries.Add(new SelectListItem {- Text = c.GetTranslation(x => x.Name, language.Id),+ Text = c.GetTranslation(x => x.Name, language?.Id),Value = c.Id,Selected = !string.IsNullOrEmpty(model.CountryId)? c.Id == model.CountryIddiff --git a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs b/src/Web/Grand.Web/Validators/Customer/LoginValidator.csindex 2f860515a..ebacfa551 100644--- a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs@@ -64,7 +64,7 @@ public class LoginValidator : BaseGrandValidator<LoginModel>context.AddFailure(translationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));break;case { CannotLoginUntilDateUtc: not null }- when customer.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:+ when customer!.CannotLoginUntilDateUtc.Value > DateTime.UtcNow:context.AddFailure(translationService.GetResource("Account.Login.WrongCredentials.LockedOut"));break;case not null:diff --git a/src/Web/Grand.Web/Views/Contact/Partials/ContactAttributes.cshtml b/src/Web/Grand.Web/Views/Contact/Partials/ContactAttributes.cshtmlindex e23cba858..d1ddf8f83 100644--- a/src/Web/Grand.Web/Views/Contact/Partials/ContactAttributes.cshtml+++ b/src/Web/Grand.Web/Views/Contact/Partials/ContactAttributes.cshtml@@ -142,7 +142,7 @@<script asp-location="Footer">function uploadFile(e) {var formData = new FormData();- formData.append("image", qqfile.files[0]);+ formData.append("file", e.files[0]);axios.post('@(Url.RouteUrl("UploadFileContactAttribute", new { attributeId = attribute.Id }))', formData, {headers: {'Content-Type': 'multipart/form-data'diff --git a/src/Web/Grand.Web/Views/ShoppingCart/Partials/CheckoutAttributes.cshtml b/src/Web/Grand.Web/Views/ShoppingCart/Partials/CheckoutAttributes.cshtmlindex 45f1c921c..78cb5e0a8 100644--- a/src/Web/Grand.Web/Views/ShoppingCart/Partials/CheckoutAttributes.cshtml+++ b/src/Web/Grand.Web/Views/ShoppingCart/Partials/CheckoutAttributes.cshtml@@ -100,7 +100,7 @@var url = imagefile.getAttribute('data-url');let attrId = e.getAttribute("attribute");- formData.append("image", qqfile.files[0]);+ formData.append("file", e.files[0]);axios.post(url, formData, {headers: {'Content-Type': 'multipart/form-data'diff --git a/src/Web/Grand.Web/wwwroot/theme/script/app.js b/src/Web/Grand.Web/wwwroot/theme/script/app.jsindex e67dcc8a8..cd621ffb4 100644--- a/src/Web/Grand.Web/wwwroot/theme/script/app.js+++ b/src/Web/Grand.Web/wwwroot/theme/script/app.js@@ -446,7 +446,7 @@ var vm = new Vue({var formData = new FormData();var imagefile = e;var url = imagefile.getAttribute('data-url');- formData.append("image", qqfile.files[0]);+ formData.append("file", e.files[0]);axios.post(url, formData, {headers: {'Content-Type': 'multipart/form-data'